赞
踩
目录
一 回归损失函数(Bounding Box Regression Loss)
① ultralytics/utils/metrics.py文件
官方论文地址:官方论文地址 点击即可跳转
官方代码地址:官方代码地址 点击即可跳转
论文中分析了边界框的回归过程,指出了IoU损失的局限性,它对不同的检测任务没有很强的泛化能力。基于边界框回归问题的固有特点,提出了一种基于辅助边界框的边界框回归损失Inner-IoU。通过比例因子比率(scale factor ratio)控制辅助边界框的生成,计算损失,加速训练的收敛。它可以集成到现有的基于IoU的损失函数中。通过一系列的模拟和烧蚀消融实验验证,该方法优于现有方法。本文提出的方法不仅适用于一般的检测任务,而且对于非常小目标的检测任务也表现良好,证实了该方法的泛化性。
官方的代码给出了2种结合方式,文件如下图:
Inner-IoU的描述见下图:
Inner-IoU的实验效果
CIoU 方法, Inner-CIoU (ratio=0.7), Inner-CIoU (ratio=0.75) and Inner-CIoU (ratio=0.8)的检测效果如下图所示:
SIoU 方法, Inner-SIoU (ratio=0.7), Inner-SIoU (ratio=0.75) and Inner-SIoU (ratio=0.8)的检测效果如下图所示:
官方论文地址:官方论文地址 点击即可跳转
官方代码地址:官方代码地址 点击即可跳转
论文中分析了难易样本的分布对目标检测的影响。当困难样品占主导地位时,需要关注困难样品以提高检测性能。当简单样本的比例较大时,则相反。论文中提出了Focaler-IoU方法,通过线性区间映射重建原始IoU损失,达到聚焦难易样本的目的。最后通过对比实验证明,该方法能够有效提高检测性能。
为了在不同的回归样本中关注不同的检测任务,使用线性间隔映射方法重构IoU损失,这有助于提高边缘回归。具体的公式如下所示:
将Focaler-IoU应用于现有的基于IoU的边界框回归损失函数中,如下所示:
实验结果如下:
GIoU、DIoU、CIoU、EIoU和MPDIou等的概述见使用MPDIou回归损失函数帮助YOLOv9模型更优秀 点击此处即可跳转
首先,我们现将后续会使用到的损失函数集成到项目中。
在utils/metrics.py文件中,使用下述代码(替换后的部分)替换掉bbox_iou()函数,即将被替换的bbox_iou()函数如下图所示:
使用下述的替换代码替换掉下述原始代码。
- # before
- def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
- """
- 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.
- 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.
- """
-
- # 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 + 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 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.pow(2) + ch.pow(2) + eps # convex diagonal squared
- rho2 = (
- (b2_x1 + b2_x2 - b1_x1 - b1_x2).pow(2) + (b2_y1 + b2_y2 - b1_y1 - b1_y2).pow(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) * ((w2 / h2).atan() - (w1 / h1).atan()).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
- # after
- class WIoU_Scale:
- ''' monotonous: {
- None: origin v1
- True: monotonic FM v2
- False: non-monotonic FM v3
- }
- '''
- 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, ratio=1, GIoU=False, DIoU=False, CIoU=False,
- SIoU=False, EIoU=False, WIoU=False, MPDIoU=False, LMPDIoU=False,
- Inner=False, Focal=False, alpha=1, gamma=0.5, scale=False, eps=1e-7):
- # 计算box1与box2之间的Intersection over Union(IoU)
- # 获取bounding box的坐标
- if Inner:
- (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_ * ratio, x1 + w1_ * ratio, \
- y1 - h1_ * ratio, y1 + h1_ * ratio
- b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_ * ratio, x2 + w2_ * ratio, \
- y2 - h2_ * ratio, y2 + h2_ * ratio
- # 计算交集面积
- inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
- (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
- # 计算并集面积
- union = w1 * ratio * h1 * ratio + w2 * ratio * h2 * ratio - inter + eps
-
- iou = inter / union # inner_iou
-
- else:
- # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
- if xywh: # xywh转换为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
-
- # 计算交集面积
- 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 = w1 * h1 + w2 * h2 - inter + eps
-
- # 计算IoU值
- iou = inter / union
-
- if CIoU or DIoU or GIoU or EIoU or SIoU or WIoU or MPDIoU or LMPDIoU:
- cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # 计算最小外接矩形的宽度
- ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # 计算最小外接矩形的高度
- if CIoU or DIoU or EIoU or SIoU or WIoU or MPDIoU or LMPDIoU: # Distance or Complete IoU
- 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 # 中心点距离的平方
- if CIoU:
- 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 MPDIoU:
- d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
- d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
- w = (b2_x2 - b2_x1) # x2 - x1
- h = (b2_y2 - b2_y1) # y2 - y1
- if Focal:
- return iou - ((d1 + d2) / (w ** 2 + h ** 2)), torch.pow(inter / (union + eps), gamma)# Focal_MPDIoU
- else:
- return iou - (d1 + d2) / (w ** 2 + h ** 2)
- elif LMPDIoU:
- d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
- d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
- w = (b2_x2 - b2_x1) # x2 - x1
- h = (b2_y2 - b2_y1) # y2 - y1
- if Focal:
- return 1 - (iou - (d1 + d2) / (w ** 2 + h ** 2)), torch.pow(inter / (union + eps), gamma)# Focal_MPDIo # MPDIoU
- else:
- return 1 - iou + d1 / (w ** 2 + h ** 2) + d2 / (w ** 2 + h ** 2)
- 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
- 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:
- self = WIoU_Scale(1 - (inter / union))
- dist = getattr(WIoU_Scale, '_scaled_loss')(self)
- return iou * dist # WIoU
-
- 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
- else:
- return iou - torch.pow((c_area - union) / c_area + eps, alpha) # GIoU
- if Focal:
- return iou, torch.pow(inter / (union + eps), gamma) # Focal_IoU
- else:
- return iou # IoU的值
接下来,需要修改loss.py文件中的内容。
before |
after |
before |
after |
与上述内容类比,如果将对应机制设置为True则开启,否则关闭。之后,可以尝试多种组合方式去训练模型。
那么。接下来开始训练模型吧!!!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。