从预训练的Keras模型中删除层与原始模型输出相同

14

在进行一些特征提取实验时,我注意到 'model.pop()' 功能不像预期的那样工作。 对于像vgg16这样的预训练模型,在使用“model.pop()”后,model.summary()显示该层已被删除(期望的4096个特征),但是通过新模型传递图像时,它会生成与原始模型相同数量的特征(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

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

2个回答

10

参考 @Koul 的回答。

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

from keras.models import Model

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

3
由于目前预训练的Keras模型(TensorFlow 2.4.0)使用的是函数式模型(而非顺序模型),因此不支持.pop()方法,这是唯一有效的解决方案。 - GMSL

4

在撰写本文时,最新的 TensorFlow(2.4.0)中,使用 .pop() 操作函数模型会引发错误,因此该方法不起作用。但是,下面用户“user3731622”的回答仍然有效。 - GMSL

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接