输入 0 与层 global_average_pooling2d_4 不兼容:预期 ndim=4,发现 ndim=2 错误

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

我正在尝试微调 VGG16 模型。我已经删除了最后 5 层

(*block5_pool (MaxPooling2D),flatten(Flatten),fc1 (Dense),fc2 (Dense),predictions (Dense)*). 

现在,我想添加一个全局平均池化层,但出现此错误

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

这似乎是什么问题?

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)

如果要删除最后四层,则只需使用include_top=False。进一步,使用pooling='avg'添加一个GlobalAveragePooling2D层作为最后一层:

model = VGG16(weights='imagenet', include_top=False, pooling='avg')

关于为什么您的原始解决方案不起作用的注释:正如 中已经建议的那样,您不能在模型的 layers 属性上使用 pop() 方法来删​​除层。相反,您需要直接引用它们的输出(例如 model.layers[-4].output),然后如果您想添加新连接,则将它们提供给其他层。