使用TensorFlow进行预测时出现错误:预期输入形状的轴-1应为784,但接收到的输入形状为[None, 28]

当我在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))

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注