如何在 python 中构建 OneHot 解码器

How to build OneHot Decoder in python

我有 encoded 我的 图像(面具),尺寸为 (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. Threshold the output to obtain 0 or 1 only.
  2. Multiply each channel with weight equal to the channel index.
  3. take the max between labels along channels axis.
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. How to git rid of the error: line 15, in oneHotDecoder img[img<0.5]=0 TypeError: '<' not supported between instances of 'list' and 'float'
  2. Is there any other issues in my implementaion that you suggest to improve?

提前致谢。

您的一些项目有逗号和点的拼写错误(例如,您的第一个列表应该是 [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]]])