【问题标题】:keras error: "AttributeError: can't set attribute" while defining a layerkeras 错误:定义图层时出现“AttributeError:无法设置属性”
【发布时间】:2018-06-29 10:24:15
【问题描述】:

我正在尝试在 keras 中创建我自己的图层,但我得到了错误。我的简单代码如下:

class MyLayer(Layer):

def __init__(self, output_dim, **kwargs):
    self.output_dim = output_dim

    self.updates = []

    super(MyLayer, self).__init__(**kwargs)

def build(self, input_shape):
    # Create a trainable weight variable for this layer.
    self.kernel = self.add_weight(name='kernel', 
                                  shape=(input_shape[1], self.output_dim),
                                  initializer='uniform',
                                  trainable=True)
    super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!

def call(self, x):
    return K.dot(x, self.kernel)

def compute_output_shape(self, input_shape):
    return (input_shape[0], self.output_dim)

错误是:

AttributeError Traceback(最近一次调用最后一次) 在 () ----> 1 MyLayer(output_dim=10)

in init(self, output_dim, **kwargs)

8 self.output_dim = output_dim

9

---> 10 个 self.updates = []

11

12 super(MyLayer, self).init(**kwargs)

AttributeError: 无法设置属性

你能帮忙解决这个问题吗? 谢谢

【问题讨论】:

    标签: python keras


    【解决方案1】:

    这适用于 TensorFlow 2.0。

    import tensorflow as tf
    from tensorflow import keras
    from tensorflow.keras.layers import Layer
    
    class MyLayer(Layer):
      def __init__(self, output_dim, **kwargs):
        self.output_dim = output_dim
    
        self.update = []
    
        super(MyLayer, self).__init__(**kwargs)
    
      def build(self, input_shape):
          # Create a trainable weight variable for this layer.
          self.my_kernel = self.add_weight(name='my_kernel', 
                                        shape=(input_shape[1], self.output_dim),
                                        initializer='uniform',
                                        trainable=True)
          super(MyLayer, self).build(input_shape)  # Be sure to call this somewhere!
    
      def call(self, x):
          return K.dot(x, self.kernel)
    
      def compute_output_shape(self, input_shape):
          return (input_shape[0], self.output_dim)
    
    my_layer = MyLayer((1))
    

    【讨论】:

      【解决方案2】:

      这看起来类似于here 中的问题。

      在这种情况下,OP 使用的是变量名称 weights 而不是似乎已经使用的 kernal。如果您查看Tensroflow guideLayer 的定义,您会发现updateweights 类的属性层

      【讨论】:

        猜你喜欢
        • 2017-07-17
        • 2021-04-04
        • 2015-02-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-08-09
        • 2017-04-26
        • 1970-01-01
        相关资源
        最近更新 更多