假设我有一个 Numpy 数组:
[
[0, 1, 0],
[0, 1, 4],
[2, 0, 0],
]
如何将其转换为“热编码”3D 数组?像这样的东西:
[
# Group of 0's
[[1, 0, 1],
[1, 0, 0],
[0, 1, 1]],
# Group of 1's
[[0, 1, 0],
[0, 1, 0],
[0, 0, 0]],
# Group of 2's
[[0, 0, 0],
[0, 0, 0],
[1, 0, 0]],
# Group of 3's
# the group is still here, even though there are no threes
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
# Group of 4's
[[0, 0, 0],
[0, 0, 1],
[0, 0, 0]]
]
也就是说,如何将数组中出现的每个数字并将它们“分组”到 3D 矩阵中自己的平面中?如示例所示,即使数字中的“间隙”(即 3
)仍应出现。就我而言,我事先知道数据的范围(范围 (0, 6]
),因此这应该会更容易。
顺便说一句,我需要这个,因为我有一个由数字表示的棋盘,但需要它以这种形式传递到二维卷积神经网络(不同棋子的不同“ channel ”)。
我见过Convert a 2d matrix to a 3d one hot matrix numpy ,但是每个值都有一个 one-hot 编码,这不是我想要的。
最佳答案
创建所需的数组(此处是arr.max()+1
),然后对其进行整形以与原始数组进行比较:
设置:
arr = np.array([
[0, 1, 0],
[0, 1, 4],
[2, 0, 0],
])
u = np.arange(arr.max()+1)
(u[:,np.newaxis,np.newaxis]==arr).astype(int)
array([[[1, 0, 1],
[1, 0, 0],
[0, 1, 1]],
[[0, 1, 0],
[0, 1, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[1, 0, 0]],
[[0, 0, 0],
[0, 0, 0],
[0, 0, 0]],
[[0, 0, 0],
[0, 0, 1],
[0, 0, 0]]])
关于python - 将 2D numpy 数组转换为热编码的 3D numpy 数组,在同一平面中具有相同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67249470/