Home > database >  Replacing a Keras layer in a pretrained model with another layer
Replacing a Keras layer in a pretrained model with another layer

Time:01-23

I am using Keras with Tensorflow version 2.7 as backend. I am referring to the stackoverflow post at enter image description here

Modified vgg16

#One of the following two:
#model_input=vgg.input
model_input=tf.keras.Input(shape=(224, 224, 3,))

x=model_input
for layer in vgg.layers[1:]:
    if isinstance(layer, tf.keras.layers.MaxPooling2D):
        kwargs=layer.get_config()
        x=tf.keras.layers.AveragePooling2D(**kwargs)(x)
    else:
        x=layer(x)
model=tf.keras.Model(inputs=model_input, outputs=x, name="vgg_avg")
model.summary()

Output:

enter image description here


Notes

By replacing the MaxPooling2D layers with their AveragePooling2D counterparts, the originally-optimized weights may not be optimal anymore. So, some level of tuning (with small learning rate) might be needed.

  • Related