从预训练的Keras模型中删除图层可提供与原始模型相同的输出 [英] Removing layers from a pretrained keras model gives the same output as original model

查看:93
本文介绍了从预训练的Keras模型中删除图层可提供与原始模型相同的输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些特征提取实验中,我注意到'model.pop()'功能无法按预期工作.对于像vgg16这样的预训练模型,在使用'model.pop()'之后,model.summary()显示该层已被删除(预期有4096个特征),但是在通过新模型传递图像时,结果相同数量(1000个)作为原始模型.不管删除了多少层(包括一个完全空的模型),它都会生成相同的输出.寻找有关可能出问题的指南.

During some feature extraction experiments, I noticed that the 'model.pop()' functionality is not working as expected. For a pretrained model like vgg16, after using 'model.pop()' , model.summary() shows that the layer has been removed (expected 4096 features), however on passing an image through the new model, it results in the same number of features (1000) as the original model. No matter how many layers are removed including a completely empty model, it generates the same output. Looking for your guidance on what might be the issue.

#Passing an image through the full vgg16 model
model = VGG16(weights = 'imagenet', include_top = True, input_shape = (224,224,3))
img = image.load_img( 'cat.jpg', target_size=(224,224) )
img = image.img_to_array( img )
img = np.expand_dims( img, axis=0 )
img = preprocess_input( img )
features = model.predict( img )
features = features.flatten()
print(len(features)) #Expected 1000 features corresponding to 1000 imagenet classes

1000

model.layers.pop()
img = image.load_img( 'cat.jpg', target_size=(224,224) )
img = image.img_to_array( img )
img = np.expand_dims( img, axis=0 )
img = preprocess_input( img )
features2 = model.predict( img )
features2 = features2.flatten()
print(len(features2)) #Expected 4096 features, but still getting 1000. Why?
#No matter how many layers are removed, the output is still 1000

1000

谢谢!

在此处查看完整代码: https://github .com/keras-team/keras/files/1592641/bug-feature-extraction.pdf

See full code here: https://github.com/keras-team/keras/files/1592641/bug-feature-extraction.pdf

推荐答案

解决@Koul答案.

我相信您不需要使用pop方法.相反,只需将输出层之前的层作为Model方法的输出参数的参数传递即可:

I believe you don't need to use the pop method. Instead just pass the layer before the output layer as the argument for the Model method's output parameter:

from keras.models import Model

model2 = Model(model.input, model.layers[-2].output)
model2.summary()

这篇关于从预训练的Keras模型中删除图层可提供与原始模型相同的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆