Keras MNIST自定义数字预测维度不匹配问题求助
Hey there, let's work through this dimension mismatch issue together—it's a common hiccup when moving from training on the standard MNIST dataset to using your own custom images!
The Root Cause
Your Conv2D layer expects input in the format (28, 28, 1) (height, width, number of channels; the 1 is for grayscale). But your input array has a shape of (1, 28, 28)—this means you've got the channel dimension stuck in the first position instead of the last, and you might be missing the explicit batch dimension that Keras expects for predictions.
Step-by-Step Fix
Let's assume your input array is named custom_img. Here's how to reshape it correctly using NumPy:
First, check your current shape (to confirm the issue):
print(custom_img.shape) # Should output (1, 28, 28)Reshape to match the model's expected format:
Depending on how you ended up with(1, 28, 28), pick one of these approaches:Scenario 1: You accidentally added the channel dimension first
If your original image was a 28x28 grayscale array and you incorrectly added the channel axis at the start:
import numpy as np # Move the channel dimension to the end: (1,28,28) → (28,28,1) img_chan_last = custom_img.transpose(1, 2, 0) # Add the batch dimension (required for model.predict()) final_img = np.expand_dims(img_chan_last, axis=0)Scenario 2: You squeezed the image into (1,28,28) from a 28x28 array
If your original image was
(28,28)and you usedexpand_dimson axis 0 by mistake:import numpy as np # Remove the extra first dimension: (1,28,28) → (28,28) img_squeezed = np.squeeze(custom_img, axis=0) # Add the channel dimension at the end: (28,28) → (28,28,1) img_chan_last = np.expand_dims(img_squeezed, axis=-1) # Add the batch dimension final_img = np.expand_dims(img_chan_last, axis=0)Verify the final shape:
print(final_img.shape) # Should output (1, 28, 28, 1)
Why This Works
Keras (with TensorFlow backend) uses the channels_last data format by default. This means inputs need to follow the order:(number_of_samples, height, width, number_of_channels)
Your original array had the channel dimension in the wrong spot, and without the explicit batch dimension, the model couldn't map your input to its expected input shape.
Test It Out
Now you can pass final_img to your model's predict method without errors:
prediction = model.predict(final_img)
内容的提问来源于stack exchange,提问作者Luke Johnston

