Py学习  »  Python

Numpy-如何在不使用python循环的情况下转换此数组?

yeah_man_i_get_it • 3 年前 • 1274 次点击  

我的输入是一个y_真标签列表,其中元素位于 i 包含范围为的值 0..len(classes) 并描述了数据集元素的真正类别。 范围从 0 len(data) .举例如下:

# 5 elements in data, 3 classes, all of which had representation in the data:
y_true = [0,2,1,0,1]

我希望我的输出是一个列表 len(数据) 通过 len(classes) ,内部列表在哪里 会有一个 1 以y_true[i]的身份,以及 0 另一方面 len(classes)-1 插槽,例如:

#same configuration as the previous example
y_true = [0,2,1,0,1]  
result = [[1,0,0],[0,0,2],[0,1,0],[1,0,0],[0,1,0]]

以下是我的创意 result :

result = np.zeros((len(y_true), max(y_true)+1))

然而,我在这个问题上没有取得任何进一步的进展。我试着用 add.at(result, y_true, 1) 这个y_true的形状翻转了,但都没有产生我想要的结果。什么样的功能可以实现我在这里的目标?

编辑:为了更好地阐明我想要实现的目标,我使用了For循环:

result = np.zeros((len(y_true), max(y_true)+1))
for x in range(4):
  result[x][y_true[x]] = 1
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/132090
 
1274 次点击  
文章 [ 1 ]  |  最新文章 3 年前
mozway
Reply   •   1 楼
mozway    3 年前

您可以使用花式索引:

result = np.zeros((len(y_true), max(y_true)+1), dtype=int)
result[np.arange(len(y_true)), y_true] = 1

输出:

array([[1, 0, 0],
       [0, 0, 1],
       [0, 1, 0],
       [1, 0, 0],
       [0, 1, 0]])

可供替代的

另一个有趣的选择可能是使用 pandas.get_dummies :

import pandas as pd
result = pd.get_dummies(y_true).to_numpy()

输出:

array([[1, 0, 0],
       [0, 0, 1],
       [0, 1, 0],
       [1, 0, 0],
       [0, 1, 0]], dtype=uint8)