1

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)
1
  • global average pooling layer yes it must be also 4d as other layers and you have some 2d input to it
    – snamef
    Commented Aug 14, 2019 at 11:36

1 Answer 1

2

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.