我正在使用 Keras 的预训练模型 VGG16,按照这个链接的指导:Keras VGG16。我试图将预测输出解码成图像中内容的文字描述:
model = VGG16(weights='imagenet', include_top=False)img_path = 'elephant.jpg'img = image.load_img(img_path, target_size=(224, 224))x = image.img_to_array(img)x = np.expand_dims(x, axis=0)x = preprocess_input(x)features = model.predict(x)(inID, label) = decode_predictions(features)[0] #ERROR HERE
完整的错误信息是:
ValueError:
decode_predictions
期望一批预测结果(即形状为 (samples, 1000) 的二维数组)。发现的数组形状为:(1, 7, 7, 512)
任何评论或建议都将不胜感激。谢谢。
回答:
您应该将第一行改为:
model = VGG16(weights='imagenet', include_top=True)
如果没有这一行,您的模型将生成 512 个特征图,每个图的大小为 7 x 7 像素。这就是您遇到错误的原因。