keras ValueError:层“model_3”的输入0与该层不兼容:预期形状=(None,224,224,3),找到的形状=(32,224,3)

bxfogqkk  于 2023-08-06  发布在  其他
关注(0)|答案(1)|浏览(151)

我有以下代码:

model = DeepFace.build_model('VGG-Face')
print(img.shape) # (224, 224, 3)
print(model.input_shape) # (None, 224, 224, 3)
representation = model.predict(img)
print(representation)
return representation

字符串
但我得到了以下错误:

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


那么,我如何将img重塑为(None,224,224,3)
谢啦,谢啦

wljmcqd8

wljmcqd81#

如@ fritera所示,为预测准备Tensor的方法是np.expand_dims()
假设我们的模型看起来像这样

Model: "model_3"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
input_5 (InputLayer)         [(None, 224, 224, 3)]     0         
_________________________________________________________________
sequential (Sequential)      (None, 224, 224, 3)       0         
_________________________________________________________________
vggface_resnet50 (Functional (None, 1, 1, 2048)        23561152  
_________________________________________________________________
flatten (Flatten)            (None, 2048)              0         
_________________________________________________________________
classifier (Dense)           (None, 8)                 16392     
=================================================================
Total params: 23,577,544
Trainable params: 16,392
Non-trainable params: 23,561,152
_________________________________________________________________

字符串
假设这是VGGFace,那么我们需要确保图像是224 x224 x3,并且我们需要添加这个“批处理”维度。(假设我们已经用PIL.Image.open()加载了图像)
我们可以准备图像:

def prepPred(someImage, resizeTarget=224):
    """Prepare Image for prediction"""
    someImage = someImage.resize((resizeTarget, 
                                  resizeTarget), 
                                 pillowImageLoader.BILINEAR)
    # Convert image to array
    imageArray = np.array(someImage)
    # add the batch dimension and return
    return np.expand_dims(imageArray, axis=0)


模型总是期望批次-当你训练时,你提供批次,当你预测时,你必须提供批次-在这种情况下,它只是一个1的“批次”。

相关问题