ValueError:`decode_predictions`期望进行一系列预测(即2D形状的数组(样本,1000个))。找到形状为(1,7)的数组

Aar*_*nDT 3 python machine-learning conv-neural-network keras pre-trained-model

我正在将VGG16与keras一起用于迁移学习(我的新模型中有7个类),因此我想使用内置的encode_predictions方法输出模型的预测。但是,使用以下代码:

preds = model.predict(img)

decode_predictions(preds, top=3)[0]
Run Code Online (Sandbox Code Playgroud)

我收到以下错误消息:

ValueError:decode_predictions需要进行一系列预测(例如,二维形状数组(样本,1000个))。找到形状为(1,7)的数组

现在,我想知道为什么在重新训练的模型中只有7个班级时会期望1000。

我在stackoverflow上发现的一个类似问题(Keras:ValueError:decode_predictions期望进行一系列预测 )建议在模型定义中包括“ inlcude_top = True”以解决此问题:

model = VGG16(weights='imagenet', include_top=True)
Run Code Online (Sandbox Code Playgroud)

我已经尝试过了,但是仍然无法正常工作-给我和以前一样的错误。非常感谢您对如何解决此问题的任何提示或建议。

Ioa*_*ios 6

我怀疑您正在使用一些预先训练的模型,例如说resnet50,并且您正在decode_predictions像这样导入:

from keras.applications.resnet50 import decode_predictions
Run Code Online (Sandbox Code Playgroud)

encode_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)
...
Run Code Online (Sandbox Code Playgroud)

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