Shapes incompatible with DenseNet transfer learning

261 views Asked by At

I want to do transfer learning with DenseNet, and I found an example I want to work off of.

model_d=DenseNet121(weights='imagenet',include_top=False, 
input_shape=(224, 224, 3)) 

x=model_d.output

x= GlobalAveragePooling2D()(x)
x= BatchNormalization()(x)
x= Dropout(0.5)(x)
x= Dense(1024,activation='relu')(x) 
x= Dense(512,activation='relu')(x) 
x= BatchNormalization()(x)
x= Dropout(0.5)(x)

preds=Dense(7,activation='softmax')(x) 

model=Model(inputs=model_d.input,outputs=preds) 
model.summary()

So this is replacing the output of the original model with these layers. When I try to fit the model however, I get an incompatible shape error:

ValueError: Shapes (None, 1) and (None, 7) are incompatible

However, looking at the model summary, I have no idea what the cause of this would be.

1

There are 1 answers

1
Saurav Rai On

I think you are having only one class for prediction after the Softmax function but preds=Dense(7,activation='softmax')(x) expects to have 7 classes for prediction. Changing the number 7 to 1 might solve your problem if you are predicting only 1 class. Also you should change your activation to sigmoid, otherwise having 1 neuron with softmax will always output 1

Note that this is just my assumption.