Minh-Long Luu
Minh-Long Luu

Reputation: 2731

TF/Keras: how to stack model

I wonder how to stack model in Keras? I want to give Input to the 2 models, take the output to feed it in the Meta model, like this:

enter image description here

If I declare like this:

inputs = tf.keras.Input(...)
x = Dense()(inputs)
y = RNN()(inputs)

meta = Add()([x, y])
meta = Dense()(meta)
model = tf.keras.Model(inputs=inputs, outputs=meta)

That piece of code is still ONE model, just inputs taking parallel paths.

P/S: I already read this answer, but I think it is just inputs taking parallel paths: How to vertically stack trained models in keras?

Upvotes: 0

Views: 214

Answers (1)

Peng Guanwen
Peng Guanwen

Reputation: 722

Keras Models are Layers as well. So just create your models separately, and combine them in your meta model.

# model1
a = Input(shape=(...))
b = Dense()(a)
model1 = Model(inputs=a, outputs=b)

# model2
a = Input(shape=(...))
b = RNN(...)(a)
model2 = Model(inputs=a, outputs=b)

# combine them in meta model
inputs = tf.keras.Input(...)
x = model1(inputs)
y = model2(inputs)

meta = Add()([x, y])
meta = Dense()(meta)
model = tf.keras.Model(inputs=inputs, outputs=meta)

Upvotes: 1

Related Questions