Python 如何从预先训练的模型中删除最后一层。我尝试了model.layers.pop(),但它不起作用
我试图删除最后一层,以便我可以使用转移倾斜Python 如何从预先训练的模型中删除最后一层。我尝试了model.layers.pop(),但它不起作用,python,keras,keras-layer,tf.keras,Python,Keras,Keras Layer,Tf.keras,我试图删除最后一层,以便我可以使用转移倾斜 vgg16_model = keras.applications.vgg16.VGG16() model = Sequential() for layer in vgg16_model.layers: model.add(layer) model.layers.pop() # Freeze the layers for layer in model.layers: layer.trainable = False # Add
vgg16_model = keras.applications.vgg16.VGG16()
model = Sequential()
for layer in vgg16_model.layers:
model.add(layer)
model.layers.pop()
# Freeze the layers
for layer in model.layers:
layer.trainable = False
# Add 'softmax' instead of earlier 'prediction' layer.
model.add(Dense(2, activation='softmax'))
# Check the summary, and yes new layer has been added.
model.summary()
但我得到的结果并不是我所期望的。它仍然显示vgg16模型的最后一层
这是输出
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
block1_conv1 (Conv2D) (None, 224, 224, 64) 1792
_________________________________________________________________
block1_conv2 (Conv2D) (None, 224, 224, 64) 36928
**THE HIDDEN LAYERS**
_________________________________________________________________
fc1 (Dense) (None, 4096) 102764544
_________________________________________________________________
fc2 (Dense) (None, 4096) 16781312
_________________________________________________________________
predictions (Dense) (None, 1000) 4097000
_________________________________________________________________
dense_10 (Dense) (None, 2) 2002
=================================================================
Total params: 138,359,546
Trainable params: 2,002
Non-trainable params: 138,357,544
注意-在输出中,我没有显示整个模型,只是显示了前几层和最后几层
如何移除最后一层进行迁移学习
p.S Keras version=2.2.4首先不要将最后一层添加到模型中。这样,您甚至不需要
pop
vgg16_model=keras.applications.vgg16.vgg16()
模型=顺序()
对于vgg16_模型中的层。层[:-1]:#这是我更改代码的地方
模型。添加(图层)
#冻结层
对于model.layers中的图层:
layer.trainable=错误
#添加“softmax”而不是早期的“预测”层。
model.add(密集(2,activation='softmax'))
除了markuscosinus answer之外,您还可以在预测层之前获取输出,并将其传递给您自己的预测层。您可以按如下方式进行操作:
for layer in vgg16_model.layers:
layer.trainable = False
last_layer = vgg16_model.get_layer('fc2').output
out = Flatten()(last_layer)
out = Dense(128, activation='relu', name='fc3')(out)
out = Dropout(0.5)(out)
out = Dense(n_classes, activation='softmax', name='prediction')(out)
vgg16_custom_model = Model(input=vgg16_model.input, output=out)
我建议您在softmax之前添加一个展平层和另一个密集层,因为最后一个“fc2”有4096个节点,很难将其更改为2
当然,在预测之前辍学会给你更好的资源