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

后端 未结 9 1790
不思量自难忘°
不思量自难忘° 2020-12-04 17:26

I am working on training a VGG16-like model in Keras, on a 3 classes subset from Places205, and encountered the following error:

ValueError: Error when chec         


        
9条回答
  •  甜味超标
    2020-12-04 18:18

    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_categorical
    train_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'.

提交回复
热议问题