PyTorch内置损失函数汇总 !!

这篇具有很好参考价值的文章主要介绍了PyTorch内置损失函数汇总 !!。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

文章目录

一、损失函数的概念

二、Pytorch内置损失函数

1. nn.CrossEntropyLoss

2. nn.NLLLoss

3. nn.NLLLoss2d

4. nn.BCELoss

5. nn.BCEWithLogitsLoss

6. nn.L1Loss

7. nn.MSELoss

8. nn.SmoothL1Loss

9. nn.PoissonNLLLoss

10. nn.KLDivLoss

11. nn.MarginRankingLoss

12. nn.MultiLabelMarginLoss

13. nn.SoftMarginLoss

14. nn.MultilabelSoftMarginLoss

15. nn.MultiMarginLoss

16. nn.TripletMarginLoss

17. nn.HingeEmbeddingLoss

18. nn.CosineEmbeddingLoss

19. nn.CTCLoss


一、损失函数的概念

损失函数(loss function):衡量模型输出与真实标签的差异。

损失函数也叫代价函数(cost function)/ 准测(criterion)/ 目标函数(objective function)/ 误差函数(error function)。

二、Pytorch内置损失函数

1. nn.CrossEntropyLoss

功能:交叉熵损失函数,用于多分类问题。这个损失函数结合了nn.LogSoftmaxnn.NLLLoss的计算过程。通常用于网络最后的分类层输出

主要参数:

  • weight:各类别的loss设置权值
  • ignore_index:忽略某个类别
  • reduction:计算模式,可为 none /sum /mean:

①. none:逐个元素计算

②. sum:所有元素求和,返回标量

③. mean:加权平均,返回标量

nn.CrossEntropyLoss(weight=None, 
					size_average=None, 
					ignore_index=-100, 
					reduce=None, 
					reduction=‘mean’)

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

# Example of target with class indices
loss = nn.CrossEntropyLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.empty(3, dtype=torch.long).random_(5)
output = loss(input, target)
output.backward()
# Example of target with class probabilities
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5).softmax(dim=1)
output = loss(input, target)
output.backward()

2. nn.NLLLoss

功能:负对数似然损失函数,当网络的最后一层是nn.LogSoftmax时使用。用于训练 C 个类别的分类问题

主要参数:

  • weight:各类别的loss设置权值,必须是一个长度为 C 的 Tensor
  • ignore _index:设置一个目标值, 该目标值会被忽略, 从而不会影响到 输入的梯度
  • reduction :计算模式,可为none /sum /mean

①. none:逐个元素计算

②. sum:所有元素求和,返回标量

③. mean:加权平均,返回标量

nn.NLLLoss(weight=None,
		   size_average=None, 
		   ignore_index=-100, 
		   reduce=None, 
		   reduction='mean')

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

m = nn.LogSoftmax(dim=1)
loss = nn.NLLLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.tensor([1, 0, 4])
output = loss(m(input), target)

3. nn.NLLLoss2d

功能:对于图片输入的负对数似然损失. 它计算每个像素的负对数似然损失。它是nn.NLLLoss的二维版本。适用于图像相关的任务,比如像素级任务或分割

torch.nn.NLLLoss2d(weight=None, ignore_index=-100, reduction='mean')

4. nn.BCELoss

功能:二元交叉熵损失函数,用于二分类问题。计算的是目标值和预测值之间的交叉熵。

注意事项:输入值取值在 [0,1]

主要参数:

  • weight:各类别的loss设置权值
  • ignore_index:忽略某个类别
  • reduction:计算模式,可为none /sum /mean

①. none:逐个元素计算

②. sum:所有元素求和,返回标量

③. mean:加权平均,返回标量

torch.nn.BCELoss(weight=None, 
				 size_average=None,
				 reduce=None, 
 				 reduction='mean')

用法示例:

m = nn.Sigmoid()
loss = nn.BCELoss()
input = torch.randn(3, requires_grad=True)
target = torch.empty(3).random_(2)
output = loss(m(input), target)

5. nn.BCEWithLogitsLoss

功能:结合了nn.Sigmoid层和nn.BCELoss的损失函数,用于二分类问题,尤其在预测值没有经过nn.Sigmoid层时

注意事项:网络最后不加sigmoid函数

主要参数:

  • pos_weight:正样本的权值
  • weight:各类别的loss设置权值
  • ignore_index:忽略某个类别
  • reduction:计算模式,可为none /sum /mean

①. none:逐个元素计算

②. sum:所有元素求和,返回标量

③. mean:加权平均,返回标量

nn.BCEWithLogitsLoss(weight=None, 
					 size_average=None, 
					 reduce=None, reduction='mean', 
					 pos_weight=None)

用法示例:

loss = nn.BCEWithLogitsLoss()
input = torch.randn(3, requires_grad=True)
target = torch.empty(3).random_(2)
output = loss(input, target)

6. nn.L1Loss

功能:L1损失函数,也称为最小绝对偏差(LAD)。它是预测值和真实值之间差的绝对值的和

主要参数:

  • reduction:计算模式,可为none /sum /mean

①. none:逐个元素计算

②. sum:所有元素求和,返回标量

③. mean:加权平均,返回标量

torch.nn.L1Loss(reduction='mean')

用法示例:

loss = nn.L1Loss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)

7. nn.MSELoss

功能:均方误差损失函数,计算预测值和真实值之间差的平方的平均值,用于回归问题。

主要参数:

  • reduction:计算模式,可为none /sum /mean

①. none:逐个元素计算

②. sum:所有元素求和,返回标量

③. mean:加权平均,返回标量

torch.nn.MSELoss(reduction='mean')

用法示例:

loss = nn.MSELoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)

8. nn.SmoothL1Loss

功能:平滑L1损失,也称为Huber损失,主要用于回归问题,尤其是当预测值与目标值差异较大时,比起L1损失更不易受到异常值的影响

  • size_average
  • reduce
  • reduction
  • beta
torch.nn.SmoothL1Loss(reduction='mean')

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

其中,

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

loss = nn.SmoothL1Loss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.randn(3, 5)
output = loss(input, target)

9. nn.PoissonNLLLoss

功能:泊松负对数似然损失,适用于计数或事件率预测,其中预测的是事件发生的平均率

主要参数:

  • log_inpput:输入是否为对数形式,决定计算公式
  • full:计算所有loss,默认为False
  • eps:修正项,避免log(input)为nan
torch.nn.PoissonNLLLoss(log_input=True, full=False,  eps=1e-08,  reduction='mean')

用法示例:

loss = nn.PoissonNLLLoss()
log_input = torch.randn(5, 2, requires_grad=True)
target = torch.randn(5, 2)
output = loss(log_input.exp(), target)

10. nn.KLDivLoss

功能::KL散度损失,用于衡量两个概率分布之间的差异。通常用于模型输出与某个目标分布或另一个模型输出之间的相似性度量

注意事项:需提前将输入计算 log-probabilities,如通过nn.logsoftmax()

主要参数:

  • reduction:none / sum / mean / batchmean

①. batchmean:batchsize维度求平均值

②. none:逐个元素计算

③. sum:所有元素求和,返回标量

④. mean:加权平均,返回标量

torch.nn.KLDivLoss(reduction='mean')

用法示例:

loss = nn.KLDivLoss(reduction='batchmean')
input = torch.log_softmax(torch.randn(5, 10), dim=1)
target = torch.softmax(torch.randn(5, 10), dim=1)
output = loss(input, target)

11. nn.MarginRankingLoss

功能:边缘排序损失,用于排序学习任务,它鼓励正例的得分比负例的得分更高一个边界值

注意事项:该方法计算两组数据之间的差异,返回一个 n*n 的loss 矩阵

主要参数:

  • margin:边界值,x1和x2之间的差异值
  • reduction:计算模式,可为none / sum / mean

①. y=1时,希望x1比x2大,当x1>x2时,不产生loss

②. y=-1时,希望x2比x1大,当x2>x1时,不产生loss

torch.nn.MarginRankingLoss(margin=0.0, reduction='mean')

用法示例:

loss = nn.MarginRankingLoss()
input1 = torch.randn(3, requires_grad=True)
input2 = torch.randn(3, requires_grad=True)
target = torch.randn(3).sign()
output = loss(input1, input2, target)

12. nn.MultiLabelMarginLoss

功能:多标签边缘损失,用于多标签分类问题,其中每个类别的损失是独立计算的。

举例:四分类任务,样本x属于0类或3类

主要参数:

  • reduction:计算模式,可为none / sum / mean
torch.nn.MultiLabelMarginLoss(reduction='mean')

对于mini-batch(小批量) 中的每个样本按如下公式计算损失:

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

loss = nn.MultiLabelMarginLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.tensor([[3, 0, -1, -1, -1],
                       [1, 3, -1, -1, -1],
                       [1, 2, 3, -1, -1]])
output = loss(input, target)

13. nn.SoftMarginLoss

功能:软边缘损失,用于二分类任务,是逻辑回归损失的平滑版本。

主要参数:

  • reduction:计算模式,可为none / sum / mean
torch.nn.SoftMarginLoss(reduction='mean')

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

loss = nn.SoftMarginLoss()
input = torch.randn(3, requires_grad=True)
target = torch.tensor([-1, 1, 1], dtype=torch.float)
output = loss(input, target)

14. nn.MultilabelSoftMarginLoss

功能:多标签软边缘损失,用于多标签分类问题,它是每个标签的二元交叉熵损失的加权版本

主要参数:

  • weight:各类别的loos设置权值
  • reduction:计算模式,可为none / sum / mean
torch.nn.MultiLabelSoftMarginLoss(weight=None, reduction='mean')

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

loss = nn.MultiLabelSoftMarginLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.empty(3, 5).random_(2)
output = loss(input, target)

15. nn.MultiMarginLoss

功能:多类别边缘损失,是SVM(支持向量机)的一个变种,用于多类别分类问题。

主要参数:

  • p:可选1或2
  • weight:各类别的loos设置权值
  • margin:边界值
  • reduction:计算模式,可为none / sum / mean
torch.nn.MultiMarginLoss(p=1, margin=1.0, weight=None,  reduction='mean')

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

loss = nn.MultiMarginLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.tensor([1, 0, 4])
output = loss(input, target)

16. nn.TripletMarginLoss

功能:三元组边缘损失,用于度量学习,其中学习的是输入样本之间的相对距离。人脸验证中常用

主要参数:

  • p:范数的阶,默认为2
  • margin:边界值
  • reduction:计算模式,可为none / sum / mean

和孪生网络相似,具体例子:给一个A,然后再给B、C,看看B、C谁和A更像。

torch.nn.TripletMarginLoss(margin=1.0, p=2.0, eps=1e-06, swap=False, reduction='mean')

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

其中,

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

loss = nn.TripletMarginLoss(margin=1.0, p=2)
anchor = torch.randn(100, 128, requires_grad=True)
positive = torch.randn(100, 128, requires_grad=True)
negative = torch.randn(100, 128, requires_grad=True)
output = loss(anchor, positive, negative)

17. nn.HingeEmbeddingLoss

功能:铰链嵌入损失,用于学习基于距离的相似性,当两个输入被认为是不相似的时,会惩罚它们的距离。常用于非线性embedding和半监督学习

注意事项:输入x 应为两个输入之差的绝对值

主要参数:

  • margin:边界值
  • reduction:计算模式,可为none / sum / mean

torch.nn.HingeEmbeddingLoss(margin=1.0,  reduction='mean')

用法示例:

loss = nn.HingeEmbeddingLoss()
input = torch.randn(3, 5, requires_grad=True)
target = torch.tensor([1, -1, 1])
output = loss(input, target)

18. nn.CosineEmbeddingLoss

功能:余弦嵌入损失,用于学习输入之间的余弦相似性,适用于确定两个输入是否在方向上是相似的

主要参数:

  • margin:可取值[-1, 1],推荐为 [0,0.5]
  • reduction:计算模式,可为none / sum / mean
torch.nn.CosineEmbeddingLoss(margin=0.0, reduction='mean')

PyTorch内置损失函数汇总 !!,Python,损失函数,pytorch,深度学习,计算机视觉,python

用法示例:

loss = nn.CosineEmbeddingLoss()
input1 = torch.randn(3, 5, requires_grad=True)
input2 = torch.randn(3, 5, requires_grad=True)
target = torch.tensor([1, -1, 1])
output = loss(input1, input2, target)

19. nn.CTCLoss

功能:连接时序分类(CTC)损失,用于无对齐或序列到序列问题,如语音或手写识别。

主要参数:

  • blank:blank label
  • zero_infinity:无穷大的值或梯度置0
  • reduction:计算模式,可为none / sum / mean
torch.nn.CTCLoss(blank=0, reduction='mean')

用法示例:

T = 50      # Input sequence length
C = 20      # Number of classes (including blank)
N = 16      # Batch size
S = 30      # Target sequence length of longest target in batch
S_min = 10  # Minimum target length, for demonstration purposes
# Initialize random batch of input vectors, for *size = (T,N,C)
input = torch.randn(T, N, C).log_softmax(2).detach().requires_grad_()
# Initialize random batch of targets (0 = blank, 1:C = classes)
target = torch.randint(low=1, high=C, size=(N, S), dtype=torch.long)
input_lengths = torch.full(size=(N,), fill_value=T, dtype=torch.long)
target_lengths = torch.randint(low=S_min, high=S, size=(N,), dtype=torch.long)
loss = nn.CTCLoss()
output = loss(input, target, input_lengths, target_lengths)

在实际的代码实现中,你需要根据你的模型和数据来调整输入和目标张量的尺寸

参考:https://yolov5.blog.csdn.net/article/details/123441628

参考:深度学习爱好者文章来源地址https://www.toymoban.com/news/detail-823102.html

到了这里,关于PyTorch内置损失函数汇总 !!的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 【深度学习所有损失函数】在 NumPy、TensorFlow 和 PyTorch 中实现(1/2)

    在本文中,讨论了深度学习中使用的所有常见损失函数,并在NumPy,PyTorch和TensorFlow中实现了它们。 我们本文所谈的代价函数如下所列:

    2024年02月13日
    浏览(34)
  • 【深度学习所有损失函数】在 NumPy、TensorFlow 和 PyTorch 中实现(2/2)

    在本文中,讨论了深度学习中使用的所有常见损失函数,并在NumPy,PyTorch和TensorFlow中实现了它们。         稀疏分类交叉熵损失类似于分类交叉熵损失,但在真实标签作为整数而不是独热编码提供时使用。它通常用作多类分类问题中的损失函数。 稀疏分类交叉熵损失的公

    2024年02月13日
    浏览(26)
  • pytorch学习-线性神经网络——softmax回归+损失函数+图片分类数据集

            Softmax回归(Softmax Regression)是一种常见的多分类模型,可以用于将输入变量映射到多个类别的概率分布中。softmax回归是机器学习中非常重要并且经典的模型,虽然叫回归,实际上是一个分类问题         回归是估计一个连续值,分类是预测一个连续的类别  示例

    2024年02月15日
    浏览(37)
  • Pytorch——常用损失函数详解

    首先直接贴上个人看过比较好的一些的解析: 深度学习之常用损失函数 损失函数loss大总结 损失函数(Loss Function) pytorch中的gather函数_PyTorch中的损失函数–L1Loss /L2Loss/SmoothL1Loss 很全的Pytorch loss函数汇总: pytorch loss function 总结 1. 余弦损失函数 torch.nn.CosineEmbeddingLoss 余弦损失

    2024年02月09日
    浏览(28)
  • Pytorch损失函数

    基本用法 criterion = LossCriterion() #构造函数有自己的参数 loss = criterion(x, y) #调用标准时也有参数 1 L1范数损失 L1Loss 计算 output 和 target 之差的绝对值。 参数: 2 均方误差损失 MSELoss 计算 output 和 target 之差的均方差。 参数: 3 交叉熵损失 CrossEntropyLoss 当训练有 C 个类别的分类问

    2023年04月25日
    浏览(26)
  • PyTorch损失函数(二)

    nn.L1Loss 是一个用于计算输入和目标之间差异的损失函数,它计算输入和目标之间的绝对值差异。 主要参数: reduction :计算模式,可以是 none 、 sum 或 mean 。 none :逐个元素计算损失,返回一个与输入大小相同的张量。 sum :将所有元素的损失求和,返回一个标量值。 mean :

    2024年01月17日
    浏览(29)
  • 【AI】《动手学-深度学习-PyTorch版》笔记(三):PyTorch常用函数

    返回一维张量(一维数组),官网说明,常见的三种用法如下 tensor.shape:查看张量的形状 tensor.reshape:返回改变形状后的张量,原张量不变

    2024年02月15日
    浏览(37)
  • pytorch-损失函数-分类和回归区别

    torch.nn 库和 torch.nn.functional库的区别 torch.nn 库:这个库提供了许多预定义的层,如全连接层(Linear)、卷积层(Conv2d)等,以及一些损失函数(如MSELoss、CrossEntropyLoss等)。这些层都是类,它们都继承自 nn.Module ,因此可以很方便地集成到自定义的模型中。 torch.nn 库中的层都

    2024年02月05日
    浏览(34)
  • [pytorch] 8.损失函数和反向传播

    torch提供了很多损失函数,可查看官方文档Loss Functions部分 作用: 计算实际输出和目标输出之间的差距 为更新输出提供一定的依据(反向传播),grad 损失函数用法差不多,这里以L1Loss和MSEloss为例 L1Loss 注意传入的数据要为float类型,不然会报错,所以inputs和outputs处要加上类

    2024年01月25日
    浏览(26)
  • 【PyTorch】在PyTorch中使用线性层和交叉熵损失函数进行数据分类

    在机器学习的众多任务中,分类问题无疑是最基础也是最重要的一环。本文将介绍如何在PyTorch框架下,使用线性层和交叉熵损失函数来解决分类问题。我们将以简单的Iris数据集作为起点,探讨线性模型在处理线性可分数据上的有效性。随后,我们将尝试将同样的线性模型应

    2024年01月18日
    浏览(43)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包