在Keras中的两个密集层之间共享权重

Mah*_*hah 5 neural-network theano keras

我有如下代码。我想要做的是在两个密集层中共享相同的权重。

op1和op2层的等式如下所示

op1 = w1y1 + w2y2 + w3y3 + w4y4 + w5y5 + b1

op2 = w1z1 + w2z2 + w3z3 + w4z4 + w5z5 + b1

这里,w1到w5的权重在op1和op2层输入之间共享,它们分别是(y1到y5)和(z1到z5)。

ip_shape1 = Input(shape=(5,))
ip_shape2 = Input(shape=(5,))

op1 = Dense(1, activation = "sigmoid", kernel_initializer = "ones")(ip_shape1)
op2 = Dense(1, activation = "sigmoid", kernel_initializer = "ones")(ip_shape2)

merge_layer = concatenate([op1, op2])
predictions = Dense(1, activation='sigmoid')(merge_layer)

model = Model(inputs=[ip_shape1, ip_shape2], outputs=predictions)
Run Code Online (Sandbox Code Playgroud)

提前致谢。

Dan*_*ler 6

双方使用相同的图层。(权衡和偏见是共享的)

ip_shape1 = Input(shape=(5,))
ip_shape2 = Input(shape=(5,))

dense = Dense(1, activation = "sigmoid", kernel_initializer = "ones")

op1 = dense(ip_shape1)
op2 = dense(ip_shape2)

merge_layer = Concatenate()([op1, op2])
predictions = Dense(1, activation='sigmoid')(merge_layer)

model = Model(inputs=[ip_shape1, ip_shape2], outputs=predictions)
Run Code Online (Sandbox Code Playgroud)

  • 它也在这里描述:https://keras.io/getting-started/functional-api-guide/#shared-layers (5认同)
  • 在第 2 边的末尾添加“Lambda(lambda x: K.stop_gradient(x))”。 (3认同)