Pytorch 常见损失函数实现

1.CrossEntropyLoss()函数

1.1.基本计算公式

1.2.Pytorch自带计算

Pytorch中计算的交叉熵:

其中自带的CrossEntropyLoss()函数的主要是将softmax-log-NLLLoss合并到一块得到的结果:

  1. Softmax后的数值都在0~1之间,所以ln之后值域是负无穷到0
  2. 然后将Softmax之后的结果取log,将乘法改成加法减少计算量,同时保障函数的单调性
  3. NLLLoss的结果就是把上面的输出与Label对应的那个值拿出来,去掉负号,再求均值。
nn.CrossEntropyLoss(weight: Optional[Tensor] = None, size_average=None,
         ignore_index: int = -100,reduce=None, reduction: str = 'mean')
  • weight(tensor): 1-D tensor,n个元素,分别代表n类的权重,如果你的训练样本很不均衡的话,是非常有用的。默认值为None。
  • input : 包含每个类的得分,2-D tensor,shape为 batch*n
  • target: 大小为 n 的 1—D tensor,包含类别的索引(0到 n-1)。

2.Focal Loss

2.1.基本计算公式基本计算表达式:

2.2.Pytorch实现

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable

class FocalLoss(nn.Module):
    r"""
        Args:
            alpha(1D Tensor, Variable) : the scalar factor for this criterion
            gamma(float, double) : gamma > 0; reduces the relative loss for 
            	well-classified examples (p > .5), putting more focus on hard, 
            	misclassified examples
            size_average(bool): By default, the losses are averaged over observations
            	 for each minibatch.However, if the field size_average is set to False, 
            	 the losses are instead summed for each minibatch.
    """
    def __init__(self, class_num, alpha=None, gamma=2, size_average=True):
        super(FocalLoss, self).__init__()
        if alpha is None:
            self.alpha = Variable(torch.ones(class_num, 1))
        else:
            if isinstance(alpha, Variable):
                self.alpha = alpha
            else:
                self.alpha = Variable(alpha)
        self.gamma = gamma
        self.class_num = 
### PyTorch 中自定义损失函数用于图像缺陷检测和面积计算 在 PyTorch 中,为了适应特定任务(如图像缺陷检测和面积计算),可以通过自定义损失函数来优化模型的表现。以下是关于如何设计适合该任务的损失函数的一些关键点: #### 1. **理解任务需求** 对于图像缺陷检测和面积计算的任务,核心在于衡量模型预测的缺陷区域与真实缺陷区域之间的差异。这不仅涉及像素级别的匹配,还可能需要关注缺陷形状、大小以及位置的信息。 - 像素级误差可以用二元交叉熵 (Binary Cross Entropy, BCE) 或 Dice Loss 来表示。 - 缺陷面积的准确性可通过 L1/L2 距离或其他几何约束项进一步提升[^1]。 #### 2. **常见损失函数的选择** 以下是一些常用的损失函数及其适用场景: - **BCEWithLogitsLoss**: 这是一个结合了 Sigmoid 函数和 Binary Cross Entropy 的损失函数,常用于二分类问题。它可以有效处理像素级别上的正负样本不平衡情况[^4]。 ```python import torch.nn as nn criterion = nn.BCEWithLogitsLoss() ``` - **Dice Loss**: 更加注重前景区域的重叠程度,尤其当目标区域占比较小时效果显著。其公式如下: \[ D = 1 - \frac{2|A \cap B|}{|A| + |B|} \] 实现代码示例如下: ```python def dice_loss(preds, targets, smooth=1e-7): preds = preds.view(-1) targets = targets.view(-1) intersection = (preds * targets).sum() loss = 1 - ((2.0 * intersection + smooth) / (preds.sum() + targets.sum() + smooth)) return loss ``` - **IoU Loss**: Intersection over Union 是另一个广泛使用的评价标准,可以直接转化为损失函数形式以指导训练过程。 ```python def iou_loss(preds, targets, eps=1e-7): intersection = (preds * targets).sum(dim=(1, 2)) union = preds.sum(dim=(1, 2)) + targets.sum(dim=(1, 2)) - intersection iou = (intersection + eps) / (union + eps) return 1 - iou.mean() ``` #### 3. **结合几何约束** 如果希望模型更好地捕捉缺陷的具体形态,则可以在传统损失基础上加入额外的惩罚项。比如基于轮廓距离或者 Hausdorff Distance 的附加损失可以帮助改善边缘平滑性和定位精度[^3]。 #### 4. **综合多项指标** 单一类型的损失往往难以全面覆盖复杂的真实世界案例;因此推荐组合多种方法共同作用于最终目标之上。例如联合使用 BCE 和 Dice Loss 可兼顾全局分布特性与局部细节保留两方面优势[^2]: ```python def combined_loss(preds, targets, alpha=0.5): bce = nn.BCEWithLogitsLoss()(preds, targets) dsc = dice_loss(torch.sigmoid(preds), targets) return alpha * bce + (1-alpha) * dsc ``` --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值