简体   繁体   中英

Input 0 is incompatible with layer global_average_pooling2d_4: expected ndim=4, found ndim=2 error

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)

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 (eg model.layers[-4].output ) and then feed them to other layers if you want to add new connections.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM