2024-04-26 17:40:57 发布
网友
我有一个巨大的numpy 2d数组,每个值都是介于0和3之间的类别:
[[3 1 0 ... 1] ... [2 0 1 ... 3]]
我想对它进行一次热编码(0是0 0 0 1,1是0 0 1 0,等等),因此上面的代码将变成:
0 0 0 1
0 0 1 0
[[1 0 0 0 0 0 1 0 0 0 0 1 ... 0 0 1 0] ... [0 1 0 0 0 0 0 1 0 0 1 0 ... 1 0 0 0]]
最有效的方法是什么?谢谢
假设有一个(M, N)矩阵,最大值为P(= 4):
(M, N)
P
= 4
M = 6 N = 5 P = 4 mat = np.random.randint(P, size=(M, N))
首先将其编码为0和1的(M, N, P)矩阵,使用mat作为最后一个维度的索引:
(M, N, P)
mat
encoded = np.zeros((M, N, P), dtype=int) encoded[(*np.ogrid[:M, :N], (P - 1) - mat)]
或者,使用np.put_along_axis:
np.put_along_axis
np.put_along_axis(encoded, (P - 1) - np.expand_dims(mat, -1), 1, axis=-1)
数据在内存中的顺序与您想要的相同,因为numpy默认使用C顺序。您只需reshape即可获得最终结果:
reshape
encoded.reshape(M, N * P)
假设有一个
(M, N)
矩阵,最大值为P
(= 4
):首先将其编码为0和1的
(M, N, P)
矩阵,使用mat
作为最后一个维度的索引:或者,使用
np.put_along_axis
:数据在内存中的顺序与您想要的相同,因为numpy默认使用C顺序。您只需
reshape
即可获得最终结果:相关问题 更多 >
编程相关推荐