神经网络架构pytorch-MSELoss损失函数

  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

猜你喜欢

转载自www.cnblogs.com/dylancao/p/9848978.html