Keras rename model and layers

2020-07-03 03:56发布

1) I try to rename a model and the layers in Keras with TF backend, since I am using multiple models in one script. Class Model seem to have the property model.name, but when changing it I get "AttributeError: can't set attribute". What is the Problem here?

2) Additionally, I am using sequential API and I want to give a name to layers, which seems to be possibile with Functional API, but I found no solution for sequential API. Does anonye know how to do it for sequential API?

UPDATE TO 2): Naming the layers works, although it seems to be not documented. Just add the argument name, e.g. model.add(Dense(...,...,name="hiddenLayer1"). Watch out, Layers with same name share weights!

标签: python keras
5条回答
Rolldiameter
2楼-- · 2020-07-03 04:32

Just to cover all the options, regarding the title of the question, if you are using the Keras functional API you can define the model and the layers name by:

inputs = Input(shape=(value, value))

output_layer = Dense(2, activation = 'softmax', name = 'training_output')(dropout_new_training_layer)

model = Model(inputs= inputs, outputs=output_layer, name="my_model")
查看更多
▲ chillily
3楼-- · 2020-07-03 04:34

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.

查看更多
Animai°情兽
4楼-- · 2020-07-03 04:36

for 1), I think you may build another model with right name and same structure with the exist one. then set weights from layers of the exist model to layers of the new model.

查看更多
在下西门庆
5楼-- · 2020-07-03 04:41

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"))
查看更多
不美不萌又怎样
6楼-- · 2020-07-03 04:55

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)))
查看更多
登录 后发表回答