ResNet: ValueError: Input 0 is incompatible with layer model_7

ResNet: ValueError: Input 0 is incompatible with layer model_7

我训练了我的 ResNet101V2 模型 (keras) 并保存了模型。在加载模型并尝试对新图像进行分类时,我不断收到错误消息:ValueError: Input 0 is incompatible with layer model_7: expected shape=(None, 255, 255, 3), found shape=(None, 255, 3)

这是我的代码:

load_path = 'path to my model'
model = keras.models.load_model(load_path)

image_path = 'path to my image'
img_np = cv2.imread(image_path, cv2.IMREAD_COLOR)
resized_img_np = cv2.resize(img_np, (255, 255))
print(resized_img_np.shape) # <============= PRINTS (255, 255, 3)

prediction = model.predict(resized_img_np) # <========= ERROR

您需要添加一个额外的维度to match with batch size。使用 np.expand_dims 向调整后的图像添加一个维度,并传递给模型进行预测。

resized_img_np = np.expand_dims(resized_img_np,axis=0)
prediction = model.predict(resized_img_np)

由于模型是按批次训练的,因此您必须为单个样本添加批次值 1, 错误表明大小应该是:

(None, 255, 255, 3)

其中 None 显示不同的批量大小。

您可以简单地通过添加“1”作为输入图像的第一个维度来解决这个问题,表明您将只对一个图像进行分类。

形状而不是 (255, 255, 3) 应该是:

import numpy as np

resized_img_np = cv2.resize(np.array(img_np), (255, 255))
resized_img_np = np.expand_dims(resized_img_np, axis=0)