学习资源站

YOLOv11改进-损失函数改进篇-最新ShapeIoU,InnerShapeIoU损失助力细节涨点(含三十余种损失函数改进方法)

一、本文介绍

本文给大家带来的改进机制是 损失函数 的改进机制标题虽然提到了 ShapeIoU和InnnerShapeIoU 但是本文的内容包括过去到现在的百分之九十以上的损失函数的实现,同时使用方法非常简单,在本文的末尾还会教大家在改进 模型 何时添加损失函数才能达到最好的效果 ,同时在开始讲解之前推荐一下我的专栏,本专栏的内容支持(分类、检测、分割、追踪、 关键点检测 ),专栏目前为 限时折扣 欢迎大家订阅本专栏,本专栏每周更新3-5篇最新机制,更有包含我所有改进的文件和交流群提供给大家,本文支持的损失函数共有如下图片所示

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



二、ShapeIoU

官方论文地址: 官方论文地址

官方代码地址: 官方代码地址


这幅图展示了在 目标检测 任务中,两种不同情况或方法下的边界框回归的对比。

GT (Ground Truth): 用桃色框表示,指的是图像中物体实际的位置和形状。在目标检测中,算法试图尽可能准确地预测这个框。

Anchor: 蓝色框代表一个预定义的框,是算法预设的一系列框,用于与GT框进行匹配,寻找最佳的候选框。

在图中,我们看到四个不同的情况(A、B、C、D),每个都显示了一个anchor与GT的对比,并给出了IoU(交并比)的数值。IoU是一个常用的度量,用来评估预测边界框与真实边界框之间的重叠程度。

论文中给了一堆公式,大家有兴趣的可以看看。


三、核心代码

下面的代码的使用方式看章节四。

  1. import numpy as np
  2. import torch
  3. import math
  4. from ultralytics.utils import ops
  5. class WIoU_Scale:
  6. ''' monotonous: {
  7. None: origin v1
  8. True: monotonic FM v2
  9. False: non-monotonic FM v3
  10. }
  11. momentum: The momentum of running mean'''
  12. iou_mean = 1.
  13. monotonous = False
  14. _momentum = 1 - 0.5 ** (1 / 7000)
  15. _is_train = True
  16. def __init__(self, iou):
  17. self.iou = iou
  18. self._update(self)
  19. @classmethod
  20. def _update(cls, self):
  21. if cls._is_train: cls.iou_mean = (1 - cls._momentum) * cls.iou_mean + \
  22. cls._momentum * self.iou.detach().mean().item()
  23. @classmethod
  24. def _scaled_loss(cls, self, gamma=1.9, delta=3):
  25. if isinstance(self.monotonous, bool):
  26. if self.monotonous:
  27. return (self.iou.detach() / self.iou_mean).sqrt()
  28. else:
  29. beta = self.iou.detach() / self.iou_mean
  30. alpha = delta * torch.pow(gamma, beta - delta)
  31. return beta / alpha
  32. return 1
  33. def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, EIoU=False, SIoU=False, WIoU=False, ShapeIoU=False,
  34. hw=1, mpdiou=False, Inner=False, alpha=1, ratio=0.7, eps=1e-7, scale=0.0):
  35. """
  36. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  37. Args:
  38. box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).
  39. box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).
  40. xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in
  41. (x1, y1, x2, y2) format. Defaults to True.
  42. GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.
  43. DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.
  44. CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.
  45. EIoU (bool, optional): If True, calculate Efficient IoU. Defaults to False.
  46. SIoU (bool, optional): If True, calculate Scylla IoU. Defaults to False.
  47. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  48. Returns:
  49. (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
  50. """
  51. if Inner:
  52. if not xywh:
  53. box1, box2 = ops.xyxy2xywh(box1), ops.xyxy2xywh(box2)
  54. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  55. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - (w1 * ratio) / 2, x1 + (w1 * ratio) / 2, y1 - (h1 * ratio) / 2, y1 + (
  56. h1 * ratio) / 2
  57. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - (w2 * ratio) / 2, x2 + (w2 * ratio) / 2, y2 - (h2 * ratio) / 2, y2 + (
  58. h2 * ratio) / 2
  59. # Intersection area
  60. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  61. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  62. # Union Area
  63. union = w1 * h1 * ratio * ratio + w2 * h2 * ratio * ratio - inter + eps
  64. iou = inter / union
  65. # Get the coordinates of bounding boxes
  66. else:
  67. if xywh: # transform from xywh to xyxy
  68. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  69. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  70. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  71. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  72. else: # x1, y1, x2, y2 = box1
  73. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  74. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  75. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  76. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  77. # Intersection area
  78. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  79. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  80. # Union Area
  81. union = w1 * h1 + w2 * h2 - inter + eps
  82. # IoU
  83. iou = inter / union
  84. if CIoU or DIoU or GIoU or EIoU or SIoU or ShapeIoU or mpdiou or WIoU:
  85. cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
  86. ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
  87. if CIoU or DIoU or EIoU or SIoU or mpdiou or WIoU or ShapeIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  88. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  89. rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
  90. if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  91. v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
  92. with torch.no_grad():
  93. alpha = v / (v - iou + (1 + eps))
  94. return iou - (rho2 / c2 + v * alpha) # CIoU
  95. elif EIoU:
  96. rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
  97. rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
  98. cw2 = cw ** 2 + eps
  99. ch2 = ch ** 2 + eps
  100. return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2) # EIoU
  101. elif SIoU:
  102. # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
  103. s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
  104. s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
  105. sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
  106. sin_alpha_1 = torch.abs(s_cw) / sigma
  107. sin_alpha_2 = torch.abs(s_ch) / sigma
  108. threshold = pow(2, 0.5) / 2
  109. sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
  110. angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
  111. rho_x = (s_cw / cw) ** 2
  112. rho_y = (s_ch / ch) ** 2
  113. gamma = angle_cost - 2
  114. distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
  115. omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
  116. omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
  117. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  118. return iou - 0.5 * (distance_cost + shape_cost) + eps # SIoU
  119. elif ShapeIoU:
  120. #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance
  121. ww = 2 * torch.pow(w2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  122. hh = 2 * torch.pow(h2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  123. cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex width
  124. ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
  125. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  126. center_distance_x = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2) / 4
  127. center_distance_y = ((b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
  128. center_distance = hh * center_distance_x + ww * center_distance_y
  129. distance = center_distance / c2
  130. #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape
  131. omiga_w = hh * torch.abs(w1 - w2) / torch.max(w1, w2)
  132. omiga_h = ww * torch.abs(h1 - h2) / torch.max(h1, h2)
  133. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  134. return iou - distance - 0.5 * shape_cost
  135. elif mpdiou:
  136. d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
  137. d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
  138. return iou - d1 / hw.unsqueeze(1) - d2 / hw.unsqueeze(1) # MPDIoU
  139. elif WIoU:
  140. self = WIoU_Scale(1 - iou)
  141. dist = getattr(WIoU_Scale, '_scaled_loss')(self)
  142. return iou * dist # WIoU https://arxiv.org/abs/2301.10051
  143. return iou - rho2 / c2 # DIoU
  144. c_area = cw * ch + eps # convex area
  145. return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
  146. return iou # IoU


四、 损失函数使用方式

4.1 步骤一

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


4.2 步骤二

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

  1. iou = bbox_iou(pred_bboxes[fg_mask], target_bboxes[fg_mask],
  2. xywh=False, GIoU=False, DIoU=False, CIoU=True, EIoU=False, SIoU=False,
  3. WIoU=False, ShapeIoU=False, hw=hw[fg_mask], mpdiou=False, Inner=False,
  4. ratio=0.75, eps=1e-7, scale=0.0)

上面的代码我来解释一下,我把所有的能选用的参数都写了出来,其中IoU很好理解了,对应的参数设置为True就是使用的对应的IoU包括本文的ShapeIoU,需要注意的是Inner这个参数,比如我Inner设置为True然后Shape_IoU也设置为True那么此时使用的就是Inner_Shape_IoU,其它的都是,其中ratio和eps是inner的参数大家可以自己尝试我这里定义了两个基本值。

替换完后的样子如下->


4.3 步骤三

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

用我给的代码替换

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

下面的样子是替换完的。


4.4 步骤四

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

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

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

替换完之后的样子->


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

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


五、本文总结

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