Search code examples
pythonkeraspre-trained-model

How to use a pretrained keras model to be a parameter to a Model's add function?


I am applying the pretrained model tutorial from Deep Learning with python to a dataset on kaggle. Below is my CNN architecture code, though simple I am getting this error:

TypeError: The added layer must be an instance of class Layer. Found: keras.engine.training.Model object at 0x7fdb6a780f60

I have been able to do this while just using native keras but I run into problems when trying to utilize with tensorflow 2.0

from keras.applications.vgg16 import VGG16

base = VGG16(weights='../input/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
             include_top=False,
             input_shape=(150,225,3))

model = models.Sequential()
model.add(base)
model.add(layers.Flatten())
model.add(layers.Dense(256, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

base.summary()

Solution

  • You need to switch to the functional API since the sequential model only accepts layers:

    from keras.applications.vgg16 import VGG16
    
    base = VGG16(weights='../input/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels_notop.h5',
                 include_top=False,
                 input_shape=(150,225,3))
    
    in = Input(shape=(150,225,3))
    base_out = base(in)
    out = Flatten()(base_out)
    out = Dense(256, activation='relu')
    out = Dense(1, activation='sigmoid')
    model = Model(in, out)
    model.summary()
    

    Notice how you can use a model as a layer in the functional API.