Error when checking target: expected dense_3 to have shape (3,) but got array with shape (1,) Error when checking target: expected dense_3 to have shape (3,) but got array with shape (1,) python-3.x python-3.x

Error when checking target: expected dense_3 to have shape (3,) but got array with shape (1,)


The problem is with your label-data shape. In a multiclass problem you are predicting the probabibility of every possible class, so must provide label data in (N, m) shape, where N is the number of training examples, and m is the number of possible classes (3 in your case).

Keras expects y-data in (N, 3) shape, not (N,) as you've problably provided, that's why it raises an error.

Use e.g. OneHotEncoder to convert your label data to one-hot encoded form.


As mentioned by others, Keras expects "one hot" encoding in multiclass problems.

Keras comes with a handy function to recode labels:

print(train_labels)[1. 2. 2. ... 1. 0. 2.]print(train_labels.shape)(2000,)

Recode labels using to_categorical to get the correct shape of inputs:

from keras.utils import to_categoricaltrain_labels = to_categorical(train_labels)print(train_labels)[[0. 1. 0.] [0. 0. 1.] [0. 0. 1.] ... [0. 1. 0.] [1. 0. 0.] [0. 0. 1.]]print(train_labels.shape)(2000, 3)  # viz. 2000 observations, 3 labels as 'one hot'

Other importent things to change/check in multiclass (compared to binary classification):

Set class_mode='categorical' in the generator() function(s).

Don't forget that the last dense layer must specify the number of labels (or classes):

model.add(layers.Dense(3, activation='softmax'))

Make sure that activation= and loss= is chosen so to suit multiclass problems, usually this means activation='softmax' and loss='categorical_crossentropy'.


Had the same issue. To solve the problem you can simply change in validation_generator and train_generator the class mode from 'binary' to 'categorical' - that's because you have 3 classes-which is not binary.