keras.utils.to_categorical中的num_class参数(IndexError: index 5 is out of bounds for axis 1 with size 5)

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/weixin_42886817/article/details/100118621

keras.utils.to_categorical函数用来作什么?

用来将整数型标签转化为onehot数据。
例如,原来使用数组labels=[[1],[2],[5],[4],[5],[2],[3]]表示标签,只有使用keras.utils.to_categorical函数将其转化为onehot数据后,才能交由网络进行训练。

keras.utils.to_categorical定义

to_categorical(y, num_classes=None, dtype='float32')

其中y是待转换的标签数组。
num_class是标签中共有多少种类。
dtype则是转化的目标数据类型。

num_class使用时存在的问题

  • 如果要指定num_class,需要明白:onehot其中种类从0开始编码
    如果你的标签数组是从1开始编码的,例如:labels=[[1],[2],[5],[4],[5],[2],[3]]
    此时,函数会自动认为类别共有0-5 ,6种,而不是五种
    如果指定参数num_class=5,则会报错:
    如下所示:
from keras.utils import np_utils

labels=[[1],[2],[5],[4],[5],[2],[3]]
onehot_labels2=np_utils.to_categorical(labels,num_classes=5)

错误信息如下:
IndexError: index 5 is out of bounds for axis 1 with size 5

此时,将num_class指定为6,即可通过,且运行结果与不指定num_class时是一样的,因为num_class的默认值是标签中最大数+1,如下所示:


from keras.utils import np_utils

labels=[[1],[2],[5],[4],[5],[2],[3]]
onehot_labels1=np_utils.to_categorical(labels)
onehot_labels2=np_utils.to_categorical(labels,num_classes=6)
print(labels)
print(onehot_labels1)
print(onehot_labels2)

运行结果:

[[1], [2], [5], [4], [5], [2], [3]]
[[0. 1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0.]]
[[0. 1. 0. 0. 0. 0.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 0. 0. 1. 0.]
 [0. 0. 0. 0. 0. 1.]
 [0. 0. 1. 0. 0. 0.]
 [0. 0. 0. 1. 0. 0.]]

我们可以看到,一共有6列,但是这和我们要求的类别数不一样。
因此,我们可以对标签内每个数减一,使其从0开始。

猜你喜欢

转载自blog.csdn.net/weixin_42886817/article/details/100118621