MSELoss損失函數中文名字就是:均方損失函數,公式如下所示:
這里 loss, x, y 的維度是一樣的,可以是向量或者矩陣,i 是下標。
很多的 loss 函數都有 size_average 和 reduce 兩個布爾類型的參數。因為一般損失函數都是直接計算 batch 的數據,因此返回的 loss 結果都是維度為 (batch_size, ) 的向量。
一般的使用格式如下所示:
loss_fn = torch.nn.MSELoss(reduce=True, size_average=True)
這里注意一下兩個入參:
A reduce = False,返回向量形式的 loss
B reduce = True, 返回標量形式的loss
C size_average = True,返回 loss.mean();
D 如果 size_average = False,返回 loss.sum()
默認情況下:兩個參數都為True.
下面的是python的例子:
1 # -*- coding: utf-8 -*- 2 3 import torch 4 import torch.optim as optim 5 6 loss_fn = torch.nn.MSELoss(reduce=False, size_average=False) 7 #loss_fn = torch.nn.MSELoss(reduce=True, size_average=True) 8 #loss_fn = torch.nn.MSELoss() 9 input = torch.autograd.Variable(torch.randn(3,4)) 10 target = torch.autograd.Variable(torch.randn(3,4)) 11 loss = loss_fn(input, target) 12 print(input); print(target); print(loss) 13 print(input.size(), target.size(), loss.size())
結果自己可以運行一下看看.
參考文檔:
1 https://blog.csdn.net/hao5335156/article/details/81029791
2 https://blog.csdn.net/zhangxb35/article/details/72464152?utm_source=itdadao&utm_medium=referral