You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Keras MNIST自定义数字预测维度不匹配问题求助

Fixing the Dimension Mismatch for Keras MNIST Custom Prediction

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:

  1. First, check your current shape (to confirm the issue):

    print(custom_img.shape)  # Should output (1, 28, 28)
    
  2. 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 used expand_dims on 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)
    
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 06:55:51