keras: Use one model output as another model input

cwzat cwzat picture cwzat cwzat · Dec 6, 2017 · Viewed 11.5k times · Source

I am adding a dense layer before InceptionResNetV2 model(pre-trained) This is InceptionResNetV2 output

model_base = InceptionResNetV2(include_top=True, weights='imagenet')
x = model_base.get_layer('avg_pool').output
x = Dense(3, activation='softmax')(x)

This is the layer will be added

input1 = Input(shape=input_shape1)
pre1 = Conv2D(filters=3, kernel_size=(5, 5), padding='SAME', 
input_shape=input_shape1, name='first_dense')(input1)
pre = Model(inputs=input1, outputs=pre1)

This is combining two models

 after = Model(inputs=pre.output, outputs=x)

 model = Model(inputs=input1, outputs=after.output)

 model.compile(optimizer='sgd', loss='categorical_crossentropy', metrics=['accuracy'])

use

pre.output

as

after.input

But it doesn't works . How can I resolve it?

Answer

Daniel Möller picture Daniel Möller · Dec 6, 2017

First let's create a new model from model_base, because you want to get an earlier output.

Your code:

model_base = InceptionResNetV2(include_top=True, weights='imagenet')
x = model_base.get_layer('avg_pool').output
x = Dense(3, activation='softmax')(x)

New model_base:

model_base = Model(model_base.input, x)

Now, it's important to pass the output pre1 to this model:

base_out = model_base(pre1)     

That's it:

model = Model(input1, base_out)