[英]Keras share weights between custom layers
我正在使用Capsule Networks的keras-capsnet實現,並嘗試將同一層應用於每個樣本30個圖像。
權重在類的init和build參數中初始化,如下所示。 我已成功共享主要路由層之間的權重,這些層只使用tf.layers.conv2d,我可以在其中為它們指定相同的名稱並設置reuse = True。
有誰知道如何在Keras自定義圖層中初始化權重,以便它們可以重復使用? 我比使用Keras更熟悉tensorflow API!
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
答案很簡單。 設置一個圖層而不在輸入時調用它,然后使用該構建的圖層單獨調用數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.