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

使用Keras进行手写数字预测时遭遇输入形状不兼容错误

MNIST模型预测时输入形状不兼容问题解决

原代码

import tensorflow as tf
import matplotlib.pyplot as plt

(input_train, output_train) , (input_test, output_test) = tf.keras.datasets.mnist.load_data()

input_train = input_train/255
input_test = input_test/255

input_train = input_train.reshape(60000, 784)
input_test = input_test.reshape(10000, 784)
input_train.shape

model = tf.keras.models.Sequential([
           tf.keras.layers.Dense(784, activation='sigmoid', input_shape=(784,)),
           tf.keras.layers.Dense(128, activation='relu'),
           tf.keras.layers.Dense(10, activation='softmax'),
                       
])


model.compile( optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])

model.fit(input_train, output_train, epochs=10, batch_size=128)

model.predict(input_test[2])

报错信息

WARNING:tensorflow:Model was constructed with shape (None, 784) for input KerasTensor(type_spec=TensorSpec(shape=(None, 784), dtype=tf.float32, name='dense_9_input'), name='dense_9_input', description="created by layer 'dense_9_input'"), but it was called on an input with incompatible shape (None,).
WARNING:tensorflow:Model was constructed with shape (None, 784) for input KerasTensor(type_spec=TensorSpec(shape=(None, 784), dtype=tf.float32, name='dense_9_input'), name='dense_9_input', description="created by layer 'dense_9_input'"), but it was called on an input with incompatible shape (None,).

ValueError Traceback (most recent call last)
in ()
----> 1 model.predict([[input_test[2]]])

1 frames
/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_graph.py in autograph_handler(*args, **kwargs)
1145 except Exception as e: # pylint:disable=broad-except
1146 if hasattr(e, "ag_error_metadata"):
-> 1147 raise e.ag_error_metadata.to_exception(e)
1148 else:
1149 raise

ValueError: in user code:

File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1801, in predict_function  *
    return step_function(self, iterator)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1790, in step_function  **
    outputs = model.distribute_strategy.run(run_step, args=(data,))
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1783, in run_step  **
    outputs = model.predict_step(data)
File "/usr/local/lib/python3.7/dist-packages/keras/engine/training.py", line 1751, in predict_step
    return self(x, training=False)
File "/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py", line 67, in error_handler
    raise e.with_traceback(filtered_tb) from None
File "/usr/local/lib/python3.7/dist-packages/keras/engine/input_spec.py", line 228, in assert_input_compatibility
    raise ValueError(f'Input {input_index} of layer "{layer_name}" '

ValueError: Exception encountered when calling layer "sequential_3" (type Sequential).

Input 0 of layer "dense_9" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)

Call arguments received:
  • inputs=(('tf.Tensor(shape=(None,), dtype=float32)',),)
  • training=False
  • mask=None

问题原因

模型定义时,输入层指定input_shape=(784,),意味着模型接收的输入必须是2维张量,格式为(批次大小, 784),其中批次大小可以是任意正整数(对应日志里的None)。但执行model.predict(input_test[2])时,input_test[2]的形状是(784,),属于1维张量,缺少批次维度,导致输入形状不匹配。

解决方法

方法1:为单个样本添加批次维度

通过以下两种方式给单个样本补上批次维度,让输入形状变为(1, 784):

# 方式A:使用numpy的expand_dims方法
import numpy as np
model.predict(np.expand_dims(input_test[2], axis=0))

# 方式B:手动将样本包裹成二维列表/数组
model.predict([input_test[2]])

方法2:直接预测多个样本

如果需要预测多个样本,直接传入切片后的数组即可,切片后的形状为(样本数量, 784),符合模型要求:

# 预测索引2、3、4的三个样本
model.predict(input_test[2:5])

内容的提问来源于stack exchange,提问作者Osama Mohammed

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:37:14