Pytorch损失函数NLLLoss()与CrossEntropyLoss()的关系

Pytorch损失函数NLLLoss()与CrossEntropyLoss()的关系

import torch
input=torch.randn(3,3)

soft_input = torch.nn.Softmax(dim=1)
input1=torch.log(soft_input(input))

print("对input做Softmax,然后取log#############")
print(torch.log(soft_input(input)))


loss=torch.nn.NLLLoss()
target=torch.tensor([0,1,2])
loss(input1,target)
print('调用torch.nn.NLLLoss的结果#########')
print(loss(input1,target))


loss1 =torch.nn.CrossEntropyLoss()
loss1(input,target)
print('调用torch.nn.CrossEntropyLoss()的结果#########')
print(loss1(input,target))



输出结果:

对input做Softmax,然后取log#################
tensor([[-0.3138, -1.5749, -2.7752],
[-2.3118, -0.5529, -1.1219],
[-2.6200, -0.6879, -0.8567]])

调用torch.nn.NLLLoss的结果#################
tensor(0.5745)

调用torch.nn.CrossEntropyLoss()的结果#########
tensor(0.5745)

结论:

softmax(x)+log(x)+nn.NLLLoss====>nn.CrossEntropyLoss

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
nn.NLLLoss()和nn.CrossEntropyLoss()是用于多分类任务的损失函数,在PyTorch中它们实际上是相同的。唯一的区别在于它们接收的输入不同: - nn.NLLLoss()的输入是一个对数概率向量和一个目标标签,它不会为我们计算对数概率。适合网络的最后一层是log_softmax损失函数的情况。 - nn.CrossEntropyLoss()的输入是一个预测值和一个目标标签,它会为我们自动计算预测值的对数概率,即先做softmax,再做log处理。在实际使用中,两者可以互换使用,效果是一样的。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [paddle中nll_loss()与CrossEntropyLoss()损失函数区别](https://blog.csdn.net/weixin_43848436/article/details/115448659)[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^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] - *2* *3* [Pytorch损失函数 NLLLOSSCROSSENTROPYLOSS 的区别](https://blog.csdn.net/cnhwl/article/details/125518586)[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^v92^chatsearchT0_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值