【问题标题】:Remove layers from a custom pre-trained model从自定义预训练模型中删除层
【发布时间】:2020-01-30 22:12:57
【问题描述】:

我在 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 层中提取特征,但我不知道如何访问它。 加载模型后,摘要如下所示:

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

这可能吗,还是我必须使用功能 API 重新构建架构并重新训练整个事物?

谢谢!

【问题讨论】:

    标签: python keras deep-learning keras-layer


    【解决方案1】:

    直接在 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()
    

    【讨论】:

    • 是的,但这意味着我需要再次训练。我有 .hdf5 文件,其中包含我之前描述的权重和架构,我想从这个架构中删除最后 2 层以进入 GlobalAveragePooling。我想使用我必须进行特征提取的检查点。我希望我现在说得更清楚了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2018-12-11
    • 2017-07-07
    • 2021-08-18
    相关资源
    最近更新 更多