如何对二维矩阵进行编码?

2024-04-26 17:40:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个巨大的numpy 2d数组,每个值都是介于0和3之间的类别:

[[3 1 0 ... 1]
...
 [2 0 1 ... 3]]

我想对它进行一次热编码(0是0 0 0 1,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]]

最有效的方法是什么?谢谢


Tags: 方法代码numpy编码数组类别
1条回答
网友
1楼 · 发布于 2024-04-26 17:40:57

假设有一个(M, N)矩阵,最大值为P= 4):

M = 6
N = 5
P = 4
mat = np.random.randint(P, size=(M, N))

首先将其编码为0和1的(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(encoded, (P - 1) - np.expand_dims(mat, -1), 1, axis=-1)

数据在内存中的顺序与您想要的相同,因为numpy默认使用C顺序。您只需reshape即可获得最终结果:

encoded.reshape(M, N * P)

相关问题 更多 >