[英]How to fix problem 'Error when checking input: expected flatten_7_input to have shape (28, 28) but got array with shape (28, 3)'
[英]How to fix: ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (28, 28)
我正在嘗試將自己的圖像輸入到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)
灰色是形狀為(28,28)的圖像,但是我收到一個錯誤,指出即使輸入形狀為(28,28),該模型也需要3個尺寸。
如果我執行gray.reshape(1,28,28),該代碼將起作用,但是我不知道為什么會起作用,或者這是否是此問題的正確解決方案。
該model
實例需要一批圖像。 這是在此行上指定的:
tf.keras.layers.Flatten(input_shape=(28, 28))
當您指定input_shape=(28, 28)
,您基本上是在告訴Tensorflow您將收到一批輸入,其中批處理中的每個元素都將具有28 x 28
形狀。 因此,添加圖像時,請確保擴大其尺寸:
gray = np.expand_dims(gray, axis=0)
然后,您可以放心地執行以下操作:
model.predict(gray)
此外,在這種情況下,您可以使用np.reshape
。 但是,該方法有不同的用途,因此我會堅持使用np.expand_dims
。 這是證明它們相等的證明:
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.