pytorch代码-图像分类损失函数

本文主要是实践代码篇,所以不会贴出太多理论知识,但是也会贴上理论解释的一些博文,对理论有兴趣的可以去看看

代码来源

本文代码来自:基于pytorch实现的图像分类源码
代码实践示例:使用Pytorch实现图像花朵分类

图像分类损失

import torch
import torch.nn as nn
class CrossEntropyLoss(nn.Module):
    def __init__(self, label_smoothing: float = 0.0, weight: torch.Tensor = None):
        super(CrossEntropyLoss, self).__init__()
        self.cross_entropy = nn.CrossEntropyLoss(weight=weight, label_smoothing=label_smoothing)
    
    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        return self.cross_entropy(input, target)
其中label_smoothing是标签平滑的值,weight是每个类别的类别权重。
假设有三个类别,我想设定类别权重为 0.5,0.8,1.5
那么代码就是:
l = CrossEntropyLoss(weight=torch.fromnumpy(np.array([0.5,0.8,1.5])))
import torch
import torch.nn as nn
import torch.nn.functional as F
class FocalLoss(nn.Module):
    def __init__(self, label_smoothing:float = 0.0, weight: torch.Tensor = None, gamma:float = 2.0):
        super(FocalLoss, self).__init__()
        self.label_smoothing = label_smoothing
        self.weight = weight
        self.gamma = gamma
    
    def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
        target_onehot = F.one_hot(target, num_classes=input.size(1))
        target_onehot_labelsmoothing = torch.clamp(target_onehot.float(), min=self.label_smoothing/(input.size(1)-1), max=1.0-self.label_smoothing)
        input_softmax = F.softmax(input, dim=1) + 1e-7
        input_logsoftmax = torch.log(input_softmax)
        ce = -1 * input_logsoftmax * target_onehot_labelsmoothing
        fl = torch.pow((1 - input_softmax), self.gamma) * ce
        fl = fl.sum(1) * self.weight[target.long()]
        return fl.mean()
我们这个focalloss是支持标签平滑的。
其中label_smoothing是标签平滑的值,weight是每个类别的类别权重(可以理解为二分类focalloss中的alpha,因为alpha就是调节样本的平衡度),。
假设有三个类别,我想设定类别权重为 0.5,0.8,1.5
那么代码就是:
l = FocalLoss(weight=torch.fromnumpy(np.array([0.5,0.8,1.5])))
import torch
import torch.nn as nn
import torch.nn.functional as F
class PolyLoss(nn.Module):
    """
    PolyLoss: A Polynomial Expansion Perspective of Classification Loss Functions
    <https://arxiv.org/abs/2204.12511>
    """
    def __init__(self, label_smoothing: float = 0.0, weight: torch.Tensor = None, epsilon=2.0):
        super().__init__()
        self.epsilon = epsilon
        self.label_smoothing = label_smoothing
        self.weight = weight

    def forward(self, outputs, targets):
        ce = F.cross_entropy(outputs, targets, label_smoothing=self.label_smoothing, weight=self.weight)
        pt = F.one_hot(targets, outputs.size()[1]) * F.softmax(outputs, 1)

        return (ce + self.epsilon * (1.0 - pt.sum(dim=1))).mean()
其中label_smoothing是标签平滑的值,weight是每个类别的类别权重。
假设有三个类别,我想设定类别权重为 0.5,0.8,1.5
那么代码就是:
l = PolyLoss(weight=torch.fromnumpy(np.array([0.5,0.8,1.5])))

最后

可能有小伙伴不知道该如何确定类别的权重,一般出现需要设定类别权重的两种情况:

  1. 类别不平衡
    对于这种情况,基本上都是使用sklearn中的compute_class_weight方法进行计算每个类别对应的权重.
  2. 类别基本平衡,但是某个类别准确率相对比较低
    对于这种情况,你需要手动设定weight,你需要可视化测试集的每个类别的识别情况,再根据那个类别精度比较低,可以适当调高这个类别的权重,就等于让模型更多的注意到这个类别的loss进行优化。

当然也有小伙伴可能代码能力比较差,但是不用怕,这个代码已经帮你们实现上述的需求,还有更加丰富的可视化和功能,有需要可以使用一下。这个代码的使用示例在本博客开头代码来源中有链接,有整个操作流程。

如果内容对你有帮助,麻烦点个赞,谢谢!

有计算机视觉合作项目可以私信作者!

  • 6
    点赞
  • 29
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
Shape-aware Loss 是一种用于图像分割任务的损失函数,它通过考虑目标形状信息来提高分割模型的性能。下面是使用 PyTorch 实现 Shape-aware Loss 的代码和使用方法: ```python import torch import torch.nn as nn class ShapeAwareLoss(nn.Module): def __init__(self, lambda_shape=1.0, reduction='mean'): super(ShapeAwareLoss, self).__init__() self.lambda_shape = lambda_shape self.reduction = reduction def forward(self, inputs, targets): bce_loss = nn.BCEWithLogitsLoss(reduction='none')(inputs, targets) shape_loss = self._compute_shape_loss(targets) total_loss = bce_loss + self.lambda_shape * shape_loss if self.reduction == 'mean': return total_loss.mean() elif self.reduction == 'sum': return total_loss.sum() else: return total_loss def _compute_shape_loss(self, targets): # 计算形状损失的具体实现 # 这里可以根据具体需求进行编写,下面是一个简单示例 shape_loss = torch.mean(torch.abs(targets - torch.mean(targets))) return shape_loss # 使用示例 criterion = ShapeAwareLoss(lambda_shape=0.5) inputs = torch.randn(10, 1, 256, 256) # 模型预测结果 targets = torch.randn(10, 1, 256, 256) # 真实标签 loss = criterion(inputs, targets) loss.backward() ``` 在上面的代码中,我们定义了一个名为 `ShapeAwareLoss` 的自定义损失函数类,它继承自 `nn.Module`。在 `forward` 方法中,我们首先计算二值交叉熵损失(`bce_loss`),然后计算形状损失(`shape_loss`)通过调用 `_compute_shape_loss` 方法。最后,将二值交叉熵损失和形状损失加权相加得到最终的损失值。 在使用示例中,我们创建了一个 `ShapeAwareLoss` 实例,并传入了 `lambda_shape` 参数。然后,我们创建了模型的预测结果 `inputs` 和对应的真实标签 `targets`。通过调用 `criterion` 实例的前向传播方法,即可计算出 Shape-aware Loss,并进行反向传播以更新模型参数。 请注意,这只是 Shape-aware Loss 的一个简单实现例子,你可以根据自己的需求和实际场景进行更改和调整。具体的形状损失计算方法需要根据具体任务和需求来设计,并在 `_compute_shape_loss` 方法中实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

魔鬼面具

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

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

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

打赏作者

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

抵扣说明:

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

余额充值