简体   繁体   English

tf.keras “所有图层名称都应该是唯一的。” 但是图层名称已经更改

[英]tf.keras "All layer names should be unique." but layer names are already changed

I am trying create an ensemble of lstm.我正在尝试创建一个 lstm 集合。 Below is my implementation of one lstm:下面是我对一个 lstm 的实现:

def lstm_model(n_features, n_hidden_unit, learning_rate, p, recurrent_p):
   model = keras.Sequential()
   model.add(Masking(mask_value=-1, input_shape=(100, n_features)))
   model.add(Bidirectional(LSTM(n_hidden_unit, input_shape=(None, n_features), return_sequences=True,
                            dropout = p, recurrent_dropout = recurrent_p)))

   model.add(TimeDistributed(Dense(3, activation='softmax')))
   model.compile(loss=CategoricalCrossentropy(from_logits=True),
              optimizer=Adam(learning_rate=learning_rate), 
              metrics=['categorical_accuracy'])
   return model

Then I trained a few lstm.然后我训练了几个lstm。 The models are stored as a list then pass into the function below模型存储为列表,然后传递到下面的 function

def define_stacked_model(members):
    for i in range(len(members)):
        model = members[i]['model']
        model.input._name = 'ensemble_' + str(i+1) + '_' + model.input.name
        for layer in model.layers:
            # make not trainable
            layer.trainable = False
            # rename to avoid 'unique layer name' issue
            layer._name = 'ensemble_' + str(i+1) + '_' + layer.name

            print(layer._name)

    # define multi-headed input
    ensemble_visible = [model_dictionary['model'].input for model_dictionary in members]

    # concatenate merge output from each model
    ensemble_outputs = [model_dictionary['model'].output for model_dictionary in members]

    merge = tf.keras.layers.Concatenate(axis=2)(ensemble_outputs)
    lstm_n_features = merge.shape[-1]

    stack_lstm = Bidirectional(LSTM(25, input_shape=(None, lstm_n_features), return_sequences=True,
                                dropout = 0, recurrent_dropout = 0))(merge)

    output = TimeDistributed(Dense(3, activation='softmax'))(stack_lstm)
    model = Model(inputs=ensemble_visible, outputs=output)
    # plot graph of ensemble
    plot_model(model, show_shapes=True, to_file='model_graph.png')
    rename(model, model.layers[1], 'new_name')
    # compile
    model.compile(loss=CategoricalCrossentropy(from_logits=True),
                  optimizer=Adam(learning_rate=learning_rate), 
                  metrics=['categorical_accuracy'])
    return model

The output shows the layer and input names are already changed output 显示图层和输入名称已更改

ensemble_1_masking_input:0
ensemble_1_masking
ensemble_1_bidirectional
ensemble_1_time_distributed
ensemble_2_masking_input_1:0
ensemble_2_masking
ensemble_2_bidirectional
ensemble_2_time_distributed
ensemble_3_masking_input_2:0
ensemble_3_masking
ensemble_3_bidirectional
ensemble_3_time_distributed
ensemble_4_masking_input_3:0
ensemble_4_masking
ensemble_4_bidirectional
ensemble_4_time_distributed

but there is a value error:但是有一个值错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-14-30bc0e96adc5> in <module>
     25 #hidden = Dense(10, activation='relu')(merge)
     26 output = TimeDistributed(Dense(3, activation='softmax'))(stack_lstm)
---> 27 model = Model(inputs=ensemble_visible, outputs=output)
     28 #model = Model(inputs=ensemble_visible)
     29 # plot graph of ensemble

~\anaconda3\envs\env_notebook\lib\site-packages\tensorflow\python\keras\engine\training.py in __init__(self, *args, **kwargs)
    165 
    166   def __init__(self, *args, **kwargs):
--> 167     super(Model, self).__init__(*args, **kwargs)
    168     _keras_api_gauge.get_cell('model').set(True)
    169     # Model must be created under scope of DistStrat it will be trained with.

~\anaconda3\envs\env_notebook\lib\site-packages\tensorflow\python\keras\engine\network.py in __init__(self, *args, **kwargs)
    171         'inputs' in kwargs and 'outputs' in kwargs):
    172       # Graph network
--> 173       self._init_graph_network(*args, **kwargs)
    174     else:
    175       # Subclassed network

~\anaconda3\envs\env_notebook\lib\site-packages\tensorflow\python\training\tracking\base.py in _method_wrapper(self, *args, **kwargs)
    454     self._self_setattr_tracking = False  # pylint: disable=protected-access
    455     try:
--> 456       result = method(self, *args, **kwargs)
    457     finally:
    458       self._self_setattr_tracking = previous_value  # pylint: disable=protected-access

~\anaconda3\envs\env_notebook\lib\site-packages\tensorflow\python\keras\engine\network.py in _init_graph_network(self, inputs, outputs, name, **kwargs)
    304 
    305     # Keep track of the network's nodes and layers.
--> 306     nodes, nodes_by_depth, layers, _ = _map_graph_network(
    307         self.inputs, self.outputs)
    308     self._network_nodes = nodes

~\anaconda3\envs\env_notebook\lib\site-packages\tensorflow\python\keras\engine\network.py in _map_graph_network(inputs, outputs)
   1800   for name in all_names:
   1801     if all_names.count(name) != 1:
-> 1802       raise ValueError('The name "' + name + '" is used ' +
   1803                        str(all_names.count(name)) + ' times in the model. '
   1804                        'All layer names should be unique.')

ValueError: The name "masking_input" is used 4 times in the model. All layer names should be unique.

I cant find where is this "masking_input" and how to change it.我找不到这个“masking_input”在哪里以及如何更改它。

Not sure if you ever fixed this, or if anyone else will find the same issue;不确定你是否曾经解决过这个问题,或者其他人是否会发现同样的问题; I just spent hours on the same problem and finally found the solution.我只是在同一个问题上花了几个小时,终于找到了解决方案。

When listing layers for renaming, instead of model.layers , you have to use model._layers , otherwise the input name remains unchanged.列出要重命名的层时,必须使用model._layers而不是model.layers ,否则输入名称保持不变。 Changing model.inputs.name does not work and produces the mentioned error.更改 model.inputs.name 不起作用并产生上述错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Keras - 所有图层名称都应该是唯一的 - Keras - All layer names should be unique “ValueError:名称“input_2”在 model 中使用了 2 次。所有图层名称都应该是唯一的。” keras 错误 seq2seq model - "ValueError: The name "input_2" is used 2 times in the model. All layer names should be unique." Error in keras with seq2seq model 使用Keras在GPU上训练GAN:所有层名称对于鉴别器应该是唯一的 - Training GANs on GPUs with Keras: All layer names should be unique for discriminator 使用带有作业数量的 optuna 超参数优化器时,keras“所有层名称都应该是唯一的”错误 - keras “All layer names should be unique” error while using optuna hyperparameters optimizer with number of jobs 在GPU上训练RNN-我应该使用哪个tf.keras层? - Training RNN on GPU - which tf.keras layer should I use? 输入到tf.keras的Conv2D层的大小不正确 - Input to tf.keras Conv2D layer not of appropriate size 手动将 pytorch 权重转换为卷积层的 tf.keras 权重 - Manualy convert pytorch weights to tf.keras weights for convolutional layer 关于 tf.keras 自定义层中 boolean 列表的问题 - a question about boolean list in custom layer in tf.keras tf.keras 输入层仅用于推理期间 - tf.keras input layer only for use during inference 有没有办法加快 tf.keras 中的嵌入层? - Is there a way to speed up Embedding layer in tf.keras?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM