1. 均方差損失函數(shù)(Mean Squared Error, MSE)
均方差損失函數(shù)是預測數(shù)據(jù)和樣本標簽對應點誤差的平方然后取均值,其公式如下所示:
其中為預測數(shù)據(jù),
為樣本標簽,
為樣本個數(shù)。
2. 均方差在pytorch中的用法
均方差損失函數(shù)在pytorch中的函數(shù)為:
torch.nn.MSELoss(size_average=None, reduce=None, reduction='mean')
pytorch中默認損失計算的是均值。
我看很多博客對該損失函數(shù)講解的不是很全面,它們只告訴你這個接口怎么用而不講解其中是怎么進行運算的,下面我用一個實例來講解一下函數(shù)內(nèi)部是如何運算的。
>>> input = torch.randn(3,5,requires_grad=True)
>>> input
tensor([[ 0.0107, 0.0574, 0.2145, -0.6022, -0.2549],
[-0.5236, -0.0693, 0.4386, 0.1597, 2.2749],
[-1.7281, -0.6220, 2.5002, -0.5681, -0.5767]], requires_grad=True)
>>> target = torch.randn(3,5)
>>> target
tensor([[ 0.3699, -0.7985, 1.2310, 0.3084, 2.2067],
[ 0.2520, -1.0720, 0.1930, -0.2715, 0.7808],
[-0.9800, -1.0310, -1.2699, -0.9418, -1.2091]])
>>> loss = nn.MSELoss()
>>> output = loss(input, target)
>>> output.backward()
>>> output
tensor(1.8899, grad_fn=<MseLossBackward>)
計算得到input和target的均方差為1.8899。下面我們不借助torch.nn.MESLoss()函數(shù),直接根據(jù)公式來計算下它們的均方差。
首先我們要計算input和target的差的平方:
>>> result = (input-output)**2
>>> result
tensor([[ 0.1290, 0.7326, 1.0333, 0.8291, 6.0594],
[ 0.6015, 1.0054, 0.0603, 0.1860, 2.2324],
[ 0.5596, 0.1673, 14.2134, 0.1397, 0.3998]], grad_fn=<PowBackward0>)
接著我們求result所有元素的和,然后再除以元素總個數(shù)15:
>>> result = result.view(15,).sum()/15
>>> result
tensor(1.8899, grad_fn=<DivBackward0>)
計算結(jié)果為1.8899,和nn.MSELoss()函數(shù)所得到的結(jié)果相同。
值得注意的是,若多分類任務中要使用均方差作為損失函數(shù),需要將標簽轉(zhuǎn)換成one-hot形式,這與交叉熵損失函數(shù)恰巧相反。關于交叉熵如何使用可以參考我的另一篇博客:[損失函數(shù)]——交叉熵。
因為在使用nn.CrossEntropyLoss()時是取出輸出層的輸出中每個樣本( 每一行)中最大的數(shù)與標簽進行運算,所以使用交叉熵損失函數(shù)時只需對應標簽即可,而均方差則不然,它是對每一個輸出都要參與運算,所以在使用均方差作為損失函數(shù)的時候要將標簽轉(zhuǎn)換成one-hot形式。
3. 均方差不宜和sigmoid函數(shù)一起使用
下面用公式來進行說明:
sigmoid的函數(shù)如下:
均方差損失函數(shù):
對權(quán)值求導:
最終變換成對sigmoid函數(shù)求導,sigmoid函數(shù)有一個特點,那就是橫坐標越遠離坐標原點,導數(shù)越接近于0,當越接近1時導數(shù)越小,最終會造成梯度小時。

pytorch官方文檔
交叉熵損失函數(shù)(Cross Entropy Error Function)與均方差損失函數(shù)(Mean Squared Error)