Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python tf.keras“;所有图层名称都应该是唯一的。”;但图层名称已经更改_Python_Tensorflow_Keras_Keras Layer - Fatal编程技术网

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

Python tf.keras“;所有图层名称都应该是唯一的。”;但图层名称已经更改,python,tensorflow,keras,keras-layer,Python,Tensorflow,Keras,Keras Layer,我正在尝试创建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,

我正在尝试创建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
然后我训练了一些lstm。模型存储为一个列表,然后传递到下面的函数中

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

输出显示图层和输入名称已更改

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
但存在一个值错误:

---------------------------------------------------------------------------
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.

---------------------------------------------------------------------------
ValueError回溯(最近一次调用上次)
在里面
25#隐藏=密集(10,activation='relu')(合并)
26输出=时间分布(密集(3,激活='softmax'))(堆栈\lstm)
--->27模型=模型(输入=可见,输出=输出)
28#模型=模型(输入=集成可见)
29#集合图
~\anaconda3\envs\env\u notebook\lib\site packages\tensorflow\python\keras\engine\training.py in\uuuuuuuu init\uuuuuu(self,*args,**kwargs)
165
166定义初始值(self,*args,**kwargs):
-->167超级(模型,自身)。\uuuuu初始值(*args,**kwargs)
168 keras api量规。获取单元格(“模型”)。设置(真)
169#模型必须在培训范围内创建。
~\anaconda3\envs\env\u notebook\lib\site packages\tensorflow\python\keras\engine\network.py in\uuuuuuuu init\uuuuu(self,*args,**kwargs)
171 kwargs中的“输入”和kwargs中的“输出”:
172#图形网络
-->173自初始化图网络(*args,**kwargs)
174.其他:
175#子类网络
~\anaconda3\envs\env\u notebook\lib\site packages\tensorflow\python\training\tracking\base.py in\u method\u包装(self、*args、**kwargs)
454 self._self_setattr_tracking=False#pylint:disable=protected access
455试试:
-->456结果=方法(自身、*args、**kwargs)
457最后:
458 self._self_setattr_tracking=上一个值#pylint:disable=受保护访问
~\anaconda3\envs\env\u notebook\lib\site packages\tensorflow\python\keras\engine\network.py in\u init\u graph\u network(self、输入、输出、名称、**kwargs)
304
305#跟踪网络的节点和层。
-->306个节点,节点按深度,层,映射图网络(
307自输入、自输出)
308自身网络节点=节点
~\anaconda3\envs\env\u notebook\lib\site packages\tensorflow\python\keras\engine\network.py in\u map\u graph\u网络(输入、输出)
1800所有_名称中的名称:
1801如果所有_名称。计数(名称)!=1:
->1802 raise VALUERROR('使用了名称“'+名称+”)+
1803 str(all_names.count(name))+“模型中的次数。”
1804“所有图层名称都应唯一。”)
ValueError:名称“屏蔽输入”在模型中使用了4次。所有图层名称都应该是唯一的。

我找不到这个“屏蔽输入”在哪里以及如何更改它。

不确定您是否解决过这个问题,或者其他人是否会发现相同的问题;我只是在同一个问题上花了几个小时,终于找到了解决办法

列出要重命名的图层时,必须使用
model.layers
,而不是
model.\u layers
,否则输入名称保持不变。更改model.inputs.name不起作用,并产生上述错误