pytorch中CrossEntropyLoss和NLLLoss的区别与联系
CrossEntropyLoss和NLLLoss主要是用在多分类问题的损失函数,他们两个既有不同,也有不浅的联系。先分别看一下:
CrossEntropyLoss
称为交叉熵损失函数,主要的计算公式为:
l o s s ( x , c l a s s ) = − l o g ( e c l a s s ∑ j ( e x [ j ] ) ) loss(x,class)=-log(\frac{e^{class}}{\sum_j(e^{x[j]})})loss(x,class)=−log(∑j(ex[j])eclass)
其中e c l a s s e^{class}eclass表示某个输出的指数,∑ j ( e x [ j ] ) \sum_j(e^{x[j]})∑j(ex[j])表示所有输出的指数的累加,指数的使用保证操作后的值大于0,除以累加和保证了所有值加起来和为1
具体的官方文档:

NLLLoss
这个损失函数的全称为负对数似然损失(The negative log likelihood loss),具体的公式如下:
l ( x , y ) = L = { l 1 , l 2 , . . . , l N } T , l n = − W y n X n , y n , W c = w e i g h t [ c ] ∗ 1 l(x,y)=L=\{l_1,l_2,...,l_N\}^T,l_n = -W_{y_n}X_{n,y_n},W_c = weight[c]*1l(x,y)=L={l1,l2,...,lN}T,ln=−WynXn,yn,Wc=weight[c]∗1
其中X为输入,W为权重,上述公式为reduction=none时的损失函数计算。W y n W_{y_n}Wyn就表示对应于y n y_nyn类的权重,X也是同样的道理,N为batch size的大小。
f ( n ) = { ∑ n = 1 N 1 ∑ n = 1 N W y n , if r e d u c t i o n = mean ∑ n = 1 N l n , if r e d u c t i o n = sum f(n)= \begin{cases} \sum_{n=1}^N\frac{1}{\sum_{n=1}^NW_{y_n}}, & \text {if $reduction$ = mean} \\ \sum_{n=1}^Nl_n, & \text{if $reduction$ = sum} \end{cases}f(n)={∑n=1N∑n=1NWyn1,∑n=1Nln,if reduction = meanif reduction = sum
官方的文档为:

区别
对于CrossEntropyLoss来说网络的最后一层线性层的输出可以直接作为该损失函数的输入。
对于NLLLoss来说网络的最后一层线性层的输入不能直接使用,需要额外加一层.LogSoftmax来对线性的输出做如下操作:
l o g ( 1 1 + e ( − X ) ) log(\frac{{1}}{1+e^{(-X)}})log(1+e(−X)1)
经过LogSoftmax后的输出作为NLLLoss的输入。
联系
从功能实现来说:
C r o s s E n t r o p y L o s s = L o g S o f t m a x 层 + N L L L o s s CrossEntropyLoss = LogSoftmax层 + NLLLossCrossEntropyLoss=LogSoftmax层+NLLLoss
在代码编写使用中的区别

