Reputation: 471
I am trying to fine-tune a VGG16 model. I have removed the last 5 layers
(*block5_pool (MaxPooling2D),flatten(Flatten),fc1 (Dense),fc2 (Dense),predictions (Dense)*).
Now, I want to add a global average pooling layer, but I am getting this error
Input 0 is incompatible with layer global_average_pooling2d_4: expected ndim=4, found ndim=2**
what seems to be the problem here?
model = VGG16(weights='imagenet', include_top=True)
model.layers.pop()
model.layers.pop()
model.layers.pop()
model.layers.pop()
model.layers.pop()
x = model.output
x = GlobalAveragePooling2D()(x)
Upvotes: 1
Views: 2127
Reputation: 33410
If want to remove the last four layers, then just use include_top=False
. Further, use pooling='avg'
to add a GlobalAveragePooling2D
layer as the last layer:
model = VGG16(weights='imagenet', include_top=False, pooling='avg')
A note about why your original solution does not work: as already suggested in this answer, you can't use pop()
method on layers
attribute of the models to remove a layer. Instead, you need to reference their output directly (e.g. model.layers[-4].output
) and then feed them to other layers if you want to add new connections.
Upvotes: 2