keras报错Error when checking target: expected dense_1 to have shape (5,) but got array with shape (1,)

【keras报错Error when checking target: expected dense_1 to have shape (5,) but got array with shape (1,)】ValueError: Error when checking target: expected dense_1 to have shape (5,) but got array with shape (1,)
描述:五分类
原因: One-hot 编码的原因
解决方法:添加相关代码

from keras.utils import np_utilstrain_label3 = np.load('./label.npy') test_label3 = np.load('./test_label.npy')nb_classes3 = 5 train_label3 = np_utils.to_categorical(train_label3, nb_classes3) test_label3 = np_utils.to_categorical(test_label3, nb_classes3)

最好还添加一下:
train_data3 = train_data3.astype('float32') # 数据归一化 test_data3 = test_data3.astype('float32') train_data3 /= 255 test_data3 /= 255

完整代码:
from keras.utils import np_utilstrain_label3 = np.load('./label.npy') test_label3 = np.load('./test_label.npy')nb_classes3 = 5 train_label3 = np_utils.to_categorical(train_label3, nb_classes3) test_label3 = np_utils.to_categorical(test_label3, nb_classes3) train_data3 = train_data3.astype('float32') # 数据归一化 test_data3 = test_data3.astype('float32') train_data3 /= 255 test_data3 /= 255

另一种解决方案:
将loss='categorical_crossentropy' 改为loss='sparse_categorical_crossentropy'

categorical_crossentropy 和 sparse_categorical_crossentropy 的区别
如果是 one-hot 编码,则使用 categorical_crossentropy
one-hot 编码:[0, 0,1], [1, 0, 0], [0, 1, 0]
如果你的 tagets 是 数字编码 ,用sparse_categorical_crossentropy
数字编码:2, 0, 1

    推荐阅读