报错详情:
categorical[np.arange(n), y] = 1 IndexError: index 34 is out of bounds for axis 1 with size 29
错误的原因一(来自网上):
这是因为train_labels不是numpy.array的形式,需要把train_labels转化为numpy数组的形式
自己输出类型,发现训练数据的标签类型为 numpy.array,那为什么还报错?
原因二:
我的数据标签是不连续的数值,最小值为1,最大值为36,不重复计数为29个,所以我刚开始将num_classes值设为29,由于使用的是to_categorical,最终编码为one-hot格式,它不会因为1-36之间有的数没出现而不给它编码。
将num_classes值设为37后,再没有报错。
from keras.utils.np_utils import to_categorical
#类别向量定义
b = [0,1,2,3,4,5,6,7,8,0]
#调用to_categorical将b按照9个类别来进行转换
x = to_categorical(b, 9)
print(x)
[[1. 0. 0. 0. 0. 0. 0. 0. 0.]
[0. 1. 0. 0. 0. 0. 0. 0. 0.]
[0. 0. 1. 0. 0. 0. 0. 0. 0.]
[0. 0. 0. 1. 0. 0. 0. 0. 0.]
[0. 0. 0. 0. 1. 0. 0. 0. 0.]
[0. 0. 0. 0. 0. 1. 0. 0. 0.]
[0. 0. 0. 0. 0. 0. 1. 0. 0.]
[0. 0. 0. 0. 0. 0. 0. 1. 0.]
[0. 0. 0. 0. 0. 0. 0. 0. 1.]
[1. 0. 0. 0. 0. 0. 0. 0. 0.]]