从自定义的预训练模型中删除图层

时间:2019-10-01 15:14:04

标签: python keras deep-learning keras-layer

我确实像这样从keras转移了关于Inception模型的学习:

base_model = applications.InceptionV3(weights='imagenet', include_top=False, input_shape=input_shape)

model_top = Sequential()
model_top.add(GlobalAveragePooling2D(input_shape=base_model.output_shape[1:], data_format=None))
model_top.add(Dropout(0.4))
model_top.add(Dense(2))
model_top.add(Activation("softmax"))

# model_top.summary()

model = Model(inputs=base_model.input, outputs=model_top(base_model.output))

我想使用训练有素的模型从GlobalAveragePooling层中提取要素,但是我不知道如何访问它。 加载模型后,摘要如下所示:enter image description here

如果显示self.model.layers[-1]的摘要,则可以看到Sequential中的GlobalAveragePooling,Dropout和Dense层,但看不到Inception层。我想要的是Inception层,然后是GlobalAveragePooling。

这是可能的还是我必须使用功能性API重新构建体系结构并重新培训整个事情?

谢谢!

1 个答案:

答案 0 :(得分:0)

直接在Sequential中添加Inception模型对我来说是有效的:

from keras import applications
from keras.layers import GlobalAveragePooling2D, Dropout, Dense, Activation
from keras.models import Model, Sequential

input_shape = (299, 299, 3)

base_model = applications.InceptionV3(weights='imagenet', include_top=False, input_shape=input_shape)

model = Sequential([
    applications.InceptionV3(weights='imagenet', include_top=False),
    GlobalAveragePooling2D(),
    Dropout(0.4),
    Dense(2),
    Activation("softmax")
])
model.summary()

submodel = Model(inputs=model.input, outputs=model.get_layer("global_average_pooling2d_1").output)
submodel.summary()