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

本文介绍如何在PyTorch中实现一热编码(one-hot encoding),特别针对图像分割任务,通过具体Python代码示例展示了如何将标签转换为一热编码形式,以便于与网络输出进行比较。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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)
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值