Search code examples
pythonkerasmodels

Copy the same model multiple times in keras


I'm working in a model that contains 5 sub-models which are identical and their only difference is on their weights.

I trained each of them separately but now that I have to use them together I build the 5 of them and I get the message

RuntimeError: The name "predictions" is used 5 times in the model. All layer names should be unique.

I would like to know if there is a way to change the names of the layers inside my model without using the name property because there are more than 100 layers and I cannot do it manually. And if I change the name I would also like to know how to load the weights, because they are saved with the previous layer names.


Solution

  • I just reached an easy solution, I'm just changing the name of the layers with:

    model1 = Model(inputs=input, outputs=output)
        model1.load_weights('model1_weights.h5', by_name=True)
    
    for i, layer in enumerate(model1.layers):
            layer.name = 'layer'+str(i)+'_model1'
    

    And I did the same with the rest