How to load only specific weights on Keras

前端 未结 2 1141
忘了有多久
忘了有多久 2020-12-13 09:28

I have a trained model that I\'ve exported the weights and want to partially load into another model. My model is built in Keras using TensorFlow as backend.

Right n

相关标签:
2条回答
  • 2020-12-13 10:13

    If your first 9 layers are consistently named between your original trained model and the new model, then you can use model.load_weights() with by_name=True. This will update weights only in the layers of your new model that have an identically named layer found in the original trained model.

    The name of the layer can be specified with the name keyword, for example:

    model.add(Dense(8, activation='relu',name='dens_1'))
    
    0 讨论(0)
  • 2020-12-13 10:26

    This call:

    weights_list = model.get_weights()
    

    will return a list of all weight tensors in the model, as Numpy arrays.

    All what you have to do next is to iterate over this list and apply:

    for i, weights in enumerate(weights_list[0:9]):
        model.layers[i].set_weights(weights)
    

    where model.layers is a flattened list of the layers comprising the model. In this case, you reload the weights of the first 9 layers.

    More information is available here:

    https://keras.io/layers/about-keras-layers/

    https://keras.io/models/about-keras-models/

    0 讨论(0)
提交回复
热议问题