torch.nn.KLDivLoss()损失函数输出结果为负数


🤵 AuthorHorizon John

编程技巧篇各种操作小结

🎇 机器视觉篇会变魔术 OpenCV

💥 深度学习篇简单入门 PyTorch

🏆 神经网络篇经典网络模型

💻 算法篇再忙也别忘了 LeetCode


import torch

a = torch.ones((3, 3, 8, 8), dtype=torch.float32) * 0.5
b = a + 0.01

criterion = torch.nn.KLDivLoss()
loss = criterion(a, b)

print(loss)

输出结果:

tensor(-0.5984)

以及出现 UserWarning :

UserWarning: reduction: 'mean' divides the total loss by both the batch size and the support size.'batchmean' divides only by the batch size, and aligns with the KL div math definition.'mean' will be changed to behave the same as 'batchmean' in the next major release.
  "reduction: 'mean' divides the total loss by both the batch size and the support size."

解决方案参考博客:UserWarning: reduction: ‘mean‘ divides the total loss by both the batch size and the support size.

出现负数的原因参考:https://discuss.pytorch.org/

因为在计算损失时把概率分布映射到 log 空间,所以给输入添加 log 即可解决:

import torch

a = torch.ones((3, 3, 8, 8), dtype=torch.float32) * 0.5
b = a + 0.01

criterion = torch.nn.KLDivLoss()
loss = criterion(a.log(), b)

print(loss)

输出结果:

tensor(0.0101)


  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
交叉熵损失函数和负对数似然损失函数是在机器学习中常用的损失函数,用于衡量模型输出与真实标签之间的差异。 交叉熵损失函数是一种常用的分类问题损失函数。它通过计算模型输出的概率分布与真实标签的概率分布之间的交叉熵来衡量两者的差异。在pytorch中,可以使用torch.nn.CrossEntropyLoss()函数来计算交叉熵损失。这个函数会同时计算softmax函数和交叉熵,所以输入的模型输出不需要经过softmax函数处理。 负对数似然损失函数是一种常用的用于最大似然估计的损失函数。在二分类问题中,假设模型的输出是一个介于0和1之间的概率值,表示为θ。负对数似然损失函数可以用来衡量模型输出θ与真实标签0或1之间的差异。当模型输出θ接近1时,即模型预测为正例时的概率较大,负对数似然损失函数的值较小;当模型输出θ接近0时,即模型预测为负例时的概率较大,负对数似然损失函数的值也较小。在pytorch中,可以使用torch.nn.functional.nll_loss()函数来计算负对数似然损失。 综上所述,交叉熵损失函数和负对数似然损失函数都是用来衡量模型输出与真实标签之间的差异的常用损失函数。交叉熵损失函数适用于分类问题,而负对数似然损失函数适用于二分类问题。在实际应用中,根据具体的问题和需求选择合适的损失函数来训练模型。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [损失函数-负对数似然和交叉熵(Pytorch中的应用)](https://blog.csdn.net/tcn760/article/details/123910565)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [15/4/2022交叉熵损失函数和负对数似然损失](https://blog.csdn.net/weixin_44228389/article/details/124202843)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Horizon John

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值