【问题标题】:Keras share weights between custom layersKeras 在自定义层之间共享权重
【发布时间】:2019-08-12 14:03:37
【问题描述】:

我正在使用 Capsule Networks 的 keras-capsnet 实现,并尝试将同一层应用于每个样本的 30 张图像。

权重在 init 中初始化,并为类构建参数,如下所示。我已经成功地在只使用 tf.layers.conv2d 的主要路由层之间共享了权重,在这里我可以为它们分配相同的名称并设置重用 = True。

有谁知道如何在 Keras 自定义层中初始化权重以便可以重用它们?我对 tensorflow API 比对 Keras 更熟悉!

def __init__(self, num_capsule, dim_capsule, routings=3,
             kernel_initializer='glorot_uniform',
             **kwargs):
    super(CapsuleLayer, self).__init__(**kwargs)
    self.num_capsule = num_capsule
    self.dim_capsule = dim_capsule
    self.routings = routings
    self.kernel_initializer = initializers.get(kernel_initializer)

def build(self, input_shape):
    assert len(input_shape) >= 3, "The input Tensor should have shape=[None, input_num_capsule, input_dim_capsule]"
    self.input_num_capsule = input_shape[1]
    self.input_dim_capsule = input_shape[2]

    # Weights are initialized here each time the layer is called
    self.W = self.add_weight(shape=[self.num_capsule, self.input_num_capsule,
                                    self.dim_capsule, self.input_dim_capsule],
                             initializer=self.kernel_initializer,
                             name='W')
    self.built = True

【问题讨论】:

  • 在 tensorflow 中你会怎么做?
  • 嗯该层是一个Keras自定义层,所以我不知道如何在tensorflow中做到这一点。我习惯于手动创建权重矩阵并仅在层内使用它(不必使用 self.add_weight 参数),或者使用相同的名称范围并传递“reuse = tf.AUTO_REUSE”——Keras 文档对此只字未提不幸的是,自定义图层中的图层共享 (tensorflow.org/api_docs/python/tf/keras/layers/Layer)
  • 文档说 Keras 应该通过在不同的输入上多次调用同一层来共享权重。像 layer = Dense(2), layer1 = layer(input), layer2 = layer(input2)。我在这种情况下尝试过,它说张量不可调用,因为该层返回张量。
  • 你能告诉我们你用来做你描述的代码吗?这正是 Keras 的方式,也许您设置图层的方式存在问题。

标签: python tensorflow keras deep-learning


【解决方案1】:

答案很简单。设置一个层而不在输入上调用它,然后使用该构建的层单独调用数据。

【讨论】:

  • 你能发布一些示例代码吗?我也对这个感兴趣。谢谢。
猜你喜欢
  • 2019-12-06
  • 1970-01-01
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 2018-08-01
  • 2020-06-02
  • 1970-01-01
相关资源
最近更新 更多