首页 > 解决方案 > 使用自定义权重进行训练

问题描述

目前我正在使用迁移学习来训练神经网络。我正在使用 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 权重转换器将这些模型转换为 keras h5 文件。

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

标签: pythontensorflowkerasdeep-learning

解决方案


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

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

推荐阅读