Pytorch机器学习——3 神经网络(七)

outline

  1. 神经元与神经网络
  2. 激活函数
  3. 前向算法
  4. 损失函数
  5. 反向传播算法
  6. 数据的准备
  7. PyTorch实例:单层神经网络实现

3.4 损失函数

3.4.4 PyTorch中常用的损失函数

  • MSELoss
import torch
loss=torch.nn.MSELoss()
_input = torch.autograd.Variable(torch.randn(3,5),requires_grad=True)
target = torch.autograd.Variable(torch.randn(3,5))
output = loss(_input,target)
print(output)
output.backward()
  • L1Loss(MAE损失)
import torch
loss=torch.nn.L1Loss()
_input = torch.autograd.Variable(torch.randn(3,5),requires_grad=True)
target = torch.autograd.Variable(torch.randn(3,5))
output = loss(_input,target)
print(output)
output.backward()
  • BCELoss:用在二分类问题中
weight指定batch中每个元素的Loss权重,必须是一个长度和batch相等的Tensor
torch.nn.BCELoss(weight=none, size_average=True)
import torch
m = torch.nn.Sigmoid()
loss=torch.nn.BCELoss()
_input = torch.autograd.Variable(torch.randn(3),requires_grad=True)
target = torch.autograd.Variable(torch.FloatTensor(3).random_(2))
output = loss(m(_input),target) #前向输出时使用Sigmoid函数
print(output)
output.backward()
  • BCEWithLogitsLoss:同样用在二分类问题中。不同的是,它把Sigmoid函数集成到函数中,在实际应用中比Sigmoid层加BCELoss层在数值上更加稳定。
  • NLLLoss:使用在多分类任务中的负对数似然损失函数,我们用C表示多分类任务中类别的个数,N表示minibatch,则NLLLoss的输入必须是(N,C)的二维Tensor,即数据集中每个实例对应每个类别的对数概率。
weight可以指定一个一维的Tensor,用来设置每个类别的权重。ignore_index可以设置一个被忽略值,使这个值不会影响到输入的梯度的计算。
torch.nn.NLLLoss(weight=none, size_average=True,ignore_index=-100,reduce=True)
  • CrossEntropyLoss:是LogSoftmax和NLLLoss的组合
torch.nn.CrossEntropyLoss(weight=none, size_average=True,ignore_index=-100,reduce=True)

有用就留个赞吧^_^

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容