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
推荐阅读
- 报错|TCP connection timed out: 10060: 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。
- Python|urllib.error.URLError(urlopen error [WinError 10060])
- imsave函数不能用解决方法
- ImportError: cannot import name 'imsave' from 'scipy.misc' (C:\Users\DELL\AppData\Roaming\Python\Pyt
- 成功解决DLL load failed: 页面文件太小,无法完成操作
- 成功解决RuntimeError: Variable += value not supported. Use variable.assign_add(value) to modify the vari
- Git clone项目失败,提示git did not exit cleanly(exit code 1)的解决办法
- TypeError: 'float' object cannot be interpreted as an integer
- 报错|SMPlayer在ubuntu16.04下没有声音的解决办法| mysql无法修改