torch中的NLLLoss与CrossEntropyLoss

0.先搞清楚几种分类问题

图片分类问题中通常一张图片中同时有多个目标,所以会有多个标签,通常分类问题可以如下划分

表格1
样本单标签样本多标签
类别数量=2简单二分类当作多个二分类
类别数量>2多分类当作多个二分类

1.pytorch常用loss总结

     pytorch中常用的几种loss:BCELoss、BCEWithLogitsLoss、NLLLoss、CrossEntropyLoss

1.1 NLLLoss和CrossEntropyLoss

     总结一下:CrossEntropyLoss(x, label) = softmax(x) + log(x) + NLLLoss(x, label)

     应用在表格1中的多分类问题

Pytorch详解NLLLoss和CrossEntropyLoss_豪哥的博客-CSDN博客_nlllosshttps://blog.csdn.net/qq_22210253/article/details/85229988

1.2 BCELoss和BCEWithLogitsLoss

     BCEWithLogitsLoss(x, label)= sigmoid(x) + BCELoss(x, label)

     应用在表格1中的所有二分类问题

Pytorch详解BCELoss和BCEWithLogitsLoss_豪哥的博客-CSDN博客_bcewithlogitslossBCELoss在图片多标签分类时,如果3张图片分3类,会输出一个3*3的矩阵。先用Sigmoid给这些值都搞到0~1之间:假设Target是:BCELoss是−1n∑(yn×ln⁡xn+(1−yn)×ln⁡(1−xn))-\frac 1 n\sum(y_n \times \ln x_n+(1-y_n) \times \ln(1-x_n))−n1​∑(yn​×lnxn​+(1−yn​)...https://blog.csdn.net/qq_22210253/article/details/85222093

2. softlabel的loss实现

2.1 二分类问题

通过BCEWithLogitsLoss可以直接实现softlabel的loss

2.2 多分类问题

  因为CrossEntropyLoss和NLLLoss都是默认hardlabel实现的,所以:

  根据交叉熵的公式 target * log(p)

import torch
import torch.nn.functional as F


def SoftCrossEntropy(inputs, target, reduction='sum'):
    log_likelihood = -F.log_softmax(inputs, dim=1)
    batch = inputs.shape[0]
    if reduction == 'average':
        loss = torch.sum(torch.mul(log_likelihood, target)) / batch
    else:
        loss = torch.sum(torch.mul(log_likelihood, target))
    return loss

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值