我正在尝试使用Keras函数API实现一个神经元网络,该API对多个层使用相同的权重。代码正在工作,但我不确定我创建的"共享层"是否符合我的需求。示例中的两个隐藏层是否使用相同的权重,或者我是否创建了一个层的两个不同实例,它们只有共同的结构?如果没有,有没有办法实现我想要的?
# create shared_layer
inputs = Input(shape=(784,))
outputs = layers.Dense(784, activation='relu')(inputs)
shared_layer = Model(inputs=inputs, outputs=outputs)
# create model
visible = Input(shape=(28, 28, 1))
flat = layers.Flatten()(visible)
hidden = shared_layer(flat)
hidden2 = shared_layer(hidden)
output = layers.Dense(10, activation='softmax')(hidden2)
new_model = Model(inputs=visible, outputs=output)
当我查看模型的摘要时,我得到这个:
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_4 (InputLayer) (None, 28, 28, 1) 0
__________________________________________________________________________________________________
flatten_2 (Flatten) (None, 784) 0 input_4[0][0]
__________________________________________________________________________________________________
model_3 (Model) (None, 784) 615440 flatten_2[0][0]
model_3[1][0]
__________________________________________________________________________________________________
dense_4 (Dense) (None, 10) 7850 model_3[2][0]
==================================================================================================
它是共享的,但你正在做不必要的事情。
您可以:
shared_layer = layers.Dense(784, activation='relu')
visible = Input(shape=(28, 28, 1))
flat = layers.Flatten()(visible)
hidden = shared_layer(flat)
hidden2 = shared_layer(hidden)
output = layers.Dense(10, activation='softmax')(hidden2)
new_model = Model(inputs=visible, outputs=output)