首页 > 解决方案 > ResNet50:层global_average_pooling2d_2的输入0与层不兼容:预期ndim=4,发现ndim=2

问题描述

尝试使用迁移学习在自定义数据集上实现 ResNet50,但出现此错误:

ValueError: Input 0 of layer global_average_pooling2d_2 is incompatible with the layer: expected ndim=4, found ndim=2. Full shape received: [None, 2048]

这是我的代码:

img_height, img_width = (224, 224)
batch_size = 32

train_generator = train_datagen.flow_from_directory(
train_data_dir,
target_size = (img_height, img_width),
batch_size = batch_size,
class_mode = 'categorical',
subset = 'training')


base_model = ResNet50(include_top = False, weights = 'imagenet', pooling='avg')
x = base_model.output
x = GlobalAveragePooling2D()(x)
x = Dense(1024, activation = 'relu')(x)
predictions = Dense(train_generator.num_classes, activation = 'softmax')(x)
model = Model(inputs = base_model.input, outputs = predictions)

for layer in base_model.layers:
    layer.trainable = False
    
model.compile(optimizer = 'adam', loss = 'categorical_crossentropy', metrics = ['accuracy'])

model.fit(train_generator, epochs = 10)

我已按照其他答案中的建议将 include_top 设置为 False。我哪里出错了,我该如何解决?

标签: machine-learningdeep-learningneural-networkcomputer-visionconv-neural-network

解决方案


在这种情况下我们不需要GlobalAveragePooling2D,试试这个代码:

base_model = ResNet50(include_top = False, weights = 'imagenet', pooling='avg')
x = base_model.output
x = Dense(1024, activation = 'relu')(x)
predictions = Dense(train_generator.num_classes, activation = 'softmax')(x)
model = Model(inputs = base_model.input, outputs = predictions)

推荐阅读