Keras在自定义图层之间共享权重

时间:2019-03-21 16:31:31

标签: python tensorflow keras deep-learning

我正在使用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

1 个答案:

答案 0 :(得分:0)

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