当前位置:   article > 正文

深度学习语义分割标签图像独热编码 (one hot encoding)_语义分割one-hot 编码

语义分割one-hot 编码

one-hot encoding (独热编码)

在 loss 的计算时,Pytorch 有些 loss 函数需要 网络的 ouput 与 label 的 shape 相同,因此需要对 label 进行 one-hot encoding

分割中的独热编码示例

在这里插入图片描述在这里插入图片描述

python 代码实现

Python 实现的思路

参考 https://discuss.pytorch.org/t/efficient-way-to-one-hot-encode-whole-image-for-semantic-segmentation/75220

网络的输出的 shape 为 ( batch_size, num_classes, h, w );
标签的 shape 为 ( batch_size, 1, h, w );
需要将 shape 表示成 独热编码 的形式:
成 num_classes 个 大小为 ( batch_size, h, w)的全为 1 的 tmplate 张量,将 tmplate中属于该类别的改为 1,其余为 0, 并 reshape 成 (batch_size, 1, h, w), 最后在 第二维对所有的 tmplate张量 concatenate

在这里插入图片描述

网络的输出是一个 (batch_size, num_classes, h, w)shape 的张量
label 是一个 (batch_size, 1, h, w)shape 的张量

>># 网络的输出是一个 (batch_size, num_classes, h, w) shape 的张量
>># label 是一个 (batch_size, 1, h, w) shape 的张量
>>def mask2one_hot(label, out):
   """
   label: 标签图像 # (batch_size, 1, h, w)
   out: 网络的输出
   """
   num_classes = out.shape[1] # 分类类别数

   current_label = label.squeeze(1)  #(batch_size, 1, h, w) ---> (batch_size, h, w)

   batch_size, h,w = current_label.shape[0],current_label.shape[1],current_label.shape[2] 


   print(h,w,batch_size)

   one_hots = []
   for i in range(num_classes):
       tmplate = torch.ones(batch_size, h, w) # (batch_size, h, w)
       tmplate[current_label != i] = 0
       tmplate = tmplate.view(batch_size,1,h,w) # (batch_size, h, w) --> (batch_size, 1, h, w)

       one_hots.append(tmplate)

   onehot = torch.cat(one_hots, dim=1) 

   return onehot


import torch
torch.random.manual_seed(100)

>out = torch.rand(4,3,384,544)	# 网络的输出
>label = torch.randint(0,3,(4,1,384,544))	# 图像标签

>oh = mask2one_hot(label,out)
>oh	# shape ---> (4,3,384,544)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/922694?site
推荐阅读
相关标签
  

闽ICP备14008679号