[英]How to fix: ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (28, 28)
I'm trying to input my own image into the mnist model 我正在尝试将自己的图像输入到mnist模型中
mnist = tf.keras.datasets.mnist
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train, x_test = x_train / 255.0, x_test / 255.0
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, activation='softmax')
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5)
model.evaluate(x_test, y_test)
model.predict(gray)
gray is an image that is of shape (28,28) but I am getting an error stating that the model expects 3 dimensions even though the input shape is (28,28). 灰色是形状为(28,28)的图像,但是我收到一个错误,指出即使输入形状为(28,28),该模型也需要3个尺寸。
The code works if I do gray.reshape(1,28,28) but I don't know why that works or if that is even the correct solution to this problem. 如果我执行gray.reshape(1,28,28),该代码将起作用,但是我不知道为什么会起作用,或者这是否是此问题的正确解决方案。
The model
instance expects a batch of images. 该
model
实例需要一批图像。 This is specified on this line: 这是在此行上指定的:
tf.keras.layers.Flatten(input_shape=(28, 28))
When you specify the input_shape=(28, 28)
, you are basically telling Tensorflow that you will receive a batch of inputs, where each element in the batch will have shape 28 x 28
. 当您指定
input_shape=(28, 28)
,您基本上是在告诉Tensorflow您将收到一批输入,其中批处理中的每个元素都将具有28 x 28
形状。 So, when you add your image, make sure to expand its dimensions: 因此,添加图像时,请确保扩大其尺寸:
gray = np.expand_dims(gray, axis=0)
Then, you can safely do: 然后,您可以放心地执行以下操作:
model.predict(gray)
Besides, in this particular case you are fine using np.reshape
. 此外,在这种情况下,您可以使用
np.reshape
。 However, that method serves a different purpose so I would stick to np.expand_dims
. 但是,该方法有不同的用途,因此我会坚持使用
np.expand_dims
。 Here is proof to see that they are equal: 这是证明它们相等的证明:
X = np.random.rand(28, 28)
np.testing.assert_array_equal(np.expand_dims(X, axis=0), np.reshape(X (1, 28, 28)))
# The assert passes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.