学习资源站

YOLOv11改进-损失函数改进篇-MPDIoU,InnerMPDIoU助力细节涨点(二次创新加代码解析)

一、本文介绍

本文为读者详细介绍了YOLOv11 模型 的最新改进,带来的改进机制是最新的损失函数 MPDIoU 和融合了 最新的Inner思想的InnerMPDIoU (效果打爆之前的所有的损失函数 ) 提升检测精度和处理细节方面的作用。通过深入探讨MPDIoU和InnerMPDIoU(全网首发)的工作原理和实际代码实现,本文旨在指导读者如何将这些先进的 损失函数 技术应用到YOLOv11模型中,以提高其性能和准确性。文章内容涵盖从理论基础、代码实现,到 实际教你如何添加本文的机制到你的模型中

分析下这个结果图片: 最左面的是基础版本没做任何修改的,中间的只是修改了MPDIoU可以看到涨点相对于基础版本的大概有0.05个点左右,但是我增加了InnerMPDIoU的效果基本持平(我个人觉得是我的 数据集 原因)所以大家自己进行实验的时候可以多做一轮进行一下对比。



二、MPDIoU的机制原理

论文地址: 官方论文地址点击即可跳转

代码地址: 官方并没有开源的该损失的函数的代码,我根据文章内容进行了复现代码块在第三章

问题提出 文章指出,在 目标检测 和实例分割的过程中,传统的边界框回归(BBR)损失函数难以优化预测框和真实框在宽高比相同但具体尺寸不同时的情况, 下面是描述现有的边界框回归的方法 的计算因素总结(包括GIoU、DIoU、CIoU和EIoU)的计算因素。这些度量方法是用于评估和优化边界框回归模型 性能 的关键工具。虽然文章没有直接展示下图的内容,但它们包括以下几个方面:

  • GIoU(Generalized IoU) :除了传统的IoU(交并比)之外,GIoU还考虑了边界框之间的包含关系和空间分布。

  • DIoU(Distance IoU) :在IoU的基础上,DIoU还考虑了边界框中心点之间的距离,以改进对齐和尺度不一致的情况。

  • CIoU(Complete IoU) :结合了DIoU的特点,并加入了宽高比的考虑,进一步提高了对边界框的精确度。

  • EIoU(Expected IoU) :这是一种更高级的度量方法,考虑了预测边界框与真实边界框之间的预期相似度。

文章提出的MPDIoU是在这些现有度量方法的基础上发展起来的 旨在通过直接最小化预测框和真实框之间的关键点距离,提供一种易于实现的解决方案,用于计算两个轴对齐矩形之间的MPDIoU​

MPDIoU的提出 为了克服这一挑战,文章提出了一种新的边界框相似度度量方法——MPDIoU(Minimum Point Distance Intersection over Union)。MPDIoU是基于水平矩形的最小点距离来计算的,能够综合考虑重叠区域、中心点距离以及宽度和高度的偏差。

下图展示了两种不同的边界框回归结果情况。其中, 绿色框代表真实的边界框 而红色框代表预测的边界框 。在这两种情况下,传统的损失函数(如GIoU、DIoU、CIoU和EIoU)计算出的损失值是相同的,但是使用MPDIoU方法计算出的损失值却有所不同。这说明传统方法在某些特定情况下可能无法区分不同的预测结果,而MPDIoU能更准确地反映预测框和真实框之间的差异。

这个发现突显了MPDIoU在处理边界框回归问题上的优势,尤其是在区分具有相同宽高比但不同尺寸或位置的边界框时。MPDIoU通过直接计算预测框和真实框之间的关键点距离,提供了更精确的损失度量方法。

LMPDIoU损失函数 :基于MPDIoU的概念,文章定义了一种新的损失函数LMPDIoU。LMPDIoU的公式如下:

LMPDIoU=1-MPDIoU

这一公式表明LMPDIoU损失函数与MPDIoU的相似度成反比关系,即MPDIoU越高,LMPDIoU损失越低,这推动模型预测的边界框更加接近真实框。

公式推理 在下图展示了作者提出的LMPDIoU损失函数的各种因素。

这些因素包括如何在训练阶段通过最小化损失函数来使模型预测的边界框接近其真实边界框。具体来说,每个预测的边界框

B_{prd} = \left[ \begin{array}{c} x_{prd} \\ y_{prd} \\ w_{prd} \\ h_{prd} \end{array} \right]

通过最小化以下损失函数来逼近其真实边界框:

B_{gt} = [x_{gt}, y_{gt}, w_{gt}, h_{gt}]^T

L = \min_{\Theta} L(B_{gt}, B_{prd} | \Theta)

其中, B_{gt} ​ 是真实边界框的集合,而 \Theta ​ 是回归深度模型的参数。文章中提出的 LMPDIoU ​损失函数公式为:

LMPDIoU=1-MPDIoU

实验验证 :通过在多个数据集(如PASCAL VOC、MS COCO和IIIT5k)上对YOLACT和YOLOv7等模型的训练和测试,文章验证了MPDIoU和LMPDIoU在实际应用中的有效性。实验结果显示,这种新的损失函数在多个方面优于传统的损失函数,尤其是在处理具有相似宽高比但不同尺寸的边界框时。

下面是一些检测效果对比图

总结来说,文章通过引入MPDIoU和LMPDIoU ( 我又将其和Inner的思想结合了在一起形成了InnerMPDIoU双重提高了效果 ) ,提供了一种新的视角来优化目标检测中的边界框回归问题,同时通过实验验证了其在提高检测模型准确性方面的有效性。


三、MPDIoU的代码复现

论文中不仅提出了MPDIoU还提出了一个LMPDIoU但是这个LMPDIoU我用了以后模型根本收敛不了,所以我不知道这是我数据集的原因还是其它原因导致的,但是MPDIoU我使用效果是非常好的,其中我还添加了Focus和Inner的思想, 如果你Inner和MPDIoU都设置为True使用的就是InnerMPDIoU,如果Inner为False但是MPDIoU设置为True就是MPDIoU,Focus同理,支持FocusInnerMPDIoU,所以大家可以多进行尝试。

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


四、手把手教你添加MPDIoU到你的模型中

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=False, EIoU=False, SIoU=False, WIoU=False,
  3. ShapeIoU=False, hw=hw[fg_mask], mpdiou=False, Inner=False, Focaleriou=True,
  4. d=0.00, u=0.95, ratio=0.75, eps=1e-7, scale=0.0)

上面的代码我来解释一下,我把所有的能选用的参数都写了出来,其中IoU很好理解了,对应的参数设置为True就是使用的对应的IoU包括本文的MPDIoU,需要注意的是Inner这个参数,比如我Inner设置为True然后MPDIoU也设置为True那么此时使用的就是Inner_MPDIoU,其它的同理。

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


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分,后期我会根据各种最新的前沿顶会进行论文复现,也会对一些老的改进机制进行补充,如果大家觉得本文帮助到你了,订阅本专栏,关注后续更多的更新~