如何在keras中为共享层建模?

How to model a shared layer in keras?

我想按以下形式训练具有共享层的模型:

x --> F(x)
          ==> G(F(x),F(y))
y --> F(y) 

xy 是两个独立的输入层,F 是共享层。 G 是连接 F(x)F(y) 后的最后一层。

可以在 Keras 中建模吗?怎么样?

您可以使用 Keras functional API 来达到这个目的:

from keras.layers import Input, concatenate

x = Input(shape=...)
y = Input(shape=...)

shared_layer = MySharedLayer(...)
out_x = shared_layer(x)
out_y = shared_layer(y)

concat = concatenate([out_x, out_y])

# pass concat to other layers ...

请注意,xy 可以是任何层的输出张量,不一定是输入层。