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

标签 python numpy

假设我有一个 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/

相关文章:

python - 运行一个进程,如果它在一小时内没有结束,则终止它

python - 如何使用python仅为特定列组合创建相关矩阵?

python - 具有较小数据集的异常值检测方法

python - 趋势线图不适用于大数据集

python - numpy 函数 cythonization

python - 当binary = False时,如何从树结构中提取诸如PER、ORG、GPE之类的命名实体?

python - 使用 `multiprocessing.Pool` 在多个 GPU 上平均分配作业

python - 如果我使用 lxml 而不是 BeautifulSoup,我会更好地控制我的蜘蛛吗?

java - java中的文字纠错程序

python - “numpy.float64”对象不可迭代 - 均值漂移聚类