我正在尝试删除最后一层,以便我可以使用转移学习。
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 版本 = 2.2.4
最佳答案
首先不要将最后一层添加到模型中。这样你甚至不需要 pop
vgg16_model = keras.applications.vgg16.VGG16()
model = Sequential()
for layer in vgg16_model.layers[:-1]: # this is where I changed your code
model.add(layer)
# Freeze the layers
for layer in model.layers:
layer.trainable = False
# Add 'softmax' instead of earlier 'prediction' layer.
model.add(Dense(2, activation='softmax'))
关于python - 如何从预训练模型中删除最后一层。我尝试过 model.layers.pop() 但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55335228/