![](/img/trans.png)
[英]Numpy array : how to convert values of a 2D array into a 3D one-hot array
[英]Convert a 2D numpy array into a hot-encoded 3D numpy array, with same values in the same plane
假设我有一个 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]
),这样应该会更容易。
顺便说一句,我需要这个,因为我有一个由数字表示的棋盘,但需要以这种形式将它传递到 2d 卷积神经网络(不同的“通道”用于不同的棋子)。
我已经看到将 2d 矩阵转换为 3d 一个热矩阵 numpy ,但这对每个值都有一个单热编码,这不是我想要的。
创建所需的数组(此处为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]]])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.