首页 > 解决方案 > 在 Keras 中,在我自己的模型上使用 include_top= False 会删除所有最后一个密集层,我可以定义模型的“顶部”吗?

问题描述

我可以定义我想要定义为“顶层”的层吗?

据我了解, include_top= false 将删除顶部的所有密集层。我想使用“include_top=False”对我自己的模型进行迁移学习,并且不希望我所有的最后一个密集层都被自动删除。

标签: kerastransfer-learning

解决方案


要访问您必须设置的最后一个密集层include_top = True。通过这种方式,您可以创建一个包含所有您想要的中间层的子模型。这里有一个 VGG16 的例子

from tensorflow.keras.layers import *
from tensorflow.keras.models import *
from tensorflow.keras.applications import VGG16

vgg = VGG16(include_top = True, input_shape = (224,224,3))
new_layer = Dense(32)(vgg.layers[-3].output) # add new layer

sub_model = Model(vgg.input, new_layer)

sub_model在这种情况下,最后一层是:

block5_conv3 (Conv2D)        (None, 14, 14, 512)       2359808   
_________________________________________________________________
block5_pool (MaxPooling2D)   (None, 7, 7, 512)         0         
_________________________________________________________________
flatten (Flatten)            (None, 25088)             0         
_________________________________________________________________
fc1 (Dense)                  (None, 4096)              102764544 
_________________________________________________________________
dense_6 (Dense)              (None, 32)                131104    

推荐阅读