我有一些数据,需要进行“one-hot编码”,这些数据以一维位置向量的形式表示。
NumPy中有没有可以将我的x
扩展为x_ohe
的函数?
在观看了Jake Vanderplas的演讲后,我尽量避免在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] = 1x_ohe# array([[1, 0, 0],# [1, 0, 0],# [0, 1, 0],# [1, 0, 0],# [0, 0, 1]])
回答:
如果x
只包含非负整数,你可以使用numpy广播将x
与一个序列进行比较,并将结果转换为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]])
或者先初始化,然后使用高级索引来分配1:
x_ohe = np.zeros((len(x), 3), dtype=int)x_ohe[np.arange(len(x)), x] = 1x_ohe#array([[1, 0, 0],# [1, 0, 0],# [0, 1, 0],# [1, 0, 0],# [0, 0, 1]])