How to copy layer and weights from one model to another using the functional API?

I know that the functional API is different from the sequential and so I’m not even sure this is possible.


Both APIs use the same layer objects. Just use get_weights() to get the weights from one layer and then use set_weigths() to put them on the new layer.

1 Like

The problem I’m encountering is that the output for the model is still set to be that of the last layer for the original model … not the last layer after I append new layers.


base_model = ResNet50(weights='imagenet', include_top=False, input_shape=(400,400,3))

final_model = Model(inputs=base_model.input, outputs=base_model.layers[-2].output)
for l in rn400_model.layers[1:]: 
    nl = l

Even after trying this:

final_model.layers[-1].outbound_nodes = []
final_model.outputs = [final_model.layers[-1].output]

When I run final_model.output it still points to the original output of the base_model and NOT to the output of the last layer I append.

I’m not entirely sure what you’re trying to do, but the line nl = l doesn’t make a new layer. So nl.set_weights(l.get_weights()) serves no purpose because nl and l are the same thing…

So how do you copy layers from one model on top of those of another?

Referencing nl in your append is just going to get you what you have in l (as you set nl = l). I’m not sure where rn400_model is getting set, (as we appear to be missing that code in your snippet), but I think your answer might be in there.