单速编码没有numpy的python位置向量的循环



我有一些我想"单速编码"的数据,并且将其表示为位置的一维向量。

numpy中是否有任何功能可以将我的x扩展到我的x_ohe

看着杰克·范德帕拉斯(Jake Vanderplas)的Talk

,我试图避免在Python中使用python的横环
x = np.asarray([0,0,1,0,2])
x_ohe = np.zeros((len(x), 3), dtype=int)
for i, pos in enumerate(x):
    x_ohe[i,pos] = 1
x_ohe
# array([[1, 0, 0],
#        [1, 0, 0],
#        [0, 1, 0],
#        [1, 0, 0],
#        [0, 0, 1]])

如果 x仅包含非负整数,则可以将 x与序列使用 numpy broadcasting 进行比较,然后将结果转换为 int int s:

(x[:,None] == np.arange(x.max()+1)).astype(int)
#array([[1, 0, 0],
#       [1, 0, 0],
#       [0, 1, 0],
#       [1, 0, 0],
#       [0, 0, 1]])

或先初始化,然后分配使用高级索引

x_ohe = np.zeros((len(x), 3), dtype=int)
x_ohe[np.arange(len(x)), x] = 1
x_ohe
#array([[1, 0, 0],
#       [1, 0, 0],
#       [0, 1, 0],
#       [1, 0, 0],
#       [0, 0, 1]])

一个衬里:

np.equal.outer(x,range(3)).astype(int)
array([[1, 0, 0],
       [1, 0, 0],
       [0, 1, 0],
       [1, 0, 0],
       [0, 0, 1]])

np.equal.outer(x,np.unique(x)).astype(int)在这里也有效。

最新更新