YOLOv11改进 | 损失函数改进篇 | 更加聚焦的边界框损失Focaler-IoU、InnerFocalerIoU(二次创新,解决样本不平衡问题)

 一、本文介绍

本文给大家带来的改进机制是更加聚焦的边界框损失Focaler-IoU已经我进行二次创新的InnerFocalerIoU同时本文的内容支持现阶段的百分之九十以上的IoU,比如Focaler-IoU、Focaler-ShapeIoU、Inner-Focaler-ShapeIoU包含非常全的损失函数,边界框的损失函数只看这一篇就够了。

在开始之前给大家推荐一下我的专栏,本专栏每周更新3-10篇最新前沿机制 | 包括二次创新全网无重复,以及融合改进(大家拿到之后添加另外一个改进机制在你的数据集上实现涨点即可撰写论文),还有各种前沿顶会改进机制 |,更有包含我所有附赠的文件(文件内集成我所有的改进机制全部注册完毕可以直接运行)和交流群和视频讲解提供给大家。  

欢迎大家订阅我的专栏一起学习YOLO!

 专栏回顾:YOLOv11改进系列专栏——本专栏持续复习各种顶会内容——科研必备


目录

 一、本文介绍

二、Focaler-IoU原理 

2.1  Focaler-IoU的基本原理

三、核心代码 

四、 损失函数使用方式 

4.1 步骤一 

4.2 步骤二

4.3 步骤三 

4.4 步骤四

4.5 什么时候使用损失函数改进

五、本文总结


二、Focaler-IoU原理 

论文地址:论文官方地址

代码地址:代码官方地址


2.1  Focaler-IoU的基本原理

Focaler-IoU是一种在对象检测中用于边界框回归的损失函数。这种方法的基本原理可以从以下几个方面来理解:

1. 专注于不同的回归样本:Focaler-IoU 通过对不同的回归样本进行聚焦,来提高在不同检测任务中的探测器性能。这是通过线性区间映射来重构IoU损失,实现对不同样本的关注。

2. 解决困难和简单样本分布问题:它分析并考虑了困难样本和简单样本在边界框回归中的分布对回归结果的影响,这是传统IoU损失函数中常被忽视的一个方面。

3. 改进现有的边界框回归方法:Focaler-IoU 通过其特有的方法来弥补现有边界框回归方法的不足,从而在不同的检测任务中进一步提高检测性能。

上面这个公式定义了Focaler-IoU,它根据交并比(IoU)的值来调整损失。

当IoU小于一个下限阈值 d 时,损失为0;

当IoU大于一个上限阈值 u 时,损失为1;

而当IoU处于 d 和 u 之间时,损失是一个根据IoU值线性递增的函数。

这样的设计允许损失函数在一定区间内对IoU值敏感,从而能够更专注于那些预测边界框与真实边界框重叠度中等的样本,即既不是太难也不是太容易的样本。这有助于模型更好地学习从中等困难的样本中提取特征,而不是仅仅专注于最容易或最困难的样本。 


三、核心代码 

代码的使用方式看章节四!

import numpy as np
import torch
import math

def xyxy2xywh(x):
    """
    Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format where (x1, y1) is the
    top-left corner and (x2, y2) is the bottom-right corner.

    Args:
        x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x1, y1, x2, y2) format.

    Returns:
        y (np.ndarray | torch.Tensor): The bounding box coordinates in (x, y, width, height) format.
    """
    assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
    y = torch.empty_like(x) if isinstance(x, torch.Tensor) else np.empty_like(x)  # faster than clone/copy
    y[..., 0] = (x[..., 0] + x[..., 2]) / 2  # x center
    y[..., 1] = (x[..., 1] + x[..., 3]) / 2  # y center
    y[..., 2] = x[..., 2] - x[..., 0]  # width
    y[..., 3] = x[..., 3] - x[..., 1]  # height
    return y

class WIoU_Scale:
    ''' monotonous: {
            None: origin v1
            True: monotonic FM v2
            False: non-monotonic FM v3
        }
        momentum: The momentum of running mean'''
    iou_mean = 1.
    monotonous = False
    _momentum = 1 - 0.5 ** (1 / 7000)
    _is_train = True

    def __init__(self, iou):
        self.iou = iou
        self._update(self)

    @classmethod
    def _update(cls, self):
        if cls._is_train: cls.iou_mean = (1 - cls._momentum) * cls.iou_mean + \
                                         cls._momentum * self.iou.detach().mean().item()

    @classmethod
    def _scaled_loss(cls, self, gamma=1.9, delta=3):
        if isinstance(self.monotonous, bool):
            if self.monotonous:
                return (self.iou.detach() / self.iou_mean).sqrt()
            else:
                beta = self.iou.detach() / self.iou_mean
                alpha = delta * torch.pow(gamma, beta - delta)
                return beta / alpha
        return 1

def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, EIoU=False, SIoU=False, WIoU=False, ShapeIoU=False,
             hw=1, mpdiou=False, Inner=False, Focaleriou=False, d=0.00, u=0.95, ratio=0.7, eps=1e-7, scale=0.0):
    """
    Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).

    Args:
        box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).
        box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).
        xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in
                               (x1, y1, x2, y2) format. Defaults to True.
        GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.
        DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.
        CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.
        EIoU (bool, optional): If True, calculate Efficient IoU. Defaults to False.
        SIoU (bool, optional): If True, calculate Scylla IoU. Defaults to False.
        eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.

    Returns:
        (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
    """
    if Inner:
        if not xywh:
            box1, box2 = xyxy2xywh(box1), xyxy2xywh(box2)
        (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
        b1_x1, b1_x2, b1_y1, b1_y2 = x1 - (w1 * ratio) / 2, x1 + (w1 * ratio) / 2, y1 - (h1 * ratio) / 2, y1 + (
                    h1 * ratio) / 2
        b2_x1, b2_x2, b2_y1, b2_y2 = x2 - (w2 * ratio) / 2, x2 + (w2 * ratio) / 2, y2 - (h2 * ratio) / 2, y2 + (
                    h2 * ratio) / 2

        # Intersection area
        inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
                (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)

        # Union Area
        union = w1 * h1 * ratio * ratio + w2 * h2 * ratio * ratio - inter + eps

    # Get the coordinates of bounding boxes
    else:
        if xywh:  # transform from xywh to xyxy
            (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
            w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
            b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
            b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
        else:  # x1, y1, x2, y2 = box1
            b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
            b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
            w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
            w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps

        # Intersection area
        inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
                (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
        # Union Area
        union = w1 * h1 + w2 * h2 - inter + eps
        # IoU
    iou = inter / union
    if Focaleriou:
        iou = ((iou - d) / (u - d)).clamp(0, 1)  # default d=0.00,u=0.95

    if CIoU or DIoU or GIoU or EIoU or SIoU or ShapeIoU or mpdiou or WIoU:
        cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1)  # convex (smallest enclosing box) width
        ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1)  # convex height
        if CIoU or DIoU or EIoU or SIoU or mpdiou or WIoU or ShapeIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
            c2 = cw ** 2 + ch ** 2 + eps  # convex diagonal squared
            rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4  # center dist ** 2
            if CIoU:  # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
                v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
                with torch.no_grad():
                    alpha = v / (v - iou + (1 + eps))
                return iou - (rho2 / c2 + v * alpha)  # CIoU
            elif EIoU:
                rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
                rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
                cw2 = cw ** 2 + eps
                ch2 = ch ** 2 + eps
                return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2) # EIoU
            elif SIoU:
                # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
                s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
                s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
                sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
                sin_alpha_1 = torch.abs(s_cw) / sigma
                sin_alpha_2 = torch.abs(s_ch) / sigma
                threshold = pow(2, 0.5) / 2
                sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
                angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
                rho_x = (s_cw / cw) ** 2
                rho_y = (s_ch / ch) ** 2
                gamma = angle_cost - 2
                distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
                omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
                omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
                shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
                return iou - 0.5 * (distance_cost + shape_cost) + eps # SIoU
            elif ShapeIoU:
                #Shape-Distance    #Shape-Distance    #Shape-Distance    #Shape-Distance    #Shape-Distance    #Shape-Distance    #Shape-Distance
                ww = 2 * torch.pow(w2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
                hh = 2 * torch.pow(h2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
                cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1)  # convex width
                ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1)  # convex height
                c2 = cw ** 2 + ch ** 2 + eps                            # convex diagonal squared
                center_distance_x = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2) / 4
                center_distance_y = ((b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
                center_distance = hh * center_distance_x + ww * center_distance_y
                distance = center_distance / c2

                #Shape-Shape    #Shape-Shape    #Shape-Shape    #Shape-Shape    #Shape-Shape    #Shape-Shape    #Shape-Shape    #Shape-Shape
                omiga_w = hh * torch.abs(w1 - w2) / torch.max(w1, w2)
                omiga_h = ww * torch.abs(h1 - h2) / torch.max(h1, h2)
                shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
                return iou - distance - 0.5 * shape_cost
            elif mpdiou:
                d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
                d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
                return iou - d1 / hw.unsqueeze(1) - d2 / hw.unsqueeze(1)  # MPDIoU
            elif WIoU:
                self = WIoU_Scale(1 - iou)
                dist = getattr(WIoU_Scale, '_scaled_loss')(self)
                return iou * dist  # WIoU https://arxiv.org/abs/2301.10051
            return iou - rho2 / c2  # DIoU
        c_area = cw * ch + eps  # convex area
        return iou - (c_area - union) / c_area  # GIoU https://arxiv.org/pdf/1902.09630.pdf
    return iou  # IoU

四、 损失函数使用方式 

4.1 步骤一 

上面的代码我们首先找到'ultralytics/utils/metrics.py'文件,然后其中有一个完全同名字的方法,原始样子如下,我们将我们的代码完整替换掉这个代码,记得是全部替换这个方法内的代码。


4.2 步骤二

替换成功后,我们找到另一个文件'ultralytics/utils/loss.py'然后找到如下一行代码原始样子下面的图片然后用我给的代码替换掉其中的红框内的一行即可。

        iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask],
                       xywh=False, GIoU=False, DIoU=False, CIoU=False, EIoU=False, SIoU=False, WIoU=False,
                       ShapeIoU=False, hw=hw[fg_mask], mpdiou=False, Inner=False, Focaleriou=True,
                       d=0.00, u=0.95, ratio=0.75, eps=1e-7, scale=0.0)

上面的代码我来解释一下,我把所有的能选用的参数都写了出来,其中IoU很好理解了,对应的参数设置为True就是使用的对应的IoU包括本文的FocalerIoU,需要注意的是Inner这个参数,比如我Inner设置为True然后FocalerIoU也设置为True那么此时使用的就是Inner_FocalerIoU,其它的都是,其中d和u是FocalerIoU的参数大家可以自己尝试我这里定义了两个官方推荐默认真。 

替换完后的样子如下(此时FocalerIoU已经设置为True了)->


4.3 步骤三 

找到如下的代码,基本样子差不多只是多了最后一个位置的参数,用我给的代码替换即可,下面为基本样子。

 用我给的代码替换

        # Bbox loss
        if fg_mask.sum():
            target_bboxes /= stride_tensor
            loss[0], loss[2] = self.bbox_loss(pred_distri, pred_bboxes, anchor_points, target_bboxes, target_scores,
                                              target_scores_sum, fg_mask,
                                              ((imgsz[0] ** 2 + imgsz[1] ** 2) / torch.square(stride_tensor)).repeat(1,
                                                                                                                     batch_size).transpose(
                                                  1, 0))

下面的样子是替换完的。


4.4 步骤四

 我们还需要修改一处,找到如下的文件''ultralytics/utils/tal.py''然后找到其中下面图片的代码,用我给的代码替换红框内的代码。

    def iou_calculation(self, gt_bboxes, pd_bboxes):
        """IoU calculation for horizontal bounding boxes."""
        return bbox_iou(gt_bboxes,  pd_bboxes, xywh=False, GIoU=False, DIoU=False, CIoU=True,
                                     EIoU=False, SIoU=False, WIoU=False, ShapeIoU=False, Inner=False,
                                     ratio=0.7, eps=1e-7, scale=0.0).squeeze(-1).clamp_(0)

此处和loss.py里面的最好是使用同一个参数。

替换完之后的样子->


4.5 什么时候使用损失函数改进

在这里多说一下,就是损失函数的使用时间,当我们修改模型的时候,损失函数是作为一种保底的存在,就是说当其它模型结构都修改完成了,已经无法在提升精度了,此时就可以修改损失函数了,不要上来先修改损失函数,当然这是我个人的建议,具体还是由大家自己来选择。


五、本文总结

到此本文的正式分享内容就结束了,在这里给大家推荐我的YOLOv11改进有效涨点专栏,本专栏目前为新开的平均质量分98分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~

希望大家阅读完以后可以给文章点点赞和评论支持一下这样购买专栏的人越多群内人越多大家交流的机会就更多了。  

 专栏回顾:YOLOv11改进系列专栏——本专栏持续复习各种顶会内容——科研必备

猜你喜欢

转载自blog.csdn.net/java1314777/article/details/143497064