Reputation: 125
Trying to implement ResNet50 on a custom dataset using transfer learning, however get this error:
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]
Here's my code:
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)
I've set the include_top to False as suggested in some other answers. Where am I going wrong and how do I fix this?
Upvotes: 0
Views: 611
Reputation: 1890
We don't need GlobalAveragePooling2D
in this case, try this code:
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)
Upvotes: 1