0


深度学习中常用的损失函数(一) —— MSELoss()

nn.MSELoss()

  1. 该函数叫做平均平方误差,简称均方误差。它的英文名是mean squared error,该损失函数是挨个元素计算的。该元素的公式如下:
  2. ![loss(x_{i},x_{j})=(x_{i}-x_{j})^2](https://latex.csdn.net/eq?loss%28x_%7Bi%7D%2Cx_%7Bj%7D%29%3D%28x_%7Bi%7D-x_%7Bj%7D%29%5E2)

其连个输入参数,第一个参数是输出的参数,第二个参数是与之对比的参数。

  1. loss= torch.nn.MSELoss(reduce=True, size_average=True)
  2. 1 如果reduce = False,返回向量形式的 loss 

  2、如果reduce = True, 返回标量形式的loss

  1. 3、如果size_average = True,返回 loss.mean();

  4、如果 size_average = False,返回 loss.sum()

  1. 默认情况下:两个参数都为True

其代码如下:

  1. import torch
  2. from torch import nn
  3. loss = nn.MSELoss()
  4. input = torch.randn(3, 5, requires_grad=True)
  5. target = torch.randn(3, 5)
  6. output = loss(input, target)
  7. output.backward() # 反向传播
  8. print('Loss: ',output.item())
  9. # Loss: 1.120721459388733
  1. import torch
  2. from torch import nn
  3. loss = nn.MSELoss(size_average=False) # 以向量的形式返回
  4. input = torch.randn(3, 5,requires_grad=True)
  5. target = torch.randn(3, 5)
  6. output = loss(input, target)
  7. output.backward() # 反向传播
  8. print('Loss: ',output)
  9. # Loss: tensor(35.4082, grad_fn=<MseLossBackward>)

本文转载自: https://blog.csdn.net/weixin_44558721/article/details/127396925
版权归原作者 卡多莫西 所有, 如有侵权,请联系我们删除。

“深度学习中常用的损失函数(一) —— MSELoss()”的评论:

还没有评论