python - 使用自定义权重进行训练
问题描述
目前我正在使用迁移学习来训练神经网络。我正在使用 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 中训练模型?
解决方案
如果您只保存了权重,则只能将这些权重加载到具有相同架构的网络中。假设您拥有的权重与 Keras 应用程序模型的架构相匹配,您可以:
base_model = ResNet50(...,weights=None)
base_model.load_weights('my_weights_file.h5')
for layer in base_model.layers:
layer.training = False
推荐阅读
- javascript - 如何限制元素的范围?
- python - scipy.stats.norm.interval 返回 inf
- javascript - Javascript连接传递给函数的数组数组
- c# - 如何创建可以在网站上搜索的用户控件
- java - 使用 Java MariaDB 连接器的 ConnectionException
- antd - Ant 设计中 Form.Item 的条件渲染
- laravel - 如何在 Laravel 的视图刀片中使用匿名字母表示属性
- ssh - Ansible sudo 密码丢失
- sql-server - 如何计算 Table Trade 中遗漏的零件以及存在于 Table Part 上的零件?
- svg - 给定svg中的4条曲线,得出圆的半径是否准确?