使用 NumPy 从 Python 中的位置向量进行没有 for 循环的单热编码?
One-Hot Encoding without for-loop from vector of positions in Python with NumPy?
我有一些想要 "one-hot encode" 的数据,它表示为位置的一维向量。
NumPy 中是否有任何函数可以将我的 x
扩展为我的 x_ohe
?
之后,我试图不惜一切代价避免在 Python 中使用 for 循环进行此类操作
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小号:
(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]])
或者先初始化,再赋值使用advanced indexing:
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)
也适用于此。
我有一些想要 "one-hot encode" 的数据,它表示为位置的一维向量。
NumPy 中是否有任何函数可以将我的 x
扩展为我的 x_ohe
?
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小号:
(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]])
或者先初始化,再赋值使用advanced indexing:
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)
也适用于此。