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

Dru*_*ugo 5 python keras tensorflow

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

---------------------------------------------------------------------------
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)
Run Code Online (Sandbox Code Playgroud)

当我使用内置层来构建我的模型或其他用户定义的层时,这不会发生。只有当我使用这个特定的用户定义层时才会出现这个错误:

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
Run Code Online (Sandbox Code Playgroud)

我阅读了文档,但没有任何效果,我不知道为什么。我正在使用 Google Colab 和 Tensorflow 2.2.0 版

Mat*_*gro 7

我认为问题在于您的两个权重变量在内部具有相同的名称,这不应该发生,您可以使用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")
Run Code Online (Sandbox Code Playgroud)

这应该可以解决问题。