how can I overcome “ValueError: Shapes (None, 1) and (None, 7) are incompatible”

天大地大妈咪最大 提交于 2021-02-20 04:24:27

问题


I am new to Keras and CNN. I am working on an assignment to build a CNN for predicting face emotions. I built the model as per the assignment but while compiling the model I get "ValueError: Shapes (None, 1) and (None, 7) are incompatible". Can someone help me how to resolve this?

Pasting my code below for reference:

'''

model = Sequential()

model.add(Conv2D(filters = 64, kernel_size = 5,input_shape = (48,48,1)))
model.add(Conv2D(filters=64, kernel_size=5,strides=(1, 1), padding='valid'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2),strides=1, padding='valid'))
model.add(Activation('relu'))

model.add(Conv2D(filters = 128, kernel_size = 5))
model.add(Conv2D(filters = 128, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Conv2D(filters = 256, kernel_size = 5))
model.add(Conv2D(filters = 256, kernel_size=5))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2,2)))
model.add(Activation('relu'))

model.add(Flatten())
model.add(Dense(128))
model.add(BatchNormalization())
model.add(Activation('relu'))
model.add(Dropout(0.25))
model.add(Dense(7,activation='softmax'))

''' 'Then tried to compile' '''

model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
history = model.fit(input_array, output_array, batch_size = 64, epochs= 20, validation_split=0.10,)

''' 'This gives the error' 'ValueError: Shapes (None, 1) and (None, 7) are incompatible' 'I am using google colab for this'


回答1:


You are most likely using your labels sparsely encoded, like [0,1,2,3,4,5,6] instead of a one-hot-encoded form.

Your solution one of the below:

  1. Use the one-hot-encoded form, i.e. transform each label to an array of length == number_of_classes. That is, for 0 you would have [1,0,0,0,0,0,0] for 1 you would have [0,1,0,0,0,0,0] etc.
  2. Use sparse_categorical_crossentropy. If you use this loss functions, the OHE step is done behind the scenes and you no longer need to process your input training + validation labels.



回答2:


If you use one-hot-encoded for the label like [0, 0, 0, 0, 0, 0, 1] you need to use categorical_crossentropy but if you use sparse label like [1, 2, 3, 4, 5, 6, 7] you need to use sparse_categorical_crossentropy.



来源:https://stackoverflow.com/questions/62148508/how-can-i-overcome-valueerror-shapes-none-1-and-none-7-are-incompatible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!