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

 nn.MSELoss() 

        该函数叫做平均平方误差,简称均方误差。它的英文名是mean squared error,该损失函数是挨个元素计算的。该元素的公式如下:

                                loss(x_{i},x_{j})=(x_{i}-x_{j})^2

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

       loss= torch.nn.MSELoss(reduce=True, size_average=True)

       1、 如果reduce = False,返回向量形式的 loss 

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

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

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

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

其代码如下: 

import torch
from torch import nn

loss = nn.MSELoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward() # 反向传播
print('Loss: ',output.item())

# Loss:  1.120721459388733
import torch
from torch import nn

loss = nn.MSELoss(size_average=False) # 以向量的形式返回
input = torch.randn(3, 5,requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)
output.backward() # 反向传播
print('Loss: ',output)
# Loss:  tensor(35.4082, grad_fn=<MseLossBackward>)

 

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
心中带点小风骚的头像心中带点小风骚普通用户
上一篇 2023年8月17日
下一篇 2023年8月17日

相关推荐