【深度学习】【Pytorch学习】Pytorch自带Loss总结

本文详细总结了PyTorch中的几种损失函数,包括L1Loss、MSELoss、NLLLoss、CrossEntropyLoss、BCELoss和BCEWithLogitsLoss,以及它们在深度学习和神经网络中的应用和差异。
摘要由CSDN通过智能技术生成

Loss总结

L1Loss

mean absolute error
在这里插入图片描述
默认reduction参数为mean,是对所有的元素进行平均。
在这里插入图片描述

MSELoss

在这里插入图片描述
默认reduction参数为mean。除了使用MSE计算loss,其他的与L1Loss一样。

NLLLoss

negative log likelihood loss,用于多分类问题

在这里插入图片描述 在这里插入图片描述
在计算时,对于每个batch的 ln,只使用xn中与yn相对应的元素进行计算。减小loss以为这相对于元素增大,由于是经过softmax层的,代表其他类的元素值下降。

  • 输入
    • x: size = (batch,class,* ), x储存每个类的log-probabilities,在神经网络添加LogSoftmax层
    • y:size = (batch,* )
  • 参数
    • weight:1D Tensor,每个类的weight
    • ignore_index:忽略类的index
    • reduction:'mean’和‘sum’是标量,对所有元素进行mean或者sum

CrossEntropyLoss

结合了LogSoftmax和NLLLoss

输入和NLLLoss一样,参数也相同。

BCELoss

Binary Cross Entropy
在这里插入图片描述

  • 输入
    • x:size = (N,*),由于是2分类问题,所以没有类的信息,神经网络的最后一层应是Sigmoid,将x归入[0,1]
    • y:size = (N,*),元素非0即1
  • 参数
    • reduction
    • weight:下面代码实验weight的选取
import torch.nn as nn
import torch

m = nn.Sigmoid()
input = torch.randn(4, 5, requires_grad=True)
target = torch.empty(4, 5).random_(2)
input = m(input)

loss1 = nn.BCELoss(reduction='none')
output1 = loss1(input, target)
print("output1:\n", output1)

#w2 = torch.empty(4).random_(2)
#loss2 = nn.BCELoss(reduction='none', weight=w2)
#output2 = loss2(input, target)
#print(w2, output2)

w3 = torch.empty(4, 1).random_(2)
loss3 = nn.BCELoss(reduction='none', weight=w3)
output3 = loss3(input, target
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值