如何解决“一号编码”中“索引3超出轴1的3号范围”的问题?

时间:2019-04-08 05:51:23

标签: python numpy

我正在使用python进行一键编码。但是当我运行一次热编码时会出现一些问题

/

这就是我以前运行的一键结束代码

数据就是这样...

Jurisdiction

发生此错误

  

“索引3超出了尺寸为3的轴1的边界”

然后我尝试另一条路径...

更改代码部分

def one_hot_encode(labels):
    n_labels = len(labels)
    n_unique_labels = len(np.unique(labels))
    one_hot_encode = np.zeros((n_labels,n_unique_labels))
    one_hot_encode[np.arange(n_labels), labels] = 1
    return one_hot_encode

这正在运行,但它不是3类... 结果是这样的

[3 3 3 3 3 2 2 2 2 2 1 1 1 1 1]

如何解决此问题?

1 个答案:

答案 0 :(得分:0)

错误从[3 3 3 3 3 2 2 2 2 2 1 1 1 1 1]开始。映射np.array中有3个,这意味着在某些位置上您试图等于index 3 to 1,但问题是映射数组中的最大索引为 2 < / strong>。

def one_hot_encode(labels):
    n_labels = len(labels) # this will give 15
    n_unique_labels = len(np.unique(labels)) # this will give 3
    one_hot_encode = np.zeros((n_labels,n_unique_labels)) # will create 15x3 matrix
    one_hot_encode[np.arange(n_labels), labels] = 1 # error here you try to map index 3 to 1 which does not exist
    return one_hot_encode

只需将映射数组从[3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]更改为[2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]