首页 文章

ValueError:`decode_predictions`需要一批预测(即2D形状阵列(样本,1000)) . 找到形状有阵列:(1,7)

提问于
浏览
2

我正在使用带有keras的VGG16进行传输学习(我的新模型中有7个类),因此我想使用内置的decode_predictions方法输出模型的预测 . 但是,使用以下代码:

preds = model.predict(img)

decode_predictions(preds, top=3)[0]

我收到以下错误消息:

ValueError:decode_predictions需要一批预测(即2D形状阵列(样本,1000)) . 找到形状有阵列:(1,7)

现在我想知道为什么当我在再培训模型中只有7个 class 时它会预期为1000 .

我在stackoverflow(Keras: ValueError: decode_predictions expects a batch of predictions)上找到的类似问题建议在模型定义中包含'inlcude_top=True'来解决此问题:

model = VGG16(weights='imagenet', include_top=True)

我试过这个,但它仍然无法正常工作 - 给我一样的错误 . 任何有关如何解决此问题的提示或建议都非常感谢 .

1 回答

  • 3

    我怀疑你正在使用一些预先训练好的模型,比方说resnet50你正在导入 decode_predictions ,如下所示:

    from keras.applications.resnet50 import decode_predictions
    

    decode_predictions将(num_samples,1000)概率的数组转换为原始imagenet类的类名 .

    如果你想转换学习并在7个不同的类之间进行分类,你需要这样做:

    base_model = resnet50 (weights='imagenet', include_top=False)
    
    # add a global spatial average pooling layer
    x = base_model.output
    x = GlobalAveragePooling2D()(x)
    # add a fully-connected layer
    x = Dense(1024, activation='relu')(x)
    # and a logistic layer -- let's say we have 7 classes
    predictions = Dense(7, activation='softmax')(x) 
    model = Model(inputs=base_model.input, outputs=predictions)
    ...
    

    在拟合模型并计算预测后,您必须使用导入的 decode_predictions 手动将类名分配给输出编号 without

相关问题