检查输入时出错:预期 conv2d_17_input 有 4 个维度,但得到形状为 (28, 28, 1) 的数组

Error when checking input: expected conv2d_17_input to have 4 dimensions, but got array with shape (28, 28, 1)

我已经从 MNIST 训练了一个手写数字识别模型。 第一个 Conv2D 的输入形状是 (28, 28, 1) 训练结束后,我想预测下载的数字图像。 图像的形状是 (1024, 791, 3),在应用以下代码后,我将图像的大小调整为 (28,28,1) 并调用 model.predict() :

resized_image = cv2.resize(image, (28, 28))
#resized_image = tf.image.resize(image, size = (28,28))
resized_image = resized_image / 225.0
resized_image = resized_image[:,:,:1] 
prediction = model.predict(resized_image)
#prediction = model.predict(resized_image, batch_size = 1, verbose = 1, steps = 1)
print(labels[np.argmax(prediction)])

但我收到以下错误:

Error when checking input: expected conv2d_17_input to have 4 dimensions, but got array with shape (28, 28, 1)

型号是:

model = tf.keras.models.Sequential([
    tf.keras.layers.Conv2D(filters = 32, kernel_size = (3,3), padding = 'Same', activation = 'relu', input_shape = (28,28,1)),
    tf.keras.layers.MaxPool2D(pool_size = (2,2)),
    tf.keras.layers.Conv2D(filters = 64, kernel_size = (3,3), padding = 'Same', activation = 'relu'),
    tf.keras.layers.MaxPool2D(pool_size = (2,2)),
    tf.keras.layers.Flatten(),
    tf.keras.layers.Dense(128, activation = 'relu'),
    tf.keras.layers.Dense(10, activation = "softmax")
])

我也试过取消注释

resized_image = tf.image.resize(image, size = (28,28))
prediction = model.predict(resized_image, batch_size = 1, verbose = 1, steps = 1)

但是我收到了同样的错误。

您没有显示您的型号,但通常情况下,您需要考虑批次。因此,您的输入必须是 [batch_size, width, height, channel]。如果你只有一张图片,你必须设置 batch_size=1,在你的情况下,[1, 28, 28, 1].

此外,请确保您的输入是 tf.tensor