均方误差MSE

MSE=1Ni=1N(xiyi)2MSE=\frac{1}{N}\sum_{i=1}^{N}(x_i-y_i)^2

函数原型

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

属性说明

  • reduction
    • = ‘none’:no reduction will be applied.下面的实例中,在loss1中是按照原始维度输出,即对应位置的元素相减然后求平方
    • = ‘mean’(默认):the sum of the output will be divided by the number of elements in the output.
    • = ‘sum’:the output will be summed.

Note:

size_average and reduce are in the process of being deprecated, and in the meantime, specifying either of those two args will override reduction.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
a = torch.tensor([[1, 2], 
[3, 4]], dtype=torch.float)

b = torch.tensor([[3, 5],
[8, 6]], dtype=torch.float)

loss_fn1 = torch.nn.MSELoss(reduction='none')
loss1 = loss_fn1(a.float(), b.float())
print(loss1) # 输出结果:tensor([[ 4., 9.],
# [25., 4.]])

loss_fn2 = torch.nn.MSELoss(reduction='sum')
loss2 = loss_fn2(a.float(), b.float())
print(loss2) # 输出结果:tensor(42.)


loss_fn3 = torch.nn.MSELoss(reduction='mean')
loss3 = loss_fn3(a.float(), b.float())
print(loss3) # 输出结果:tensor(10.5000)