1
from keras import layers as KL
def create_model():
    inp = KL.Input(shape=(None,), name='input')
    embedding = KL.Embedding(input_dim=10, output_dim=10)(inp)
    out = KL.Dense(1, activation='sigmoid', name='dense')(embedding)
    model = KM.Model(inputs=[inp], outputs=[out])

    return model

model1 = create_model()
model1.summary()
model2 = create_model()
model2.summary()

The output for model1:

embedding_1 (Embedding) 

model2:

embedding_2 (Embedding) 

Why the name of the layer is not fixed? If I run create_model() again, the name will be suffixed with _3.

Any idea? Does this has anything to do with running in Jupyter? Does Jupyter kernel somehow cache the variables? Thanks!

desertnaut
  • 57,590
  • 26
  • 140
  • 166
zs2020
  • 53,766
  • 29
  • 154
  • 219
  • 1
    Keras does this, because layer names have to be unique. – Dr. Snoopy Mar 07 '19 at 15:45
  • Does Keras maintain the layer names globally? `create_model()` defines a new model every time it is called. – zs2020 Mar 07 '19 at 15:47
  • It creates them so they are globally unique but they don't have to. Note that this has nothing to do with variable names. – Dr. Snoopy Mar 07 '19 at 15:49
  • Is there a way to reset the counter? I need the layer names to be fixed because I need to port the model as tensforflow format and use it in C#. If the name of the layer is changed every time when the model is trained, I have to update the code. – zs2020 Mar 07 '19 at 15:52
  • Possibly of help: [Keras - All layer names should be unique](https://stackoverflow.com/questions/43452441/keras-all-layer-names-should-be-unique) – desertnaut Mar 07 '19 at 15:56

1 Answers1

0

Each layer has a parameter called name, which sets the layer name. You can use this to put your own fixed names to layers, so you can operate on them later.

For example:

conv1 = Conv2D(..., name='conv1')(some_input)
Dr. Snoopy
  • 55,122
  • 7
  • 121
  • 140
  • This won't work. The name will be `embedding_1/embedding` or `embedding_2/embedding` after ported as Tensorflow format – zs2020 Mar 07 '19 at 15:59
  • 1
    @zsong I get the feeling that we have a XY problem here, because you don't explain what exactly is the problem, but you are trying to make your solution work. Please state the full problem. – Dr. Snoopy Mar 07 '19 at 16:04