【问题标题】:Convert a 2D numpy array into a hot-encoded 3D numpy array, with same values in the same plane将 2D numpy 数组转换为热编码的 3D numpy 数组,在同一平面上具有相同的值
【发布时间】:2021-07-18 19:31:45
【问题描述】:

假设我有一个 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]),这样应该会更容易。

顺便说一句,我需要这个,因为我有一个由数字表示的棋盘,但需要它以这种形式传递到二维卷积神经网络(不同的“通道”用于不同的棋子)。

我见过Convert a 2d matrix to a 3d one hot matrix numpy,但它对每个值都有一个单热编码,这不是我想要的。

【问题讨论】:

    标签: python numpy


    【解决方案1】:

    创建所需的数组(此处为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]]])
    

    【讨论】:

      猜你喜欢
      • 2021-12-29
      • 2019-10-31
      • 2011-05-19
      • 1970-01-01
      • 2017-07-26
      • 2017-07-27
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      相关资源
      最近更新 更多