【问题标题】:How to build OneHot Decoder in python如何在 python 中构建一个热编码器
【发布时间】:2020-09-18 17:11:37
【问题描述】:

我有 encoded 我的 images(masks) 尺寸 (img_width x img_height x 1)OneHotEncoder 这样:

import numpy as np

def OneHotEncoding(im,n_classes):
  one_hot = np.zeros((im.shape[0], im.shape[1], n_classes),dtype=np.uint8)
  for i, unique_value in enumerate(np.unique(im)):
    one_hot[:, :, i][im == unique_value] = 1
  return one_hot

在使用深度学习进行一些数据操作后,softmax 激活函数将产生概率而不是 01 值,因此在我的解码器中我想实现以下方法:

  1. 仅获取01 的输出阈值。
  2. 将每个通道乘以等于通道索引的权重。
  3. 沿通道轴取标签之间的最大值。
import numpy as np

arr = np.array([
    [[0.1,0.2,0,5],[0.2,0.4,0.7],[0.3,0.5,0.8]],
    [[0.3,0.6,0  ],[0.4,0.9,0.1],[0  ,0  ,0.2]],
    [[0.7,0.1,0.1],[0,6,0.1,0.1],[0.6,0.6,0.3]],
    [[0.6,0.2,0.3],[0.4,0.5,0.3],[0.1,0.2,0.7]]
])

# print(arr.dtype,arr.shape)

def oneHotDecoder(img):
    # Thresholding
    img[img<0.5]=0
    img[img>=0.5]=1
    # weigts of the labels
    img = [i*img[:,:,i] for i in range(img.shape[2])]
    # take the max label
    img = np.amax(img,axis=2)
    print(img.shape)
    return img

arr2 = oneHotDecoder(arr)
print(arr2)

我的问题是:

  1. 如何摆脱错误: line 15, in oneHotDecoder img[img<0.5]=0 TypeError: '<' not supported between instances of 'list' and 'float'
  2. 您是否建议改进我的实施中的任何其他问题?

提前致谢。

【问题讨论】:

    标签: python numpy decoding one-hot-encoding


    【解决方案1】:

    您的某些项目中有逗号和点的拼写错误(例如,您的第一个列表应该是 [0.1, 0.2, 0.5] 而不是 [0.1, 0.2, 0, 5])。

    固定列表是:

    l = [
          [[0.1,0.2,0.5],[0.2,0.4,0.7],[0.3,0.5,0.8]],
          [[0.3,0.6,0  ],[0.4,0.9,0.1],[0  ,0  ,0.2]],
          [[0.7,0.1,0.1],[0.6,0.1,0.1],[0.6,0.6,0.3]],
          [[0.6,0.2,0.3],[0.4,0.5,0.3],[0.1,0.2,0.7]]
    ]
    

    那么你可以这样做:

    np.array(l)  # np.dstack(l) would work as well
    

    这会产生:

    array([[[0.1, 0.2, 0.5],
            [0.2, 0.4, 0.7],
            [0.3, 0.5, 0.8]],
           [[0.3, 0.6, 0. ],
            [0.4, 0.9, 0.1],
            [0. , 0. , 0.2]],
           [[0.7, 0.1, 0.1],
            [0.6, 0.1, 0.1],
            [0.6, 0.6, 0.3]],
           [[0.6, 0.2, 0.3],
            [0.4, 0.5, 0.3],
            [0.1, 0.2, 0.7]]])
    

    【讨论】:

      猜你喜欢
      • 2020-01-30
      • 2022-09-27
      • 2021-09-11
      • 2017-11-05
      • 1970-01-01
      • 2018-12-17
      • 2018-03-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多