以自定义重量训练

时间:2019-07-07 00:53:20

标签: python tensorflow keras deep-learning

目前,我正在使用转移学习来训练神经网络。 我正在使用keras提供的ResNet50预训练模型。

base_model=ResNet50(weights='imagenet', include_top=False, input_shape=(224, 224, 3))

# function to finetune model
def build_finetune_model(base_model, dropout, fc_layers, num_classes):
    for layer in base_model.layers:
        layer.trainable = False

    x = base_model.output
    x = Flatten()(x)
    for fc in fc_layers:
        # New FC layer, random init
        x = Dense(fc, use_bias=False)(x)
        x = BatchNormalization()(x)
        x = Activation('relu')(x)
        x = Dropout(dropout)(x)

    # New softmax layer
    x = Dense(num_classes, use_bias=False)(x) 
    x = BatchNormalization()(x)
    predictions = Activation('softmax')(x)
    finetune_model = Model(inputs=base_model.input, outputs=predictions)

    return finetune_model

FC_LAYERS = [1024, 512]
dropout = 0.5

model = build_finetune_model(base_model, dropout=dropout, fc_layers=FC_LAYERS,num_classes=len(categories))

现在,我想看看是否使用Resnet50 1by2(以及其他方法)会提高我的准确性。这些模型作为caffe模型提供。我使用Caffe weight converter将这些模型转换为keras h5文件。

现在的问题是这些文件不包含可以训练的模型,仅包含权重。 如何使用权重在keras中训练模型?

1 个答案:

答案 0 :(得分:1)

如果仅保存了权重,则只能将这些权重加载到具有相同体系结构的网络中。假设权重与Keras应用程序模型的架构匹配,您可以:

base_model = ResNet50(...,weights=None)
base_model.load_weights('my_weights_file.h5')
for layer in base_model.layers:
   layer.training = False