训练第二个模型,同时在第一个模型的相同第一层中使用权重
Train second model while using weights in the same first layers of the first model
假设我们有两个模型,model1 和 model2。假设前 10 层对于 model1 和 model2 是相同的。然后你用一些数据集在 Keras 中训练 model1。您将模型保存在 "model1.h5" 中。然后你意识到 model1 的权重对于开始你的训练很有用 model2.I 想做这样的事情:
# make model1 and model2
# then set weights for the first 10 layers
model1.load_model("model1.h5")
model2.set_weights[:10] = model1.get_weights[:10]
model2.compile(...)
model2.fit(...)
model2.save("model2.h5")
使用 model.load_weights(file, by_name=True)
选项的简洁方法。您需要为共享的图层分配相同的名称:
# model 1 ...
model1.add(Dense(64, name="dense1"))
model1.add(Dense(2, name="dense2"))
# model 2 ...
model2.add(Dense(64, name="dense1"))
model2.add(Dense(32, name="notshared"))
# train model 1 and save
model1.save(filename) # or model.save_weights(filename)
# Load shared layers into model 2
model2.load_weights(filename, by_name=True) # will skip non-matching layers
# So it will only load "dense1"
要点是您从模型 1 权重文件加载模型 2 权重,但仅加载匹配层名称。图层必须具有相同的形状和类型。
作为对@nuric 回答的补充和对的回应,如果您在训练和存储模型之前没有在层上设置名称,您也可以在加载模型后设置它们:
# load the model
model = load_model(...)
model.layers[index_of_layer].name = 'layer_name'
然后就可以使用@nuric的方案来加载权重了。此外,要查找层的索引,您可以使用 model.summary()
。该列表中的图层从零开始从上到下编号。
假设我们有两个模型,model1 和 model2。假设前 10 层对于 model1 和 model2 是相同的。然后你用一些数据集在 Keras 中训练 model1。您将模型保存在 "model1.h5" 中。然后你意识到 model1 的权重对于开始你的训练很有用 model2.I 想做这样的事情:
# make model1 and model2
# then set weights for the first 10 layers
model1.load_model("model1.h5")
model2.set_weights[:10] = model1.get_weights[:10]
model2.compile(...)
model2.fit(...)
model2.save("model2.h5")
使用 model.load_weights(file, by_name=True)
选项的简洁方法。您需要为共享的图层分配相同的名称:
# model 1 ...
model1.add(Dense(64, name="dense1"))
model1.add(Dense(2, name="dense2"))
# model 2 ...
model2.add(Dense(64, name="dense1"))
model2.add(Dense(32, name="notshared"))
# train model 1 and save
model1.save(filename) # or model.save_weights(filename)
# Load shared layers into model 2
model2.load_weights(filename, by_name=True) # will skip non-matching layers
# So it will only load "dense1"
要点是您从模型 1 权重文件加载模型 2 权重,但仅加载匹配层名称。图层必须具有相同的形状和类型。
作为对@nuric 回答的补充和对
# load the model
model = load_model(...)
model.layers[index_of_layer].name = 'layer_name'
然后就可以使用@nuric的方案来加载权重了。此外,要查找层的索引,您可以使用 model.summary()
。该列表中的图层从零开始从上到下编号。