Search code examples
pythonmachine-learningkerasconv-neural-networkkeras-layer

Delete last layer and insert three Conv2D layers in Keras


I have a model in Keras for classification that I trained on some dataset. Call that model "classification_model". That model is saved in "classification.h5". Model for detection is the same, except that we delete last convolutional layer, and add three Conv2D layers of size (3,3). So, our model for detection "detection_model" should look like this:

detection_model = classification_model[: last_conv_index] + Conv2d + Conv2d + Conv2d.

How can we implement that in Keras?


Solution

  • Well, load your classification model and use Keras functional API to construct your new model:

    model = load_model("classification.h5")
    
    last_conv_layer_output = model.layers[last_conv_index].output
    conv = Conv2D(...)(last_conv_layer_output)
    conv = Conv2D(...)(conv)
    output = Conv2D(...)(conv)
    
    new_model = Model(model.inputs, output)
    
    # compile the new model and save it ...