gpt4 book ai didi

python - 将 2D numpy 数组转换为热编码的 3D numpy 数组,在同一平面上具有相同的值

转载 作者:行者123 更新时间:2023-12-04 03:34:16 26 4
gpt4 key购买 nike

假设我有一个 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 ,但它对每个值都有一个单热编码,这不是我要找的。

最佳答案

创建所需的数组(此处为 arr.max()+1),然后 reshape 它以与原始数组进行比较:

设置:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com