Keras rename model and layers

To rename a keras model in TF2.2.0:

model._name = "newname"

I have no idea if this is a bad idea - they don't seem to want you to do it, but it does work. To confirm, call model.summary() and you should see the new name.


Your first problem about the model name is not reproducible on my machine. I can set it like this. many a times these errors are caused by software versions.

model=Sequential()
model.add(Dense(2,input_shape=(....)))
model.name="NAME"

As far as naming the layers, you can do it in Sequential model like this

model=Sequential()
model.add(Dense(2,input_shape=(...),name="NAME"))

The Answer from user239457 only works with Standard keras.

If you want to use the Tensorflow Keras, you can do it like this:

from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense

model = Sequential(name='Name')
model.add(Dense(2,input_shape=(5, 1)))

For changing names of model.layers with tf.keras you can use the following lines:

for layer in model.layers:
    layer._name = layer.name + str("_2")

I needed this in a two-input model case and ran into the "AttributeError: can't set attribute", too. The thing is that there is an underlying hidden attribute _name, which causes the conflict.

Tags:

Python

Keras