[英]ResNet: ValueError: Input 0 is incompatible with layer model_7
I have trained my ResNet101V2 model (keras) and have saved the model.我已经训练了我的 ResNet101V2 model (keras) 并保存了 model。 On loading the model and trying to classify a new image, I keep getting the error: ValueError: Input 0 is incompatible with layer model_7: expected shape=(None, 255, 255, 3), found shape=(None, 255, 3)
在加载 model 并尝试对新图像进行分类时,我不断收到错误消息: ValueError: Input 0 is incompatible with layer model_7: expected shape=(None, 255, 255, 3), found shape=(None, 255, 3)
Here's my code:这是我的代码:
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
You need to add an extra dimension to match with batch size
.您需要添加一个额外的维度to match with batch size
。 Add a dimension using np.expand_dims to the resized image and pass to model for predictionion.使用np.expand_dims为调整大小的图像添加一个维度,并传递给 model 进行预测。
resized_img_np = np.expand_dims(resized_img_np,axis=0)
prediction = model.predict(resized_img_np)
As the model was trained on batches you have to add a batch value of 1 for a single sample, the error indicated that the size should be:由于 model 是在批次上进行训练的,因此您必须为单个样本添加 1 的批次值,错误表明大小应为:
(None, 255, 255, 3)
Where the None
shows the varying batchsize.其中None
显示不同的批量大小。
You can simply solve this by adding a "1" as the first dimension of your input image, showing that you are going to classify only one image.您可以通过添加“1”作为输入图像的第一个维度来简单地解决此问题,这表明您将只对一个图像进行分类。
Where the shape instead of (255, 255, 3)
would be:其中形状而不是(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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.