python - how to fix "index 3 is out of bounds for axis 1 with size 3" in one-hot encoding?
问题描述
I was working on one-hot encoding using python. but there is some problem when i run one-hot-encoding
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
this is what i used to running one-hot endcode
and the data is like this...
[3 3 3 3 3 2 2 2 2 2 1 1 1 1 1]
It occurs this error
"index 3 is out of bounds for axis 1 with size 3"
And i try another path...
change the part of code
one_hot_encode = np.zeros((n_labels,n_unique_labels+1))
This is running but it its not the 3 classes... The result is like this
array([[0., 0., 0., 1.],
[0., 0., 0., 1.],
[0., 0., 0., 1.],
[0., 0., 0., 1.],
[0., 0., 0., 1.],
[0., 0., 1., 0.],
[0., 0., 1., 0.],
[0., 0., 1., 0.],
[0., 0., 1., 0.],
[0., 0., 1., 0.],
[0., 1., 0., 0.],
[0., 1., 0., 0.],
[0., 1., 0., 0.],
[0., 1., 0., 0.],
[0., 1., 0., 0.]])
how do I fix this problem?
解决方案
The error is raising from [3 3 3 3 3 2 2 2 2 2 1 1 1 1 1]
. You have 3 in your mapping np.array
which means in some position you are trying to equal index 3 to 1
but the problem is that maximum index in your mapping array is 2.
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
Just simply change your mapping array from [3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
to [2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0]
推荐阅读
- azure-devops - 无法将任务或用户故事分配给 Azure DevOps 中的项目成员
- java - 如何使用 Spring Boot 设置 JSESSION cookie 的过期日期时间
- c# - 如何为 DataGrid WPF 创建复杂的过滤器
- android - 模拟器派9失败
- mysql - 如何获取具有两个值的用户 ID
- google-cloud-platform - pub/sub 消息 ID 可以作为数字保存吗?
- javascript - 未在 JavaScript 和 Rails 中定义未捕获的 ReferenceError 函数
- post - 如何使用 traefik 记录 request_body?
- android - 在您的应用程序中打开以太网 android 片段
- r - r - 使用 Dplyr 计算子组内的百分比