【问题标题】:Why does Keras model predict function report warning and error about wrong shape of a image?为什么 Keras 模型预测函数会报告有关图像形状错误的警告和错误?
【发布时间】:2021-08-18 07:48:18
【问题描述】:

我是 tensorflow 新手,我尝试使用 Keras MNIST 数据集来训练中性网络。但是当我在 fit() 函数之后调用 model.predict() 函数时,tensorflow 报告了如下所示的 WARNING 和 ERROR:

WARNING:tensorflow:Model 是用 shape (None, 28, 28) 作为输入 Tensor("flatten_input:0", shape=(None, 28, 28), dtype=float32) 构建的,但它是在一个形状不兼容的输入(无,28)。

ValueError:密集层的输入 0 与层不兼容:输入形状的预期轴 -1 具有值 784,但接收到形状为 [None, 28] 的输入

这是我的代码:

(train_images, train_labels), (test_images, test_labels) = keras.datasets.fashion_mnist.load_data()

model = keras.Sequential()
model.add(keras.layers.Flatten(input_shape=(28,28)))
model.add(keras.layers.Dense(128, activation=tf.nn.relu))
model.add(keras.layers.Dense(10,activation=tf.nn.softmax))

train_images_scaled = train_images/255
model.compile(optimizer=tf.optimizers.Adam(), loss=tf.losses.sparse_categorical_crossentropy, metrics=['accuracy'])

model.fit(train_images_scaled, train_labels, epochs=5)

model.predict(test_images[2]) #Error here

我使用 test_images[2].shape 检查了 test_images[2] 的形状 确实,形状是 (28, 28)。

我真的很困惑,这里有什么帮助吗?

【问题讨论】:

  • 您忘记了第一个维度(批量维度)。实际上 test_images[2] 的形状应该是 (1,28,28)。因为您传递了 1 个样本。
  • 改成这样:model.predict(np.reshape(test_image[2],(1,28,28)))

标签: python tensorflow keras


【解决方案1】:

问题是说test_images[2] 您正在删除批次维度。预测适用于批量而不是单个图像。因此,要预测单个图像,您应该传递形状为 (1, 28, 28) 而不是 (28, 28) 的东西。您可以尝试model.predict(np.expand_dims(test_images[2], 0))[0],它将重新添加批处理维度。另请注意,预测返回一个预测列表,这就是您需要从返回结果中获取第一个元素的原因。

【讨论】:

    猜你喜欢
    • 2016-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-21
    • 2011-11-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多