使用Keras Sequential模型预测图像时遇ValueError的解决方法
我用Fashion MNIST数据集训练了一个模型,执行图像类别预测时运行代码prediction = model.predict(image)出现了ValueError,已经按步骤预处理测试图像但问题依然存在,求修复建议。
错误信息
ValueError: in user code:
File "c:\Users\mkcor\anaconda3\Lib\site-packages\keras\src\engine\training.py", line 2440, in predict_function *
...
Call arguments received by layer 'sequential' (type Sequential):
• inputs=tf.Tensor(shape=, dtype=float32)
• training=False
• mask=None
模型代码
model = keras.models.Sequential([ keras.layers.Flatten(), keras.layers.Dense(512, activation='relu'), keras.layers.Dropout(0.2), keras.layers.Dense(10, activation='softmax') ]) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']) model.fit(train_images, train_labels, epochs=5)
已尝试的预处理步骤
from keras.preprocessing import image import numpy as np # Load the image img_path = 'image.jpg' # Load and resize image to match Fashion MNIST img = image.load_img(img_path, target_size=(28, 28), color_mode='grayscale') # Convert image to array and normalize img_array = image.img_to_array(img) img_array /= 255.0 # Normalize pixel values # Reshape the image for model prediction img_input = np.expand_dims(img_array, axis=0)
修复建议
从错误信息看,输入张量的shape为空,说明模型接收的输入维度不匹配,结合代码细节,可按以下方向排查修复:
修正预测时的传入变量
你预处理后得到的是img_input,但预测代码写的是model.predict(image)——大概率是变量名写错了,应该传入处理好的img_input而非原始image对象。修正代码:prediction = model.predict(img_input)确认输入张量维度是否正确
Fashion MNIST训练数据的维度是(样本数, 28, 28, 1)(单通道灰度图),预处理后的img_input应是(1, 28, 28, 1)。可在预测前打印维度确认:print(img_input.shape) # 正常输出应为(1, 28, 28, 1)如果维度缺失(比如是
(1,28,28)),手动补充通道和样本维度:img_input = np.expand_dims(img_array, axis=-1) # 增加通道维度 img_input = np.expand_dims(img_input, axis=0) # 增加样本维度匹配图像像素明暗方向
Fashion MNIST的图像是黑底白字(背景为0,前景为1),你加载的图片可能是白底黑字,会导致特征反向影响预测。可反转像素值:img_array = 1.0 - img_array明确模型输入层形状
你的模型第一层Flatten()未指定input_shape,训练时虽能自动推断,但预测时易因输入维度歧义报错。建议定义模型时明确输入形状:model = keras.models.Sequential([ keras.layers.Flatten(input_shape=(28, 28, 1)), # 明确输入维度 keras.layers.Dense(512, activation='relu'), keras.layers.Dropout(0.2), keras.layers.Dense(10, activation='softmax') ])
内容的提问来源于stack exchange,提问作者Mamo

