python - 使用经过训练的 TensorFlow 模型预测单个 PNG 图像

标签 python tensorflow machine-learning

import tensorflow as tf
model = tf.keras.models.Sequential([
    tf.keras.layers.Flatten(input_shape = (28,28)),
    tf.keras.layers.Dense(128, activation = 'relu'),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10)
]) 

这是模型的代码,我使用 mnist 数据集对其进行了训练。我想做的是将 28x28 png 图像传递给 Predict() 方法,该方法不起作用。预测代码为:

img = imageio.imread('image_0.png')
prediction = model.predict(img, batch_size = 1)

产生错误

ValueError: Error when checking input: expected flatten_input to have shape (28, 28) but got array with shape (28, 3)

我已经被这个问题困扰了几天,但我找不到将图像传递到预测方法的正确方法。有什么帮助吗?

最佳答案

预测函数对一批图像进行预测。您应该在您的 img 中包含批处理维度(第一维度),甚至是为了预测单个示例。 你需要这样的东西:

img = imageio.imread('image_0.png')
img = np.expand_dims(img, axis=0)
prediction = model.predict(img)

正如@desertnaut所说,似乎您使用的是RGB图像,因此您的第一层应该使用input_shape = (28,28,3)。因此,预测函数的 img 参数应具有 (1,28,28,3) 形状。

在您的情况下,预测函数的 img 参数具有 (28,28,3) 形状,因此预测函数将第一个维度作为图像数量,并且无法将其他两个维度与第一层的input_shape

关于python - 使用经过训练的 TensorFlow 模型预测单个 PNG 图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61685285/

相关文章:

python - 将 python 编译为单个 .exe,为什么这么难?

python - 列表切片如何与 __getitem__ Hook ?

tensorflow - tensorflow 急切模块中的错误

python - Keras 预测一个数字,如果在一个范围内则通过

python - scikit-learn 谱聚类的输入值可以是负值吗?

java - 是否有可以从 Hudson/Jenkins 获取工件的 Ant 任务?

TensorFlow 嵌入查找

python-3.x - 如何预处理数据并将其输入keras模型?

python - 使用我的分类器和数据试用 scikit 学习示例

python - 为什么 selenium 在这个 div 中找不到任何东西?