当我在Python中使用TensorFlow的神经网络进行预测时,出现了以下错误:ValueError: Input 0 of layer dense is incompatible with the layer: expected axis -1 of input shape to have value 784 but received input with shape [None, 28]
。
我正在尝试按照TensorFlow网站上的教程训练一个神经网络来分类衣物。我编写了以下代码:
import tensorflow as tffrom tensorflow import kerasimport matplotlib.pyplot as pltimport numpy as npfrom skimage import color, ioprint(tf.__version__)data = keras.datasets.fashion_mnist(train_images, train_labels), (test_images, test_labels) = data.load_data()class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']train_images = train_images / 255test_images = test_images / 255model = keras.Sequential([ keras.layers.Flatten(input_shape=(28, 28)), keras.layers.Dense(128, activation="relu"), keras.layers.Dense(10, activation="softmax")])model.compile( optimizer="adam", loss="sparse_categorical_crossentropy", metrics=["accuracy"])model.fit(train_images, train_labels, epochs=20)print(type(test_images))images = [test_images[0]]predictions = model.predict(images)print(class_names[np.argmax(predictions[0])])
任何帮助都将不胜感激,提前感谢。
回答:
为了社区的利益,从评论部分分享解决方案。
通过将model.predict(images)
更改为以下代码行已解决问题。
model.predict(np.expand_dims(test_images[0],0))