图像分类的Label smooth介绍与代码实现

目的

解决分类模型存在的过拟合(over-fitting)和过分自信(overconfident)的问题。

思想

中庸思想,答对了不过分夸奖,打错了不过分惩罚,既要保持答对与答错的区分度,又有保持一定的可伸缩性,防止一棍子打死

公式

image.png

过分自信(overconfident)

预测出来的概率,比模型整体的概率高
image.png

实现

负对数似然损失:NLLloss

NLLloss(negative log-likelihood loss):对x(输入)做softmax,然后取log(对数),等价于CrossEntropyLoss(交叉熵损失)

做法

import torch
import torch.nn as nn
import torch.nn.functional as F

class LabelSmoothingCrossEntropy(nn.Module):
    """
    Cross Entropy loss with label smoothing.
    """
    def __init__(self, smoothing=0.1):
        """
        Constructor for the LabelSmoothing module.
        :param smoothing: label smoothing factor
        """
        super(LabelSmoothingCrossEntropy, self).__init__()
        assert 0.0 < smoothing < 1.0
        self.smoothing = smoothing
        self.confidence = 1. - smoothing

    def forward(self, x, target):
        """
        写法1
        """
        # logprobs = F.log_softmax(x, dim=-1)
        # nll_loss = -logprobs.gather(dim=-1, index=target.unsqueeze(1))
        # nll_loss = nll_loss.squeeze(1)  # 得到交叉熵损失
        # # 注意这里要结合公式来理解,同时留意预测正确的那个类,也有a/K,其中a为平滑因子,K为类别数
        # smooth_loss = -logprobs.mean(dim=1)
        # loss = self.confidence * nll_loss + self.smoothing * smooth_loss
        """
        写法2
        """
        y_hat = torch.softmax(x, dim=1)
        # 这里cross_loss和nll_loss等价
        cross_loss = self.cross_entropy(y_hat, target)
        smooth_loss = -torch.log(y_hat).mean(dim=1)
        # smooth_loss也可以用下面的方法计算,注意loga + logb = log(ab)
        # smooth_loss = -torch.log(torch.prod(y_hat, dim=1)) / y_hat.shape[1]
        loss = self.confidence * cross_loss + self.smoothing * smooth_loss
        return loss.mean()

    def cross_entropy(self, y_hat, y):
        return - torch.log(y_hat[range(len(y_hat)), y])

l = LabelSmoothingCrossEntropy(smoothing=0.1)

# 两个样本,第一个正确类为第1类,第二个正确类为第3类
x = torch.tensor([[0.0682, -0.5742,  0.3612, -0.4870, -2.7665],
                  [-0.8642, -0.0828, -0.9225, -1.1206,  0.6337]])
target = torch.tensor([0, 2])

a = l.forward(x, target)
print(a)

tensor(1.7892)

参考链接

https://towardsdatascience.com/what-is-label-smoothing-108debd7ef06

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值