ValueError:`decode_predictions`需要一批预测(即2D形状的数组(样本,1000个)).找到形状为(1,7)的数组 [英] ValueError: `decode_predictions` expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 7)
问题描述
我正在将VGG16与keras一起用于迁移学习(我的新模型中有7个类),因此,我想使用内置的encode_predictions方法输出我的模型的预测.但是,使用以下代码:
I am using VGG16 with keras for transfer learning (I have 7 classes in my new model) and as such I want to use the build-in decode_predictions method to output the predictions of my model. However, using the following code:
preds = model.predict(img)
decode_predictions(preds, top=3)[0]
我收到以下错误消息:
ValueError:
decode_predictions
期望进行一系列预测(即2D形状的数组(样本,1000个)).找到形状为(1,7)
ValueError:
decode_predictions
expects a batch of predictions (i.e. a 2D array of shape (samples, 1000)). Found array with shape: (1, 7)
现在,我想知道为什么在重新训练的模型中只有7个类时会期望1000.
Now I wonder why it expects 1000 when I only have 7 classes in my retrained model.
我在stackoverflow上发现了一个类似的问题( Keras: ValueError:decode_predictions需要一批预测 )建议在模型定义中包含"inlcude_top = True"以解决此问题:
A similar question I found here on stackoverflow (Keras: ValueError: decode_predictions expects a batch of predictions ) suggests to include 'inlcude_top=True' upon model definition to solve this problem:
model = VGG16(weights='imagenet', include_top=True)
我已经尝试过了,但是仍然无法正常工作-给我和以前一样的错误.对于如何解决此问题的任何提示或建议,我们深表感谢.
I have tried this, however it is still not working - giving me the same error as before. Any hint or suggestion on how to solve this issue is highly appreciated.
推荐答案
我怀疑您使用的是预先训练的模型,例如说resnet50,并且您正在导入decode_predictions
,如下所示:
i suspect you are using some pre-trained model, let's say for instance resnet50 and you are importing decode_predictions
like this:
from keras.applications.resnet50 import decode_predictions
decode_predictions将(num_samples,1000)个概率数组转换为原始imagenet类的类名.
decode_predictions transform an array of (num_samples, 1000) probabilities to class name of original imagenet classes.
如果您想在7个不同的班级之间进行学习和分类,您需要这样做:
if you want to transer learning and classify between 7 different classes you need to do it like this:
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
after fitting the model and calculate predictions you have to manually assign the class name to output number without using imported decode_predictions
这篇关于ValueError:`decode_predictions`需要一批预测(即2D形状的数组(样本,1000个)).找到形状为(1,7)的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!