Search code examples
kerastransfer-learning

In Keras, does using include_top= False on my own model will remove all last dense layer and can I define the "top" of my model?


Can I define what layers I want to be define as "top".

As I understand, include_top= false will remove all denses layer on top. I want to use "include_top=False" for transfert learning with my own models and don't want all my last dense layer to be automaticly remove.


Solution

  • to access the last dense layers you have to set include_top = True. In this way, you can create a sub-model with all the intermediate layers you want. here an example with VGG16

    from tensorflow.keras.layers import *
    from tensorflow.keras.models import *
    from tensorflow.keras.applications import VGG16
    
    vgg = VGG16(include_top = True, input_shape = (224,224,3))
    new_layer = Dense(32)(vgg.layers[-3].output) # add new layer
    
    sub_model = Model(vgg.input, new_layer)
    

    the last layers of sub_model in this case are:

    block5_conv3 (Conv2D)        (None, 14, 14, 512)       2359808   
    _________________________________________________________________
    block5_pool (MaxPooling2D)   (None, 7, 7, 512)         0         
    _________________________________________________________________
    flatten (Flatten)            (None, 25088)             0         
    _________________________________________________________________
    fc1 (Dense)                  (None, 4096)              102764544 
    _________________________________________________________________
    dense_6 (Dense)              (None, 32)                131104