I train a model A
and try to use the output of the intermediate layer with the name=\"layer_x\"
as an additional input for model B
.
There are two things that you seem to be doing wrong :
intermediate_output = intermediate_layer_model.predict(data)
when you do .predict()
, you are actually passing data through the graph and asking what will be the result. When you do that, intermediate_output
will be a numpy array and not a layer as you would like it to be.
Secondly, you don't need to recreate a new intermediate model. You can directly use the part of model_a
that interest you.
Here is a code that "compiles" for me :
from keras.layers import Input, Dense, concatenate
from keras.models import Model
inputs = Input(shape=(100,))
dnn = Dense(1024, activation='relu')(inputs)
dnn = Dense(128, activation='relu', name="layer_x")(dnn)
dnn = Dense(1024, activation='relu')(dnn)
output = Dense(10, activation='softmax')(dnn)
model_a = Model(inputs=inputs, outputs=output)
# You don't need to recreate an input for the model_a,
# it already has one and you can reuse it
input_b = Input(shape=(200,))
# Here you get the layer that interests you from model_a,
# it is still linked to its input layer, you just need to remember it for later
intermediate_from_a = model_a.get_layer("layer_x").output
# Since intermediate_from_a is a layer, you can concatenate it with the other input
merge_layer = concatenate([input_b, intermediate_from_a])
dnn_layer = Dense(512, activation="relu")(merge_layer)
output_b = Dense(5, activation="sigmoid")(dnn_layer)
# Here you remember that one input is input_b and the other one is from model_a
model_b = Model(inputs=[input_b, model_a.input], outputs=output_b)
I hope this is what you wanted to do.
Please tell me if something isn't clear :-)