categorical[np.arange(n), y] = 1 IndexError: index 2 is out of bounds for axis 1 with size 2

本文探讨了在使用Keras的to_categorical函数时遇到的错误,即当标签不是连续数值且num_classes设置不当时。解决方法包括确认标签类型并将其转换为numpy数组,以及根据实际类别数量调整num_classes。案例分析了将非连续数值标签编码为one-hot的问题和调整后的解决方案。
摘要由CSDN通过智能技术生成

报错详情:

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.]]

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值