从预训练的keras模型中移除图层会提供与原始模型相同的输出

时间:2017-12-29 06:33:07

标签: keras keras-layer keras-2

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

<VirtualHost *:80>
  ServerName www.example.com
  Redirect / https://www.example.com/
 </VirtualHost>

<virtualHost *:443>
   DocumentRoot /var/www/html/example.com
   ServerName www.example.com 
 </VirtualHost>

1000

#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

谢谢!

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

2 个答案:

答案 0 :(得分:1)

在这里找到答案:https://github.com/keras-team/keras/issues/2371#issuecomment-308604552

from keras.models import Model

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

model2表现正确。

答案 1 :(得分:1)

解决@Koul答案。

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

from keras.models import Model

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