Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a model trained in keras?

I trained a model with 4 hidden layers and 2 dense layers and I have saved that model.

Now I want to load that model and want to split into two models, one with one hidden layers and another one with only dense layers.

I have splitted the model with hidden layer in the following way

model = load_model ("model.hdf5")
HL_model = Model(inputs=model.input, outputs=model.layers[7].output)

Here the model is loaded model, in the that 7th layer is my last hidden layer. I tried to split the dense in the like

DL_model = Model(inputs=model.layers[8].input, outputs=model.layers[-1].output)

and I am getting error

TypeError: Input layers to a `Model` must be `InputLayer` objects.

After splitting, the output of the HL_model will the input for the DL_model.

Can anyone help me to create a model with dense layer?


PS : I have tried below code too

from keras.layers import Input 
inputs = Input(shape=(9, 9, 32), tensor=model_1.layers[8].input)
model_3 = Model(inputs=inputs, outputs=model_1.layers[-1].output)

And getting error as

RuntimeError: Graph disconnected: cannot obtain value for tensor Tensor("conv2d_1_input:0", shape=(?, 144, 144, 3), dtype=float32) at layer "conv2d_1_input". The following previous layers were accessed without issue: []

here (144, 144, 3) in the input image size of the model.

like image 645
Akhilesh Avatar asked Mar 09 '18 12:03

Akhilesh


1 Answers

You need to specify a new Input layer first, then stack the remaining layers over it:

DL_input = Input(model.layers[8].input_shape[1:])
DL_model = DL_input
for layer in model.layers[8:]:
    DL_model = layer(DL_model)
DL_model = Model(inputs=DL_input, outputs=DL_model)
like image 144
jdehesa Avatar answered Nov 15 '22 16:11

jdehesa