Suppose we have two models, model1 and model2. Suppose that first 10 layers are the same for model1 and model2. Then you train model1 in Keras with some dataset. You save the model in "model1.h5". Then you realize that the weights of model1 are useful for starting your training model2.I would like to do something like this:
# 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")
A clean way of doing this using the model.load_weights(file, by_name=True)
option. What you need is to assign the same names to layers that are shared:
# 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"
The gist is you load model 2 weights from model 1 weights file but only the matching layer names. Layers must be same shape and type.