JLL
JLL

Reputation: 15

Value Error: Shapes (None, 21) and (None, 7, 7, 21) are incompatible

Hello I am new to using keras. and I am doing an exercise with the VGG16 model.

I have loaded the model and now I have to Replace the last 3 fully connected layers with 3 new layers: the first 2 of 50 and 20 neurons respectively with ReLU activation, and a last layer with the appropriate number of neurons.

I have done the following:

enter code here

# Freeze the weights of the pretrained model layers
for layer in base_model.layers:
    layer.trainable = False

# Replace the last 3 fully connected layers with 3 new layers
x = base_model.output
x = Dense(50, activation='relu')(x)
x = Dense(20, activation='relu')(x)
x = Dense(num_classes, activation='softmax')(x)

# Create a new model by joining the base of VGG16 with the new layers
model = Model(inputs=base_model.input, outputs=x)

the model.summary() is like this:

=================================================================

input_13 (InputLayer) [(None, 224, 224, 3)] 0

block1_conv1 (Conv2D) (None, 224, 224, 64) 1792

block1_conv2 (Conv2D) (None, 224, 224, 64) 36928

block1_pool (MaxPooling2D) (None, 112, 112, 64) 0

block2_conv1 (Conv2D) (None, 112, 112, 128) 73856

block2_conv2 (Conv2D) (None, 112, 112, 128) 147584

block2_pool (MaxPooling2D) (None, 56, 56, 128) 0

block3_conv1 (Conv2D) (None, 56, 56, 256) 295168

block3_conv2 (Conv2D) (None, 56, 56, 256) 590080

block3_conv3 (Conv2D) (None, 56, 56, 256) 590080

block3_pool (MaxPooling2D) (None, 28, 28, 256) 0

block4_conv1 (Conv2D) (None, 28, 28, 512) 1180160

block4_conv2 (Conv2D) (None, 28, 28, 512) 2359808

block4_conv3 (Conv2D) (None, 28, 28, 512) 2359808

block4_pool (MaxPooling2D) (None, 14, 14, 512) 0

block5_conv1 (Conv2D) (None, 14, 14, 512) 2359808

block5_conv2 (Conv2D) (None, 14, 14, 512) 2359808

block5_conv3 (Conv2D) (None, 14, 14, 512) 2359808

block5_pool (MaxPooling2D) (None, 7, 7, 512) 0

dense_6 (Dense) (None, 7, 7, 50) 25650

dense_7 (Dense) (None, 7, 7, 20) 1020

dense_8 (Dense) (None, 7, 7, 21) 441

=================================================================

Total params: 14,741,799 Trainable params: 27,111 Non-trainable params: 14,714,688


When I try to train the model it gives me the following error:

"ValueError: Shapes (None, 21) and (None, 7, 7, 21) are incompatible"

What could be the problem?

Thanks!

Upvotes: 0

Views: 80

Answers (1)

Jurgy
Jurgy

Reputation: 2370

Flatten the output layer:


x = base_model.output
x = Flatten(name="flatten")(x)
x = Dense(50, activation='relu')(x)
x = Dense(20, activation='relu')(x)
x = Dense(num_classes, activation='softmax')(x)

Upvotes: 1

Related Questions