語義分割損失函數


1. 交叉熵損失

語義分割時相當於對每個像素進行分類,所以實際是一個分類任務

對每一個像素的預測值與實際值比較,將損失求平均,是所以最常用的還是交叉熵損失

self.CE = nn.CrossEntropyLoss(weight=weight, ignore_index=ignore_index, reduction=reduction)
loss = self.CE(outputs, target)
 
2. 帶權重的交叉熵損失
 交叉熵Loss 可以用在大多數語義分割場景中,但它有一個明顯的缺點,那就是對於只分割前景和背景
的時候,當前景像素的數量遠遠小於背景像素的數量時,即出現樣本不平衡的的時候,損失函數中y=背景
的成分就會占據主導,使的模型嚴重偏向背景,導致效果不好。
為解決樣本不平衡問題,
在多樣本損失加一個小的權重,在少樣本損失加一個大的權重

self.CE_loss = nn.CrossEntropyLoss(reduce=False, ignore_index=ignore_index, weight=alpha)
 
3. FoaclLoss
Focal Loss 用於解決難以樣本數量不平衡問題,即更關注難分對樣本的損失。一個簡單的想法就是將高置信度的
樣本的損失降低,低置信度的樣本損失提高

 當p = 0.9 的時候,取 gamma=2, 損失降低了1000倍。

self.CE_loss = nn.CrossEntropyLoss(reduce=False, ignore_index=ignore_index)
logpt = self.CE_loss(output, target)
pt = torch.exp(-logpt)
loss = (1-pt)**self.gamma * logpt
loss.mean()
 
4. Dice Loss
用來度量集合相似度的度量函數,通常用於計算兩個樣本之間的像素。
   

class DiceLoss(nn.Module):
  def __init__(self, smooth=1, ignore_index=255):
    super(DiceLoss, self).__init__()
    self.ignore_index = ignore_index
    self.smooth = smooth

  def forward(self, output, target):
    if self.ignore_index not in range(target.min(), target.max()):
      if (target == self.ignore_index).sum() > 0:
        target[target==self.ignore_index] = target.min()
  # 轉化成one-hot形式 target
= make_one_hot(target.unsqueeze(dim=1), classes=output.size()[1])
# 轉化為概率 output
= F.softmax(output, dim=1) output_flat = output.contiguous().view(-1) target_flat = target.contiguous().view(-1)
# 重合部分 intersection
= (output_flat * target_flat).sum() loss = 1 - (2 * intersection + self.smooth) / (output_flat.sum() + target_flat.sum() + self.smooth)

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM