我在使用 Keras 的 VGG16 进行迁移学习(我的新模型有7个类别),因此我想使用内置的 decode_predictions 方法来输出我的模型预测结果。然而,使用以下代码时:
preds = model.predict(img)decode_predictions(preds, top=3)[0]
我收到了以下错误信息:
ValueError:
decode_predictions
期望得到一批预测结果(即形状为(样本数,1000)的二维数组)。发现的数组形状为:(1, 7)
现在我想知道为什么它期望有1000个类别,而我的重新训练模型只有7个类别。
我在 StackOverflow 上找到了一个类似的问题(Keras: ValueError: decode_predictions expects a batch of predictions),建议在定义模型时包含 ‘include_top=True’ 来解决这个问题:
model = VGG16(weights='imagenet', include_top=True)
我已经尝试过这个方法,但它仍然不起作用 – 给我相同的错误。任何关于如何解决这个问题的提示或建议都将不胜感激。
回答:
我怀疑你在使用某个预训练模型,比如说 ResNet50,并且你像这样导入 decode_predictions
:
from keras.applications.resnet50 import decode_predictions
decode_predictions 将一个形状为(样本数,1000)的概率数组转换为原始 ImageNet 类别的类名。
如果你想进行迁移学习并在7个不同的类别之间进行分类,你需要这样做:
base_model = resnet50 (weights='imagenet', include_top=False)# 添加全局空间平均池化层x = base_model.outputx = GlobalAveragePooling2D()(x)# 添加全连接层x = Dense(1024, activation='relu')(x)# 添加逻辑层 -- 假设我们有7个类别predictions = Dense(7, activation='softmax')(x) model = Model(inputs=base_model.input, outputs=predictions)...
在拟合模型并计算预测结果后,你必须手动将类名分配给输出数字,不使用导入的 decode_predictions