运行时错误:无法创建链接(名称已存在)Keras

2024-04-19 13:37:39 发布

您现在位置:Python中文网/ 问答频道 /正文

保存模型时,出现以下错误:

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-40-853303da8647> in <module>()
      7 
      8 
----> 9 model.save(outdir+'model.h5')
     10 
     11 
5 frames
/usr/local/lib/python3.6/dist-packages/h5py/_hl/group.py in __setitem__(self, name, obj)
    371 
    372             if isinstance(obj, HLObject):
--> 373                 h5o.link(obj.id, self.id, name, lcpl=lcpl, lapl=self._lapl)
    374 
    375             elif isinstance(obj, SoftLink):

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

h5py/_objects.pyx in h5py._objects.with_phil.wrapper()

h5py/h5o.pyx in h5py.h5o.link()

RuntimeError: Unable to create link (name already exists)

当我使用内置层构建模型或其他用户定义层时,不会发生这种情况。仅当我使用此特定的用户定义层时,才会出现此错误:

class MergeTwo(keras.layers.Layer):

def __init__(self, nout, **kwargs):
    super(MergeTwo, self).__init__(**kwargs)
    self.nout = nout


    self.alpha = self.add_weight(shape=(self.nout,), initializer='zeros',
                             trainable=True)

    self.beta = self.add_weight(shape=(self.nout,), initializer='zeros',
                             trainable=True)

def call(self, inputs):
    A, B = inputs
    result = keras.layers.add([self.alpha*A ,self.beta*B])
    result = keras.activations.tanh(result)
    return result


def get_config(self):
    config = super(MergeTwo, self).get_config()
    config['nout'] = self.nout
    return config

我读了Docs但是没有任何效果,我不明白为什么。 我正在使用Google Colab和Tensorflow版本2.2.0


Tags: nameinselfconfigobjobjectsdeflink
2条回答

我找到了另一个解决方案,尽管是从不同的场景中找到的。 我使用Keras tuner进行一些超参数调整,在构建(例如4个模型)时,每个模型的层都有相同的名称。 当我测试网络深度作为一个参数时,我的组中会有多个lstm、lstm_1和密集层。下面为上下文显示了单个模型的示例

Layer (type)                 Output Shape              Param# 
=================================================================
lstm (LSTM)                  (None, 12, 320)           536320
_________________________________________________________________
lstm_1 (LSTM)                (None, 12, 64)            98560
_________________________________________________________________
dense (Dense)                (None, 12, 1)             65

我发现,使用name参数更改图层的名称,使其具有唯一性,这意味着我不会出现此错误。 举例说明:

unique_id = random.randint(1,99999999) # quite unlike 
model.add(LSTM(64, name="my_layer_name_{}".format(unique_id))) 

在自定义名称上添加唯一的_id时,我确保keras tuner组中每个模型的每个层都有唯一的层

在您的例子中,您只有一个模型,但是,由于层是自定义的,我不太确定如何命名它们(考虑到它们的当前格式)。 你能检查一下情况是否如此吗

我认为问题在于两个权重变量在内部具有相同的名称,这不应该发生,您可以使用name参数为它们命名add_weight

self.alpha = self.add_weight(shape=(self.nout,), initializer='zeros',
                         trainable=True, name="alpha")

self.beta = self.add_weight(shape=(self.nout,), initializer='zeros',
                         trainable=True, name="beta")

这应该可以解决这个问题

相关问题 更多 >