我正在尝试使用Keras的函数式API实现一个神经网络,该网络在多个层中使用相同的权重。代码是可以运行的,但我不能确定我创建的“共享层”是否达到了我想要的效果。示例中的两个隐藏层是否使用了相同的权重,还是我创建了两个不同实例的层,仅有结构相同?如果不是这样,有没有办法实现我想要的效果?
# create shared_layerinputs = Input(shape=(784,))outputs = layers.Dense(784, activation='relu')(inputs)shared_layer = Model(inputs=inputs, outputs=outputs)# create modelvisible = 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)