首页 > 解决方案 > 如何加载具有全连接层的 keras CNN 模型并转换为 FCN?

问题描述

我有一个 VGG16 样式模型(即具有完全连接层的 CNN)保存为 json 文件和权重为 h5 文件。

我想加载这个模型并将其转换为 FCN(全卷积模型),它可以接受可变大小的 RGB 图像作为输入。

据我了解,有 4 个主要步骤:1)更改输入层以接受可变大小的输入 RGB 输入。2) 从具有全连接层的 VGG16 样式模型中移除全连接层。3)添加与全连接层等效的适当卷积层。4) 为新的卷积层重塑和设置权重。

我相信我知道如何执行步骤 2-4。但是,我在执行第 1 步时遇到了问题。

我已经阅读过Keras replace input layer 之类的帖子,但还没有找到适合我的解决方案。

这是我想做的:

#load model & weights
with open(model_json_file, 'r') as json_file:
    model_json = json_file.read()

vgg16_model = model_from_json(model_json)
vgg16_model.load_weights(model_h5_file)

#remove input layer
vgg16_model.layers.pop(0)

x = vgg16_model.get_layer('block5_pool').output
x = Conv2D(4096, (7,7), strides=1, padding='same', data_format='channels_last', activation='relu', use_bias=True)(x)
x = Conv2D(1000, (7,7), strides=1, padding='same', data_format='channels_last', activation='relu', use_bias=True)(x)
x = Conv2D(2, (7,7), strides=1, padding='same', data_format='channels_last', activation='relu', use_bias=True)(x)

new_input = Input(shape=(None,None,3), batch_shape=None, name='fcn_input')
vgg16_model.layers[0](new_input)
fcn_model_fixed_input = Model(inputs=vgg16_model.input, outputs=x)

然而然后:

fcn_model_fixed_input.summary()

给出:

wind_turbine_fcn_model_fixed_input.summary()

标签: pythonkerasconv-neural-networkvgg-net

解决方案


推荐阅读