pytorch的各種loss

總計學習一下pytorch的各種loss函數:

轉載自:https://zhuanlan.zhihu.com/p/61379965

目錄

1.L1 loss

2.MSE Loss

3.CrossEntropy Loss

4.NLL Loss

5.Poisson Loss

6.KLDiv Loss

7.BCELoss

8.BCEwithLogitsLoss

9.MarginRanking Loss

10.HingeEmbeddingLoss

11.MultiLableMargin Loss

12.SmoothL1 Loss

13.SoftMargin Loss

14.MultiLabelSoftMargin Loss

15.CosineEmbedding Loss

16.MultiMargin Loss

17.TripletMarginLoss

18.CTCLoss


1.L1 loss

class torch.nn.L1Loss(size_average=None,reduce=None)

功能:計算output和target只差的絕對值,可選擇返回同維度的tensor或者是一個標量。

計算公式:

preview

 參數:

reduce(bool)-返回值是否爲標量,默認 爲True

size_average(bool)-當reduce=True時有效。爲True時,返回的loss爲平均值;爲False,返回的各樣本的loss之和。

2.MSE Loss(L2 loss)

class torch.nn.MSELoss(size_average=None,reduce=None,reduction='elementwise_mean')

功能:計算output和target只差的平方,可選返回同維度tensor或者是一個標量。

計算公式:

preview

 參數:

reduce(bool)-返回值是否爲標量,默認 爲True

size_average(bool)-當reduce=True時有效。爲True時,返回的loss爲平均值;爲False,返回的各樣本的loss之和。

使用經驗:在做模型蒸餾的時候,常用MSE loss(L2 loss);

3.CrossEntropy Loss

class torch.nn.CrossEbtropyLoss(weight=None,size_average=None,ignore_index=-100,reduce=None,reduction='elementwise_mean')

功能:將輸入經過softmax激活函數之後,再計算其與target的交叉熵損失 。即該方法將nn.LogSoftmax()和nn.NLLLoss進行了結合,嚴格意義上的交叉熵損失函數是nn.NLLLoss()。

補充:小談交叉熵損失函數 交叉熵損失(cross-entropy Loss)又稱之爲對數似然損失(Log-likelihood Loss)、對數損失;二分類時還可稱爲邏輯斯諦迴歸損失(Logistic Loss)。交叉熵損失函數表達式L=-sigama(y_i*log(x_i))。pytorch這裏不是嚴格意義的交叉熵損失函數,而是先將input經過softmax激活函數,將向量“歸一化”成概率形式,然後再與target計算嚴格意義上交叉熵損失。再多分類任務中,經常採用softmax激活函數+交叉熵損失函數,因爲交叉熵描述了兩個概率分佈的差異,然而神經網絡輸出的是向量,並不是概率分佈的形式。所以需要softmax激活函數將一個向量進行“歸一化”成概率分佈的形式,再採用交叉熵損失函數計算loss。再回顧pytorch的CrossEntropyLoss(),官方文檔中提到的nn.LogSoftmax()和nn.NLLLoss()進行結合,nn.LogSoftmax()相當於激活函數,nn.NLLLoss()是損失函數,將其結合,完整的是否可以叫做softmax+交叉熵損失函數呢?

計算公式:

preview

參數:

weight(Tensor)-爲每個類別的loss設置權限,常用於類別不均衡問題。weight必須是float類型的tensor,其長度要於類別C一致,即每一個類別都要設置weight。帶weight的計算公式:(?原文沒有公式)

 size_average(bool)-當reduce=True時有效。爲True時,返回的loss爲平均值;爲False,返回的各樣本的loss之和。

reduce(bool)-返回值是否爲標量,默認爲True;

ignore_index(int)-忽略某一類別,不計算其loss,其loss會爲0,並且,在採用size_average時,不會計算那一類的loss,除的時候的分母也不會統計哪一類的樣本。

補充:output不僅可以是向量,還可以是圖片,即對圖像進行像素點分類,這個例子可以從NLLLoss()中看到,還在圖像分割當中很有用;

4.NLL Loss

class torch.nn.NLLLoss(weight=None,size_average=None,ignore_index=-100,reduce=None,reduction='elementwise_mean')

功能:不好語言描述其功能!請看計算公式:loss(input,class)=-input[class].舉個例,三分類任務,input=【-1.233,2.657,0.534】,真實標籤爲2(class=2),則loss爲-0.534.就是對應類別上的輸出,取一個負號!感覺被NLLLoss的名字欺騙。實際應用:常用於多分類任務,但是input在輸入NLLLoss()之前,需要對input進行log_softmax函數激活,即將input轉換成概率分佈的形式,並且取對數。其實這些步驟在CrossEntropyLoss中就用,如果不想讓網絡的最後一層是log_softmaxc層的話,就可以採用CrossEntropyLoss完全代替此函數。

參數:

weight(Tensor)-爲每個類別的loss設置權限,常用於類別不均衡問題。weight必須是float類型的tensor,其長度要與類別C一致,即每一個類別都要設置weight。

 size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲除以權重之和的平均值;爲False時,返回的各樣本的loss之和。

reduce(bool)- 返回值是否爲標量,默認爲True。

ignore_index(int)- 忽略某一類別,不計算其loss,其loss會爲0,並且,在採用size_average時,不會計算那一類的loss,除的時候的分母也不會統計那一類的樣本。

特別注意:當帶上權重,reduce=True,size_average=True,其計算公式爲:

preview

例:input = [[0.6,0.2,0.2],[0.4,1.2,0.4]] ,target = [0,1],weight = [0.6,0.2,0.2]

l1 = -0.6*0.6=-0.36  l2 = -1.2*0.2 = -0.24 loss = -0.36/(0.6+0.2) + (-0.24)/(0.6+0.2) = -0.75

5.Poisson Loss

class torch.nn.PoissonNLLLoss(log_input = True,full=False,size_average=None,eps=1e-08,reduce=None,reduction='elementwise_mean')

功能:用於target服從泊松分佈的分類任務。

計算公式:

 previewpreview

參數:log_input(bool)-爲True時,計算公式爲:loss(input,target) =exp(input)-target*input;爲False時,loss(input, target)=input - target*log(input+eps)

full(bool)-是否計算全部的loss。

例如,當採用斯特林公式近似階乘項時,此爲target*log(target)-target+0.5*log(2πtarget)eps(float)-當log_input=False時,用來防止計算log(0)。而增加的一個修正項。即loss(input,target)=input-target*log(input+eps)

size_average(bool)-當reduce=True時有效。爲True時,返回loss爲平均值;爲False時,返回各樣本的loss之和。

reduce(bool)-返回值是否爲標量,默認爲True

6.KLDiv Loss

class torch.nn.KLDivLoss(size_average=None,reduce=None,reduction='elementwise_mean')

功能:計算input和target之間的KL散度(Kullback-Leibler divergence) 

計算公式:

補充:KL散度(kullback-Leibler divergence)又稱爲相對熵(Relative Entropy),用於描述兩個概率分佈之間的差異。計算公式(離散時) :

其中p代表真實分佈,q代表p的擬合分佈,D(P||Q)表示當用概率分佈q來擬合真實分佈時,產生的信息損耗。這裏的信息損耗,可以理解爲損失,損失越低,擬合分佈q越接近真實分佈p。同時也可以從另外一個角度上觀察這個公式,即計算的是p與q之間的對數差在p上的期望值。特別注意,D(p||q)!=D(q||p),其不具有對稱性,因此不能稱爲K_L距離。

信息熵=交叉熵-相對熵 從信息論角度觀察三者,其關係爲信息熵=交叉熵-相對熵。在機器學習中,當訓練數據固定,最小化相對熵D(p||q)等價於最小化交叉熵H(p,q)。

參數:

size_average(bool)-當reduce=True時有效。爲True時,返回是各樣本各loss之和。reduce(bool)-返回值是否爲標量,默認爲True。

使用注意事項:要想獲得KL散度,需要如下操作:

1.reduce=True;size_average=False

2.計算得到的loss要對batch求平均

7.BCELoss

class torch.nn.BCELoss(weight=None,size_average=None,reduce=None,reduction='elementwise_mean')

功能:二分類任務時的交叉熵計算函數。此函數可以認爲是nn.CrossEntropyLoss函數的特例。

其分類限定爲二分類,y必須是{0,1}。還需要注意的是,input應該爲概率分佈的形式,這樣才符合交叉熵的應用。所以在BCELoss之前,input一般爲sigmoid激活層的輸出,官方例子也要這樣給的。該損失函數在自編碼器中常用。計算公式:

 previewpreview

參數:

weight(Tensor)-爲每個類別deloss設置權值,常用於類別不均衡問題。

 size_average(bool)-當reduce=True時有效。爲True時,返回是各樣本各loss之和。

reduce(bool)-返回值是否爲標量,默認爲True

8.BCEwithLogitsLoss

class troch.nn.BCEWithLogitsLoss(weight=None,size_average=None,reduce=None,reduction='elementwise_mean',pos_weight=None)

功能:將Sigmoid與BCELoss結合,類似於CrossEntropyLoss(將nn.LogSoftmax()和nn.NLLLoss()進行結合)。即input會經過Sigmoid激活函數,將input變爲概率分佈的形式。計算公式:

preview

\delta()表示Sigmoid函數,特別地,當設置weight時:

參數:

weight(Tensor)-:爲batch中單個樣本設置權值,If given,has to be a Tensor of size “nbatch”.

pos_weight -:正樣本的權重,當p>1,當p<1,提高精確度。可達到權衡召回率(Recall)和精確度(precision)的作用。Must be a vector

with equal to the number of class。

size_average(bool)-當reduce=True時有效。爲True時,返回是各樣本各loss之和。

reduce(bool)-返回值是否爲標量,默認爲True

9.MarginRanking Loss

class torch.nn.MarginRankingLoss(margin=0,size_average=None, reduce=None, reduction='elementwise_mean')

功能: 計算兩個向量之間的相似度,當兩個向量之間的距離大於margin,則loss爲正,小於margin,loss爲0。

計算公式:

preview

y==1時,x1要比x2大,纔不會有loss,反之,y==-1時,x1要比x2小,纔不會有loss。

參數:

margin(float)- x1和x2之間的差異。

size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲平均值;爲False時,返回的各樣本的loss之和。

reduce(bool)- 返回值是否爲標量,默認爲True。

10.HingeEmbeddingLoss

class torch.nn.HingeEmbeddingLoss(margin=1.0, size_average=None, reduce=None, reduction='elementwise_mean')

功能: 未知。爲摺頁損失的拓展,主要用於衡量兩個輸入是否相似。 used for learning nonlinear embeddings or semi-supervised 。

計算公式:

參數:

margin(float)- 默認值爲1,容忍的差距。

size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲平均值;爲False時,返回的各樣本的loss之和。

reduce(bool)- 返回值是否爲標量,默認爲True。

11.MultiLableMargin Loss

class torch.nn.MultiLabelMarginLoss(size_average=None, reduce=None, reduction='elementwise_mean')

功能: 用於一個樣本屬於多個類別時的分類任務。例如一個四分類任務,樣本x屬於第0類,第1類,不屬於第2類,第3類。

計算公式: 

where i==0 to x.size(0),j==0 to y.size(0),y[j]>=0,and i!=y[j] for all i ang j;

x[y[j]] 表示 樣本x所屬類的輸出值,x[i]表示不等於該類的輸出值。

參數:

size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲平均值;爲False時,返回的各樣本的loss之和。

reduce(bool)- 返回值是否爲標量,默認爲True。 Input: (C) or (N,C) where N is the batch size and C is the number of classes. Target: (C) or (N,C), same shape as the input.

12.SmoothL1 Loss

class torch.nn.SmoothL1Loss(size_average=None, reduce=None, reduction='elementwise_mean')

功能: 計算平滑L1損失,屬於 Huber Loss中的一種(因爲參數δ固定爲1了)。

補充: Huber Loss常用於迴歸問題,其最大的特點是對離羣點(outliers)、噪聲不敏感,具有較強的魯棒性。 公式爲:

preview

 理解爲,當誤差絕對值小於δ,採用L2損失;若大於δ,採用L1損失。 回到SmoothL1Loss,這是δ=1時的Huber Loss。 計算公式爲:

 

where Zi is given by:

 對應下圖紅色線:

preview

 參數: size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲平均值;爲False時,返回的各樣本的loss之和。 reduce(bool)- 返回值是否爲標量,默認爲True。

13.SoftMargin Loss

class torch.nn.SoftMarginLoss(size_average=None, reduce=None, reduction='elementwise_mean')

功能: Creates a criterion that optimizes a two-class classification logistic loss between input tensor xand target tensor y (containing 1 or -1).

計算公式:

 

參數: size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲平均值;爲False時,返回的各樣本的loss之和。 reduce(bool)- 返回值是否爲標量,默認爲True。 

14.MultiLabelSoftMargin Loss

class torch.nn.MultiLabelSoftMarginLoss(weight=None, size_average=None, reduce=None, reduction='elementwise_mean')

功能: SoftMarginLoss多標籤版本,a multi-label one-versus-all loss based on max-entropy,

計算公式:

preview

參數: weight(Tensor)- 爲每個類別的loss設置權值。weight必須是float類型的tensor,其長度要於類別C一致,即每一個類別都要設置有weight。

15.CosineEmbedding Loss

class torch.nn.CosineEmbeddingLoss(margin=0, size_average=None, reduce=None, reduction='elementwise_mean')

功能: 用Cosine函數來衡量兩個輸入是否相似。 used for learning nonlinear embeddings or semi-supervised 。

計算公式:

preview

margin(float)- : 取值範圍[-1,1], 推薦設置範圍 [0, 0.5]

size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲平均值;爲False時,返回的各樣本的loss之和。

reduce(bool)- 返回值是否爲標量,默認爲True。

16.MultiMargin Loss

class torch.nn.MultiMarginLoss(p=1, margin=1, weight=None, size_average=None, reduce=None, reduction='elementwise_mean')

功能: 計算多分類的摺頁損失。

計算公式:

preview

 

其中,0≤y≤x.size(1) ; i == 0 to x.size(0) and i≠y; p==1 or p ==2; w[y]爲各類別的weight。

參數:

p(int)- 默認值爲1,僅可選1或者2。

margin(float)- 默認值爲1

weight(Tensor)- 爲每個類別的loss設置權值。weight必須是float類型的tensor,其長度要於類別C一致,即每一個類別都要設置有weight。

size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲平均值;爲False時,返回的各樣本的loss之和。

reduce(bool)- 返回值是否爲標量,默認爲True。

17.TripletMarginLoss

class torch.nn.TripletMarginLoss(margin=1.0, p=2, eps=1e-06, swap=False, size_average=None, reduce=None, reduction='elementwise_mean')

功能: 計算三元組損失,人臉驗證中常用。 如下圖Anchor、Negative、Positive,目標是讓Positive元和Anchor元之間的距離儘可能的小,Positive元和Negative元之間的距離儘可能的大。 

preview

從公式上看,Anchor元和Positive元之間的距離加上一個threshold之後,要小於Anchor元與Negative元之間的距離。

 

preview

計算公式: 

preview

參數:

margin(float)- 默認值爲1

p(int)- The norm degree ,默認值爲2

swap(float)– The distance swap is described in detail in the paper Learning shallow convolutional feature descriptors with triplet losses by V. Balntas, E. Riba et al. Default: False

size_average(bool)- 當reduce=True時有效。爲True時,返回的loss爲平均值;爲False時,返回的各樣本的loss之和。 reduce(bool)- 返回值是否爲標量,默認爲True。

preview

18.CTCLoss

nn.CTCLoss(blank=0, reduction='mean', zero_infinity=False)

 功能: Connectionist Temporal Classification。主要是解決時序類數據的分類問題,特別是label 和output 不對齊的問題(Alignment problem)

參考文獻:Connectionist Temporal Classification: Labelling Unsegmented Sequence Data with Recurrent Neural Network

CTC算法全稱叫:Connectionist temporal classification。從字面上理解它是用來解決時序類數據的分類問題。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章