one-hot encoding (独热编码)
在 loss 的计算时,Pytorch 有些 loss 函数需要 网络的 ouput 与 label 的 shape 相同,因此需要对 label 进行 one-hot encoding
分割中的独热编码示例
python 代码实现
Python 实现的思路
网络的输出的 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)