Search code examples
pythonkerasconv-neural-networkkeras-layer

TypeError: The added layer must be an instance of class Layer. Found: <keras.engine.input_layer.InputLayer object at 0x7fc6f1b92240>


I am trying to add vgg16 layers to Sequential model but getting the error mentioned in the Question Title

from keras.applications.vgg16 import VGG16

from tensorflow.contrib.keras.api.keras.models import Sequential
vgg_model = VGG16()
model = Sequential()
#print(model.summary())
for layer in vgg_model.layers:
        model.add(layer)

print(model.summary())

I am using keras 2.2.4

TypeError: The added layer must be an instance of class Layer. Found: <keras.engine.input_layer.InputLayer object at 0x7fc6f1b92240>

Solution

  • Let's say you want to drop the last layer and add your own last full connected layer with 10, nodes. To achieve this keras functional API can be used.

    from tensorflow.contrib.keras.api.keras.models import Sequential
    import keras
    from keras_applications.vgg16 import VGG16
    vgg_model = VGG16()
    
    # replace the last layer with new layer with 10 nodes.
    last_layer = vgg_model.layers[-2].output ## 
    output = keras.layers.Dense(10, activation="softmax")(last_layer) 
    
    model = keras.models.Model(inputs=vgg_model.inputs, outputs=output)
    model.summary()
    
    
    print(model.summary())
    

    Or using include_top = False

    vgg_model = VGG16(include_top=False)
    vgg_output = vgg_model.outputs[0]
    output = keras.layers.Dense(10, activation="softmax")(vgg_output)
    
    model = keras.models.Model(inputs=vgg_model.inputs, outputs=output)
    

    You may want to use pretrained weights. You can acheive this by using weights argument

    vgg_model = VGG16(weights='imagenet',include_top=False)
    

    You may want to freeze some of layers.

    number_of_layers_to_freeze = 10
    vgg_model = VGG16(include_top=False)
    for i in range(number_of_layers_to_freeze):
        vgg_model.layers[i].trainable = False
    vgg_output = vgg_model.outputs[0]
    output = keras.layers.Dense(10, activation="softmax")(vgg_output)
    
    model = keras.models.Model(inputs=vgg_model.inputs, outputs=output)