How to model a shared layer in keras?

Viewed 5043

I want to train a model with a shared layer in the following form:

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

x and y are two separate input layers and F is a shared layer. G is the last layer after concatenating F(x) and F(y).

Is it possible to model this in Keras? How?

1 Answers

You can use Keras functional API for this purpose:

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 ...

Note that x and y could be the output tensors of any layer and not necessarily input layers.

Related