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

Fashion MNIST模型预测新图片时出现输入形状不兼容错误求助

解决Fashion MNIST模型预测外部图片的形状不兼容问题

错误原因

错误核心提示:

ValueError: Input 0 of layer "sequential" is incompatible with the layer: expected shape=(None, 28, 28), found shape=(None, 28, 3)

问题出在输入数据的维度和通道数不匹配:

  • 训练时的Fashion MNIST数据集是28x28的单通道灰度图,模型输入层定义为input_shape=(28, 28)
  • 读取的外部图片是3通道RGB图,且尺寸大概率不是28x28,导致模型无法处理。

解决步骤

需要对外部图片做三个关键预处理,使其匹配模型的输入要求:

  1. 将RGB图转为单通道灰度图
  2. 调整图片尺寸为28x28
  3. 归一化像素值,并添加batch维度(模型要求输入格式为(batch_size, 28, 28))

修改后的预测代码段

替换原代码中从读取图片到预测的部分:

# 读取图片并执行预处理
img = cv.imread("shoes.png")
# 转为灰度图
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
# 调整尺寸至28x28,匹配训练数据规格
img_resized = cv.resize(img_gray, (28, 28))
# 归一化像素值到0-1区间,并添加batch维度(模型需要批量输入格式)
img_input = np.expand_dims(img_resized / 255.0, axis=0)

# 可选:可视化处理后的图片,确认预处理效果
plt.imshow(img_resized, cmap=plt.cm.binary)
plt.show()

# 执行预测
prediction = model.predict(img_input)
index = np.argmax(prediction)
print(f"Prediction is {class_names[index]}")

完整可运行代码

如果需要整合后的完整代码,替换预处理部分即可:

import numpy as np
import matplotlib.pyplot as plt
import cv2 as cv
import tensorflow as tf
from tensorflow.keras import datasets, layers, models

fashion_mnist = tf.keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

train_images, test_images = train_images / 255, test_images / 255

model = tf.keras.Sequential([
    tf.keras.layers.Flatten(input_shape=(28, 28)),
    tf.keras.layers.Dense(128, activation='relu'),
    tf.keras.layers.Dense(10)
])

model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])

model.fit(train_images, train_labels, epochs=10)

test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

print('\nTest accuracy:', test_acc)

probability_model = tf.keras.Sequential([model,
                                         tf.keras.layers.Softmax()])

predictions = probability_model.predict(test_images)

predictions[0]

model.save("image_classifier.model")
model = models.load_model("image_classifier.model")

# -------------------------- 预处理与预测部分 --------------------------
img = cv.imread("shoes.png")
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img_resized = cv.resize(img_gray, (28, 28))
img_input = np.expand_dims(img_resized / 255.0, axis=0)

plt.imshow(img_resized, cmap=plt.cm.binary)
plt.show()

prediction = model.predict(img_input)
index = np.argmax(prediction)
print(f"Prediction is {class_names[index]}")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 05:45:39