YOLOv8改进:损失函数改为SIOU、EIOU、WIOU、Focal-IOU、a-IOU

目录

1.介绍

1.1 IOU

1.2 SIOU

1.3 WIOU

2.替换 IoU       

 3.替换WIOU



1.介绍

1.1 IOU

在机器学习领域,损失函数(Loss Function)是衡量模型预测值和真实值之间差异的函数。在训练期间,模型会尝试最小化损失函数的值,从而提高模型的准确性。

通常来说,损失函数的定义方式取决于你要解决的问题类型。例如,在分类问题中,常见的损失函数包括交叉熵损失函数和负对数似然损失函数等;在回归问题中,通常使用均方误差(MSE)损失函数和平均绝对误差(MAE)损失函数等。

以分类问题为例,交叉熵损失函数是一种常用的损失函数,通常用来度量模型在分类问题上的性能。交叉熵损失函数的定义如下:        

其中,y表示真实标签的向量(标签被编码为一组0或1),而p表示模型预测标签的向量,代表模型对每个类别属于正例的概率。n是类别总数。

交叉熵损失函数通常用于多分类问题中,它的主要特点是能够惩罚模型在错误分类的情况下的置信度预测。

在训练过程中,在每个训练样本上,损失函数都会计算当前模型的预测标签与真实标签之间的距离(或差异),并根据其结果调整模型权重,以尽量减小损失函数值。因此,选择合适的损失函数非常重要,并且可以对模型性能产生重大影响。

1.2 SIOU

SIOU(Smoothed Intersection over Union,平滑交并比)是一种用于目标检测中的评价指标,旨在更加准确地衡量预测框与真实目标框之间的相似程度。

传统的IoU(Intersection over Union,交并比)是用于衡量两个框之间重叠的面积大小的常见指标。在目标检测任务中,通常将IoU作为一种衡量预测框质量的评价指标,即预测框与真实目标框之间的IoU越大,说明预测框越与真实目标框匹配。

但是,传统的IoU存在两个问题:1)IoU是一个硬阈值,无法处理近似正确但不完全匹配的情况;2)IoU在预测框和真实目标框发生较小变化时非常敏感,可能会引起误判。

SIOU通过引入一个平滑函数来解决这些问题,将IoU从硬阈值转换为一个连续可微的函数。SIOU可以被表示为以下公式:

SIOU(p, g) = s(p, α) * IoU(p, g) + (1 - s(p, α))

其中,p是预测框,g是真实目标框,α是平滑系数,控制平滑函数的形状。SIOU首先计算预测框和真实目标框之间的IoU,然后使用一个平滑函数s(p, α)对其进行加权,最后将加权后的IoU值和一个补偿项(1-s(p, α))结合起来。

平滑函数s(p, α)通常采用高斯分布或者sigmoid函数等,可以控制IoU是否需要被平滑处理,以及平滑程度的大小。

通过引入平滑函数,SIOU可以处理近似正确但不完全匹配的情况,并且可以抵抗预测框和真实目标框发生较小变化时的误判。SIOU在一些目标检测算法中得到了广泛应用,如RetinaNet、FCOS等。

1.3 WIOU

WIOU(Weighted Intersection over Union,加权交并比)是一种用于目标检测中的评价指标,旨在更加准确地衡量预测框与真实目标框之间的相似程度。

传统的IoU(Intersection over Union,交并比)是用于衡量两个框之间重叠的面积大小的常见指标。在目标检测任务中,通常将IoU作为一种衡量预测框质量的评价指标,即预测框与真实目标框之间的IoU越大,说明预测框越与真实目标框匹配。

WIOU首先通过计算IoU来测量两个框之间的重叠程度,然后使用预测框和真实目标框中每个部分的最小权重来对其进行加权,以准确地描述每个部分的贡献。最后,WIOU使用两个框中每个部分的最大权重来归一化加权后的IoU值。

通过引入权重概念,WIOU可以更准确地衡量预测框和真实目标之间的相似性,尤其在涉及到多个物体部分时可以提高检测精度。WIOU已被应用于广泛的目标检测算法中,如CornerNet、CenterNet等。

2.替换 IoU       

yolov8中box_iou其默认用的是CIoU,其中代码还带有GIoU,DIoU,文件路径:ultralytics/yolo/utils/metrics.py,函数名为:bbox_iou 

def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
    # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
 
    # Get the coordinates of bounding boxes
    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).clamp(eps)
        w2, h2 = b2_x2 - b2_x1, (b2_y2 - b2_y1).clamp(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 CIoU or DIoU or GIoU:
        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:  # 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
            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

在原bbox_iou中,GIoU、DIoU、CIoU都是默认关闭,为最普通的Iou,如果其中一个为True的时候,即返回设定为True的那个Iou。

要添加WIoU,只需要把上面bbox_iou替换为下面的代码:

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, SIoU=False, EIoU=False, WIoU=False, Focal=False, alpha=1, gamma=0.5, scale=False, eps=1e-7):
    # Returns Intersection over Union (IoU) of box1(1,4) to box2(n,4)
 
    # Get the coordinates of bounding boxes
    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).clamp(eps)
        w2, h2 = b2_x2 - b2_x1, (b2_y2 - b2_y1).clamp(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
    if scale:
        self = WIoU_Scale(1 - (inter / union))
 
    # IoU
    # iou = inter / union # ori iou
    iou = torch.pow(inter/(union + eps), alpha) # alpha iou
    if CIoU or DIoU or GIoU or EIoU or SIoU 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 WIoU:  # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
            c2 = (cw ** 2 + ch ** 2) ** alpha + eps  # convex diagonal squared
            rho2 = (((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4) ** alpha  # 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_ciou = v / (v - iou + (1 + eps))
                if Focal:
                    return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, alpha)), torch.pow(inter/(union + eps), gamma)  # Focal_CIoU
                else:
                    return iou - (rho2 / c2 + torch.pow(v * alpha_ciou + eps, 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 = torch.pow(cw ** 2 + eps, alpha)
                ch2 = torch.pow(ch ** 2 + eps, alpha)
                if Focal:
                    return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2), torch.pow(inter/(union + eps), gamma) # Focal_EIou
                else:
                    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)
                if Focal:
                    return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha), torch.pow(inter/(union + eps), gamma) # Focal_SIou
                else:
                    return iou - torch.pow(0.5 * (distance_cost + shape_cost) + eps, alpha) # SIou
            elif WIoU:
                if Focal:
                    raise RuntimeError("WIoU do not support Focal.")
                elif scale:
                    return getattr(WIoU_Scale, '_scaled_loss')(self), (1 - iou) * torch.exp((rho2 / c2)), iou # WIoU https://arxiv.org/abs/2301.10051
                else:
                    return iou, torch.exp((rho2 / c2)) # WIoU v1
            if Focal:
                return iou - rho2 / c2, torch.pow(inter/(union + eps), gamma)  # Focal_DIoU
            else:
                return iou - rho2 / c2  # DIoU
        c_area = cw * ch + eps  # convex area
        if Focal:
            return iou - torch.pow((c_area - union) / c_area + eps, alpha), torch.pow(inter/(union + eps), gamma)  # Focal_GIoU https://arxiv.org/pdf/1902.09630.pdf
        else:
            return iou - torch.pow((c_area - union) / c_area + eps, alpha)  # GIoU https://arxiv.org/pdf/1902.09630.pdf
    if Focal:
        return iou, torch.pow(inter/(union + eps), gamma)  # Focal_IoU
    else:
        return iou  # IoU

 除了以上这个函数替换,还需要在ultralytics/yolo/utils/loss.py中BboxLoss Class中的forward函数中修改一下:

iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, EIoU=True, Focal=True)

 3.替换WIOU

        # # WIoU
        iou = bbox_iou_for_nms(pred_bboxes[fg_mask], target_bboxes[fg_mask], xywh=False, WIoU=True,scale=True)
        if type(iou) is tuple:
            if len(iou) == 2:
                loss_iou = ((1.0 - iou[0]) * iou[1].detach() * weight).sum() / target_scores_sum
            else:
                loss_iou = (iou[0] * iou[1] * weight).sum() / target_scores_sum
        else:
            loss_iou = ((1.0 - iou) * weight).sum() / target_scores_sum

你可能感兴趣的:(yolov8改进,YOLO,目标检测,计算机视觉)