本節簡單總結torch.nn封裝的18種損失函數。【文中思維導圖采用MindMaster軟件,Latex公式采用在線編碼器】 |
目錄
1.nn.CrossEntropyLoss()交叉熵損失函數
這里大家可以進入“一文搞懂交叉熵在機器學習中的使用,透徹理解交叉熵背后的直覺”,這個博主講的非常好!
loss_f = nn.CrossEntropyLoss(weight=None, ignore_index=-100, reduction='mean')
inputs = torch.tensor([[1, 2], [1, 3], [1, 3]], dtype=torch.float)
target = torch.tensor([0, 1, 1], dtype=torch.long)
loss = loss_f(inputs, target)
# 參數:
# weight:設置各類別的loss的權重,(防止類別數目不平衡)e.g. weights = torch.tensor([1, 2], dtype=torch.float) 兩個類別
# ignore_index: 忽略某個類別
# reduction:計算模式 1.'None':逐元素計算,返回張量;2.'sum':所有元素求和,返回標量;3.'mean':加權平均,返回標量
nn.CrossEntropyLoss是nn.LogSoftmax與nn.NLLLoss的結合,公式為:
\[loss\left ( x,class \right )= -\log{\left ( \frac{\exp x\left [ class \right ] }{\sum_{j} \exp x\left [ j \right ] } \right ) }=weight\left [ class \right ] \left ( -x\left [ class \right ] +\log{\sum_{j} \exp x\left [ j \right ]} \right ) \]
上述公式的由來:交叉熵 = 信息熵 + 相對熵
- 信息熵:描述整個概率分布上事件的不確定性
\[H\left ( p \right ) =E_{x\sim p} \left [ I\left ( x \right ) \right ] =\sum_{i}^{N} p\left ( x_{i} \right )\left ( -\log{p\left ( x_{i} \right )} \right ) \]
- 相對熵(KL散度):描述兩個分布之間的距離
\[D_{KL}\left ( P,Q \right ) =E_{x\sim p} \left [ \log{\frac{P\left ( x \right ) }{Q\left ( x \right ) } } \right ]=\sum_{i}^{N} P\left ( x_{i} \right )\left [ \log{P\left ( x_{i} \right )}- \log{Q\left ( x_{i} \right )} \right ] \]
- 交叉熵
\[H\left ( P, Q \right ) =D_{KL}\left ( P,Q \right ) +H\left ( p \right ) =-\sum_{i}^{N} P\left ( x_{i} \right )\left [- \log{Q\left ( x_{i} \right )} \right ] \]
其中 \(P\) 為真實數據分布,\(H(P)\) 在優化時為常數,故而 \(H\left ( P,Q \right ) \longrightarrow D_{KL}\left ( P,Q \right )\)。實際代碼中, \(P\) 即為標簽,\(Q\) 為數據經過網絡得到的分布,即取\(softmax\)。
2.nn.BCELoss()二分類交叉熵損失函數
注意:輸入值必須在[0,1]之間,表示一個分布。
loss_f = nn.BCELoss(weight=None,reduction='mean')
inputs = torch.tensor([[1, 2], [2, 2], [3, 4], [4, 5]], dtype=torch.float)
target = torch.tensor([[1, 0], [1, 0], [0, 1], [0, 1]], dtype=torch.float)
loss = loss_f(inputs, target)
3.nn.BCEWithLogitsLoss()結合Sigmoid的二分類交叉熵損失函數
loss_f = nn.BCEWithLogitsLoss(weight=None, reduction='mean', pos_weight=None)
# 參數:
# pos_weight:正樣本(標簽為1)的權值
4.nn.L1Loss
計算inputs與label之間差值的絕對值
\[l_{i}=\left | x_{i}-y_{i } \right | \]
5.nn.MSELoss
計算inputs與label之間的平方差
\[l_{i}=\left ( x_{i}-y_{i } \right ) ^{2} \]
6.nn.SmoothL1Loss
平滑的L1Loss,由圖2紅色線與藍色線對比可以看出。通過下面的公式我們也可以知道,SmoothL1損失結合了L1和MSE兩者的優點。
\[\left\{\begin{matrix} loss=\frac{1}{n}\sum_{i}^{n} z_{i} \\z_{i}=\begin{cases} \frac{1}{2} \left ( x_{i}-y_{i } \right ) ^{2} & \text{ if } \left | x_{i}-y_{i }< 1\right | \\ \left | x_{i}-y_{i }\right |-0.5 & \text{others} \end{cases} \end{matrix}\right.\]