Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to vertically stack trained models in keras?

I have two trained models in keras that i want to stack one on the top of another to form one single model. I want to do this to combine my trained models into one.

enter image description here

I think merge(Merge) is for stacking models horizontally whereas I want to stack keras functional API models vertically.

PS : Output 1's shape is identical to Input 2

like image 381
Manipal King Avatar asked Apr 30 '18 00:04

Manipal King


2 Answers

inputA = Input(input_shape_for_A)
outputA = modelA(inputA)
outputB = modelB(outputA)

modelC = Model(inputA, outputB)
like image 160
Daniel Möller Avatar answered Sep 28 '22 07:09

Daniel Möller


The above method works fine. But when try modelC.summary() it will print only modelA, modelB names. Because you are creating a model in which it has models. Means modelC has modelA and modelB, not the layers. But modelA and modelB, have layers, so you can access modelA.summary(), modelB.summary(). You don't need what happens in modelC. Cause it just holds modelA and modelB together, like a single model. To get modelC.summary(), you have to just follow this:

modelC = Sequential()

#since modelA input shape is also input shape for modelC
modelC.add(modelA.input)

# this adds all layers to modelC from modelA
for layer in modelA.layers:
    modelC.add(layer)

# since modelA output is input to modelB, you don't want any Input here, just add layers stacked to previous layers in modelC from modelB
for layer in modelB.layers:
    modelC.add(layer)

To check overall modelC, see modelC.input, this must match modelA.input and modelC.output, this must match modelB.output. To check whole model, modelC.summary(), and also verify whether all layers from modelA, and modelB are in modelC. If any quires, please feel free to ask. The above is useful you don't need this much of work but since you asked for layer names and connection, I replied this to you.

like image 33
Krishna Rohith Avatar answered Sep 28 '22 07:09

Krishna Rohith