【问题标题】:Keras: Custom layer without inputsKeras:没有输入的自定义层
【发布时间】:2022-01-31 20:13:50
【问题描述】:

我想实现一个没有任何输入的 Keras 自定义层,只是可训练的权重。

这是目前为止的代码:

class Simple(Layer):

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

    def build(self):
       self.kernel = self.add_weight(name='kernel', shape=self.output_dim, initializer='uniform', trainable=True)
       super(Simple, self).build()  

    def call(self):
       return self.kernel

    def compute_output_shape(self):
       return self.output_dim

X = Simple((1, 784))()

我收到一条错误消息:

__call__() missing 1 required positional argument: 'inputs'

是否有在 Keras 中构建没有输入的自定义层的解决方法?

【问题讨论】:

  • 你必须打电话给X = Simple((1, 784))而不是X = Simple((1, 784))()
  • 我想获取输出张量,而不仅仅是创建层。
  • 你可以做def call(self,x):return self.kernel(x),仍然打电话X = Simple((1,784))继续你想做的事
  • @adalca 不,我不这么认为。
  • @adalca 如果您没有设置,请检查因此发布的答案。

标签: python tensorflow keras


【解决方案1】:

您可以执行以下操作,

from tensorflow.keras.layers import Layer

class Simple(Layer):

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

    def build(self, input_shapes):
       self.kernel = self.add_weight(name='kernel', shape=self.output_dim, initializer='uniform', trainable=True)
       super(Simple, self).build(input_shapes)  

    def call(self, inputs):
       return self.kernel

    def compute_output_shape(self):
       return self.output_dim

X = Simple((1, 784))([])
print(X.shape)

哪个产生

>>> (1, 784)

【讨论】:

    【解决方案2】:

    小修正:self.output_dim 周围需要方括号:

    def build(self, input_shapes):
       self.kernel = self.add_weight(name='kernel', shape=[self.output_dim], initializer='uniform', trainable=True)
       super(Simple, self).build(input_shapes)  
    

    【讨论】:

      猜你喜欢
      • 2017-06-28
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 2021-03-12
      • 1970-01-01
      • 2021-01-14
      • 2020-07-05
      • 1970-01-01
      相关资源
      最近更新 更多