metrics.py 85 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. """Model validation metrics."""
  3. import math
  4. import warnings
  5. from pathlib import Path
  6. import matplotlib.pyplot as plt
  7. import numpy as np
  8. import torch
  9. from ultralytics.utils import LOGGER, SimpleClass, TryExcept, plt_settings
  10. from ultralytics.trainsdk import TrainSdk
  11. OKS_SIGMA = (
  12. np.array([0.26, 0.25, 0.25, 0.35, 0.35, 0.79, 0.79, 0.72, 0.72, 0.62, 0.62, 1.07, 1.07, 0.87, 0.87, 0.89, 0.89])
  13. / 10.0
  14. )
  15. def bbox_ioa(box1, box2, iou=False, eps=1e-7):
  16. """
  17. Calculate the intersection over box2 area given box1 and box2. Boxes are in x1y1x2y2 format.
  18. Args:
  19. box1 (np.ndarray): A numpy array of shape (n, 4) representing n bounding boxes.
  20. box2 (np.ndarray): A numpy array of shape (m, 4) representing m bounding boxes.
  21. iou (bool): Calculate the standard IoU if True else return inter_area/box2_area.
  22. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  23. Returns:
  24. (np.ndarray): A numpy array of shape (n, m) representing the intersection over box2 area.
  25. """
  26. # Get the coordinates of bounding boxes
  27. b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
  28. b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
  29. # Intersection area
  30. inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * (
  31. np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)
  32. ).clip(0)
  33. # Box2 area
  34. area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
  35. if iou:
  36. box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
  37. area = area + box1_area[:, None] - inter_area
  38. # Intersection over box2 area
  39. return inter_area / (area + eps)
  40. def box_iou(box1, box2, eps=1e-7):
  41. """
  42. Calculate intersection-over-union (IoU) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
  43. Based on https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
  44. Args:
  45. box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes.
  46. box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes.
  47. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  48. Returns:
  49. (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.
  50. """
  51. # NOTE: Need .float() to get accurate iou values
  52. # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
  53. (a1, a2), (b1, b2) = box1.float().unsqueeze(1).chunk(2, 2), box2.float().unsqueeze(0).chunk(2, 2)
  54. inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp_(0).prod(2)
  55. # IoU = inter / (area1 + area2 - inter)
  56. return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
  57. def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, EIoU=False, SIoU=False, ShapeIoU=False, PIoU=False, PIoU2=False, eps=1e-7, scale=0.0, Lambda=1.3):
  58. """
  59. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  60. Args:
  61. box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).
  62. box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).
  63. xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in
  64. (x1, y1, x2, y2) format. Defaults to True.
  65. GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.
  66. DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.
  67. CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.
  68. EIoU (bool, optional): If True, calculate Efficient IoU. Defaults to False.
  69. SIoU (bool, optional): If True, calculate Scylla IoU. Defaults to False.
  70. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  71. Returns:
  72. (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
  73. """
  74. # Get the coordinates of bounding boxes
  75. if xywh: # transform from xywh to xyxy
  76. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  77. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  78. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  79. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  80. else: # x1, y1, x2, y2 = box1
  81. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  82. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  83. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  84. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  85. # Intersection area
  86. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  87. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  88. # Union Area
  89. union = w1 * h1 + w2 * h2 - inter + eps
  90. # IoU
  91. iou = inter / union
  92. if CIoU or DIoU or GIoU or EIoU or SIoU or ShapeIoU or PIoU or PIoU2:
  93. cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
  94. ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
  95. if CIoU or DIoU or EIoU or SIoU or PIoU or PIoU2 or ShapeIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  96. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  97. rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
  98. if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  99. v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
  100. with torch.no_grad():
  101. alpha = v / (v - iou + (1 + eps))
  102. return iou - (rho2 / c2 + v * alpha) # CIoU
  103. elif EIoU:
  104. rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
  105. rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
  106. cw2 = cw ** 2 + eps
  107. ch2 = ch ** 2 + eps
  108. return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2) # EIoU
  109. elif SIoU:
  110. # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
  111. s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
  112. s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
  113. sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
  114. sin_alpha_1 = torch.abs(s_cw) / sigma
  115. sin_alpha_2 = torch.abs(s_ch) / sigma
  116. threshold = pow(2, 0.5) / 2
  117. sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
  118. angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
  119. rho_x = (s_cw / cw) ** 2
  120. rho_y = (s_ch / ch) ** 2
  121. gamma = angle_cost - 2
  122. distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
  123. omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
  124. omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
  125. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  126. return iou - 0.5 * (distance_cost + shape_cost) + eps # SIoU
  127. elif ShapeIoU:
  128. #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance
  129. ww = 2 * torch.pow(w2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  130. hh = 2 * torch.pow(h2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  131. cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex width
  132. ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
  133. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  134. center_distance_x = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2) / 4
  135. center_distance_y = ((b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
  136. center_distance = hh * center_distance_x + ww * center_distance_y
  137. distance = center_distance / c2
  138. #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape
  139. omiga_w = hh * torch.abs(w1 - w2) / torch.max(w1, w2)
  140. omiga_h = ww * torch.abs(h1 - h2) / torch.max(h1, h2)
  141. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  142. return iou - distance - 0.5 * shape_cost
  143. elif PIoU or PIoU2:
  144. dw1 = torch.abs(b1_x2.minimum(b1_x1)-b2_x2.minimum(b2_x1))
  145. dw2 = torch.abs(b1_x2.maximum(b1_x1)-b2_x2.maximum(b2_x1))
  146. dh1 = torch.abs(b1_y2.minimum(b1_y1)-b2_y2.minimum(b2_y1))
  147. dh2 = torch.abs(b1_y2.maximum(b1_y1)-b2_y2.maximum(b2_y1))
  148. P = ((dw1+dw2)/torch.abs(w2)+(dh1+dh2)/torch.abs(h2))/4
  149. piou_v1 = 1 - iou - torch.exp(-P**2) + 1
  150. if PIoU:
  151. return 1 - piou_v1
  152. elif PIoU2:
  153. q=torch.exp(-P)
  154. x=q*Lambda
  155. return 1 - 3*x*torch.exp(-x**2)*piou_v1
  156. return iou - rho2 / c2 # DIoU
  157. c_area = cw * ch + eps # convex area
  158. return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
  159. return iou # IoU
  160. def get_inner_iou(box1, box2, xywh=True, eps=1e-7, ratio=0.7):
  161. def xyxy2xywh(x):
  162. """
  163. Convert bounding box coordinates from (x1, y1, x2, y2) format to (x, y, width, height) format where (x1, y1) is the
  164. top-left corner and (x2, y2) is the bottom-right corner.
  165. Args:
  166. x (np.ndarray | torch.Tensor): The input bounding box coordinates in (x1, y1, x2, y2) format.
  167. Returns:
  168. y (np.ndarray | torch.Tensor): The bounding box coordinates in (x, y, width, height) format.
  169. """
  170. assert x.shape[-1] == 4, f"input shape last dimension expected 4 but input shape is {x.shape}"
  171. y = torch.empty_like(x) if isinstance(x, torch.Tensor) else np.empty_like(x) # faster than clone/copy
  172. y[..., 0] = (x[..., 0] + x[..., 2]) / 2 # x center
  173. y[..., 1] = (x[..., 1] + x[..., 3]) / 2 # y center
  174. y[..., 2] = x[..., 2] - x[..., 0] # width
  175. y[..., 3] = x[..., 3] - x[..., 1] # height
  176. return y
  177. if not xywh:
  178. box1, box2 = xyxy2xywh(box1), xyxy2xywh(box2)
  179. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  180. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - (w1 * ratio) / 2, x1 + (w1 * ratio) / 2, y1 - (h1 * ratio) / 2, y1 + (h1 * ratio) / 2
  181. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - (w2 * ratio) / 2, x2 + (w2 * ratio) / 2, y2 - (h2 * ratio) / 2, y2 + (h2 * ratio) / 2
  182. # Intersection area
  183. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  184. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  185. # Union Area
  186. union = w1 * h1 * ratio * ratio + w2 * h2 * ratio * ratio - inter + eps
  187. return inter / union
  188. def bbox_inner_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, EIoU=False, SIoU=False, ShapeIoU=False, PIoU=False, PIoU2=False, eps=1e-7, ratio=0.7, scale=0.0, Lambda=1.3):
  189. """
  190. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  191. Args:
  192. box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).
  193. box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).
  194. xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in
  195. (x1, y1, x2, y2) format. Defaults to True.
  196. GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.
  197. DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.
  198. CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.
  199. EIoU (bool, optional): If True, calculate Efficient IoU. Defaults to False.
  200. SIoU (bool, optional): If True, calculate Scylla IoU. Defaults to False.
  201. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  202. Returns:
  203. (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
  204. """
  205. # Get the coordinates of bounding boxes
  206. if xywh: # transform from xywh to xyxy
  207. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  208. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  209. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  210. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  211. else: # x1, y1, x2, y2 = box1
  212. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  213. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  214. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  215. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  216. innner_iou = get_inner_iou(box1, box2, xywh=xywh, ratio=ratio)
  217. # Intersection area
  218. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  219. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  220. # Union Area
  221. union = w1 * h1 + w2 * h2 - inter + eps
  222. # IoU
  223. iou = inter / union
  224. if CIoU or DIoU or GIoU or EIoU or SIoU or ShapeIoU or PIoU or PIoU2:
  225. cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
  226. ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
  227. if CIoU or DIoU or EIoU or SIoU or PIoU or PIoU2 or ShapeIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  228. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  229. rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
  230. if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  231. v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
  232. with torch.no_grad():
  233. alpha = v / (v - iou + (1 + eps))
  234. return innner_iou - (rho2 / c2 + v * alpha) # CIoU
  235. elif EIoU:
  236. rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
  237. rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
  238. cw2 = cw ** 2 + eps
  239. ch2 = ch ** 2 + eps
  240. return innner_iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2) # EIoU
  241. elif SIoU:
  242. # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
  243. s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
  244. s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
  245. sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
  246. sin_alpha_1 = torch.abs(s_cw) / sigma
  247. sin_alpha_2 = torch.abs(s_ch) / sigma
  248. threshold = pow(2, 0.5) / 2
  249. sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
  250. angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
  251. rho_x = (s_cw / cw) ** 2
  252. rho_y = (s_ch / ch) ** 2
  253. gamma = angle_cost - 2
  254. distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
  255. omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
  256. omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
  257. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  258. return innner_iou - 0.5 * (distance_cost + shape_cost) + eps # SIoU
  259. elif ShapeIoU:
  260. #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance
  261. ww = 2 * torch.pow(w2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  262. hh = 2 * torch.pow(h2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  263. cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex width
  264. ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
  265. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  266. center_distance_x = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2) / 4
  267. center_distance_y = ((b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
  268. center_distance = hh * center_distance_x + ww * center_distance_y
  269. distance = center_distance / c2
  270. #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape
  271. omiga_w = hh * torch.abs(w1 - w2) / torch.max(w1, w2)
  272. omiga_h = ww * torch.abs(h1 - h2) / torch.max(h1, h2)
  273. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  274. return innner_iou - distance - 0.5 * shape_cost
  275. elif PIoU or PIoU2:
  276. dw1 = torch.abs(b1_x2.minimum(b1_x1)-b2_x2.minimum(b2_x1))
  277. dw2 = torch.abs(b1_x2.maximum(b1_x1)-b2_x2.maximum(b2_x1))
  278. dh1 = torch.abs(b1_y2.minimum(b1_y1)-b2_y2.minimum(b2_y1))
  279. dh2 = torch.abs(b1_y2.maximum(b1_y1)-b2_y2.maximum(b2_y1))
  280. P = ((dw1+dw2)/torch.abs(w2)+(dh1+dh2)/torch.abs(h2))/4
  281. piou_v1 = 1 - innner_iou - torch.exp(-P**2) + 1
  282. if PIoU:
  283. return 1 - piou_v1
  284. elif PIoU2:
  285. q=torch.exp(-P)
  286. x=q*Lambda
  287. return 1 - 3*x*torch.exp(-x**2)*piou_v1
  288. return innner_iou - rho2 / c2 # DIoU
  289. c_area = cw * ch + eps # convex area
  290. return innner_iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
  291. return innner_iou # IoU
  292. def bbox_focaler_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, EIoU=False, SIoU=False, ShapeIoU=False, PIoU=False, PIoU2=False, eps=1e-7, scale=0.0, d=0.0, u=0.95, Lambda=1.3):
  293. """
  294. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  295. Args:
  296. box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).
  297. box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).
  298. xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in
  299. (x1, y1, x2, y2) format. Defaults to True.
  300. GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.
  301. DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.
  302. CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.
  303. EIoU (bool, optional): If True, calculate Efficient IoU. Defaults to False.
  304. SIoU (bool, optional): If True, calculate Scylla IoU. Defaults to False.
  305. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  306. Returns:
  307. (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
  308. """
  309. # Get the coordinates of bounding boxes
  310. if xywh: # transform from xywh to xyxy
  311. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  312. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  313. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  314. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  315. else: # x1, y1, x2, y2 = box1
  316. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  317. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  318. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  319. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  320. # Intersection area
  321. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  322. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  323. # Union Area
  324. union = w1 * h1 + w2 * h2 - inter + eps
  325. # IoU
  326. iou = inter / union
  327. # Focaler-IoU
  328. iou = ((iou - d) / (u - d)).clamp(0, 1) # default d=0.00, u=0.95
  329. if CIoU or DIoU or GIoU or EIoU or SIoU or ShapeIoU or PIoU or PIoU2:
  330. cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
  331. ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
  332. if CIoU or DIoU or EIoU or SIoU or PIoU or PIoU2 or ShapeIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  333. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  334. rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
  335. if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  336. v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
  337. with torch.no_grad():
  338. alpha = v / (v - iou + (1 + eps))
  339. return iou - (rho2 / c2 + v * alpha) # CIoU
  340. elif EIoU:
  341. rho_w2 = ((b2_x2 - b2_x1) - (b1_x2 - b1_x1)) ** 2
  342. rho_h2 = ((b2_y2 - b2_y1) - (b1_y2 - b1_y1)) ** 2
  343. cw2 = cw ** 2 + eps
  344. ch2 = ch ** 2 + eps
  345. return iou - (rho2 / c2 + rho_w2 / cw2 + rho_h2 / ch2) # EIoU
  346. elif SIoU:
  347. # SIoU Loss https://arxiv.org/pdf/2205.12740.pdf
  348. s_cw = (b2_x1 + b2_x2 - b1_x1 - b1_x2) * 0.5 + eps
  349. s_ch = (b2_y1 + b2_y2 - b1_y1 - b1_y2) * 0.5 + eps
  350. sigma = torch.pow(s_cw ** 2 + s_ch ** 2, 0.5)
  351. sin_alpha_1 = torch.abs(s_cw) / sigma
  352. sin_alpha_2 = torch.abs(s_ch) / sigma
  353. threshold = pow(2, 0.5) / 2
  354. sin_alpha = torch.where(sin_alpha_1 > threshold, sin_alpha_2, sin_alpha_1)
  355. angle_cost = torch.cos(torch.arcsin(sin_alpha) * 2 - math.pi / 2)
  356. rho_x = (s_cw / cw) ** 2
  357. rho_y = (s_ch / ch) ** 2
  358. gamma = angle_cost - 2
  359. distance_cost = 2 - torch.exp(gamma * rho_x) - torch.exp(gamma * rho_y)
  360. omiga_w = torch.abs(w1 - w2) / torch.max(w1, w2)
  361. omiga_h = torch.abs(h1 - h2) / torch.max(h1, h2)
  362. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  363. return iou - 0.5 * (distance_cost + shape_cost) + eps # SIoU
  364. elif ShapeIoU:
  365. #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance
  366. ww = 2 * torch.pow(w2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  367. hh = 2 * torch.pow(h2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  368. cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex width
  369. ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
  370. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  371. center_distance_x = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2) / 4
  372. center_distance_y = ((b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
  373. center_distance = hh * center_distance_x + ww * center_distance_y
  374. distance = center_distance / c2
  375. #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape
  376. omiga_w = hh * torch.abs(w1 - w2) / torch.max(w1, w2)
  377. omiga_h = ww * torch.abs(h1 - h2) / torch.max(h1, h2)
  378. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  379. return iou - distance - 0.5 * shape_cost
  380. elif PIoU or PIoU2:
  381. dw1 = torch.abs(b1_x2.minimum(b1_x1)-b2_x2.minimum(b2_x1))
  382. dw2 = torch.abs(b1_x2.maximum(b1_x1)-b2_x2.maximum(b2_x1))
  383. dh1 = torch.abs(b1_y2.minimum(b1_y1)-b2_y2.minimum(b2_y1))
  384. dh2 = torch.abs(b1_y2.maximum(b1_y1)-b2_y2.maximum(b2_y1))
  385. P = ((dw1+dw2)/torch.abs(w2)+(dh1+dh2)/torch.abs(h2))/4
  386. piou_v1 = 1 - iou - torch.exp(-P**2) + 1
  387. if PIoU:
  388. return 1 - piou_v1
  389. elif PIoU2:
  390. q=torch.exp(-P)
  391. x=q*Lambda
  392. return 1 - 3*x*torch.exp(-x**2)*piou_v1
  393. return iou - rho2 / c2 # DIoU
  394. c_area = cw * ch + eps # convex area
  395. return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
  396. return iou # IoU
  397. def bbox_mpdiou(box1, box2, xywh=True, mpdiou_hw=1, eps=1e-7):
  398. """
  399. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  400. """
  401. # Get the coordinates of bounding boxes
  402. if xywh: # transform from xywh to xyxy
  403. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  404. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  405. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  406. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  407. else: # x1, y1, x2, y2 = box1
  408. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  409. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  410. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  411. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  412. # Intersection area
  413. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  414. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  415. # Union Area
  416. union = w1 * h1 + w2 * h2 - inter + eps
  417. # IoU
  418. iou = inter / union
  419. d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
  420. d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
  421. return iou - d1 / mpdiou_hw.unsqueeze(1) - d2 / mpdiou_hw.unsqueeze(1) # MPDIoU
  422. def bbox_inner_mpdiou(box1, box2, xywh=True, mpdiou_hw=1, ratio=0.7, eps=1e-7):
  423. """
  424. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  425. """
  426. # Get the coordinates of bounding boxes
  427. if xywh: # transform from xywh to xyxy
  428. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  429. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  430. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  431. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  432. else: # x1, y1, x2, y2 = box1
  433. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  434. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  435. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  436. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  437. # Inner-IoU
  438. innner_iou = get_inner_iou(box1, box2, xywh=xywh, ratio=ratio)
  439. # Intersection area
  440. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  441. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  442. # Union Area
  443. union = w1 * h1 + w2 * h2 - inter + eps
  444. # IoU
  445. iou = inter / union
  446. d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
  447. d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
  448. return innner_iou - d1 / mpdiou_hw.unsqueeze(1) - d2 / mpdiou_hw.unsqueeze(1) # MPDIoU
  449. def bbox_focaler_mpdiou(box1, box2, xywh=True, mpdiou_hw=1, eps=1e-7, d=0.0, u=0.95):
  450. """
  451. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  452. """
  453. # Get the coordinates of bounding boxes
  454. if xywh: # transform from xywh to xyxy
  455. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  456. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  457. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  458. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  459. else: # x1, y1, x2, y2 = box1
  460. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  461. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  462. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  463. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  464. # Intersection area
  465. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  466. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  467. # Union Area
  468. union = w1 * h1 + w2 * h2 - inter + eps
  469. # IoU
  470. iou = inter / union
  471. # Focaler-IoU
  472. iou = ((iou - d) / (u - d)).clamp(0, 1) # default d=0.00, u=0.95
  473. d1 = (b2_x1 - b1_x1) ** 2 + (b2_y1 - b1_y1) ** 2
  474. d2 = (b2_x2 - b1_x2) ** 2 + (b2_y2 - b1_y2) ** 2
  475. return iou - d1 / mpdiou_hw.unsqueeze(1) - d2 / mpdiou_hw.unsqueeze(1) # MPDIoU
  476. def wasserstein_loss(pred, target, eps=1e-7, constant=12.8):
  477. r"""`Implementation of paper `Enhancing Geometric Factors into
  478. Model Learning and Inference for Object Detection and Instance
  479. Segmentation <https://arxiv.org/abs/2005.03572>`_.
  480. Code is modified from https://github.com/Zzh-tju/CIoU.
  481. Args:
  482. pred (Tensor): Predicted bboxes of format (x_min, y_min, x_max, y_max),
  483. shape (n, 4).
  484. target (Tensor): Corresponding gt bboxes, shape (n, 4).
  485. eps (float): Eps to avoid log(0).
  486. Return:
  487. Tensor: Loss tensor.
  488. """
  489. b1_x1, b1_y1, b1_x2, b1_y2 = pred.chunk(4, -1)
  490. b2_x1, b2_y1, b2_x2, b2_y2 = target.chunk(4, -1)
  491. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  492. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  493. b1_x_center, b1_y_center = b1_x1 + w1 / 2, b1_y1 + h1 / 2
  494. b2_x_center, b2_y_center = b2_x1 + w2 / 2, b2_y1 + h2 / 2
  495. center_distance = (b1_x_center - b2_x_center) ** 2 + (b1_y_center - b2_y_center) ** 2 + eps
  496. wh_distance = ((w1 - w2) ** 2 + (h1 - h2) ** 2) / 4
  497. wasserstein_2 = center_distance + wh_distance
  498. return torch.exp(-torch.sqrt(wasserstein_2) / constant)
  499. class WiseIouLoss(torch.nn.Module):
  500. ''' :param monotonous: {
  501. None: origin V1
  502. True: monotonic FM V2
  503. False: non-monotonic FM V3
  504. }'''
  505. momentum = 1e-2
  506. alpha = 1.7
  507. delta = 2.7
  508. def __init__(self, ltype='WIoU', monotonous=False, inner_iou=False, focaler_iou=False):
  509. super().__init__()
  510. assert getattr(self, f'_{ltype}', None), f'The loss function {ltype} does not exist'
  511. self.ltype = ltype
  512. self.monotonous = monotonous
  513. self.inner_iou = inner_iou
  514. self.focaler_iou = focaler_iou
  515. self.register_buffer('iou_mean', torch.tensor(1.))
  516. def __getitem__(self, item):
  517. if callable(self._fget[item]):
  518. self._fget[item] = self._fget[item]()
  519. return self._fget[item]
  520. def forward(self, pred, target, ret_iou=False, ratio=1.0, d=0.0, u=0.95, **kwargs):
  521. self._fget = {
  522. # pred, target: x0,y0,x1,y1
  523. 'pred': pred,
  524. 'target': target,
  525. # x,y,w,h
  526. 'pred_xy': lambda: (self['pred'][..., :2] + self['pred'][..., 2: 4]) / 2,
  527. 'pred_wh': lambda: self['pred'][..., 2: 4] - self['pred'][..., :2],
  528. 'target_xy': lambda: (self['target'][..., :2] + self['target'][..., 2: 4]) / 2,
  529. 'target_wh': lambda: self['target'][..., 2: 4] - self['target'][..., :2],
  530. # x0,y0,x1,y1
  531. 'min_coord': lambda: torch.minimum(self['pred'][..., :4], self['target'][..., :4]),
  532. 'max_coord': lambda: torch.maximum(self['pred'][..., :4], self['target'][..., :4]),
  533. # The overlapping region
  534. 'wh_inter': lambda: torch.relu(self['min_coord'][..., 2: 4] - self['max_coord'][..., :2]),
  535. 's_inter': lambda: torch.prod(self['wh_inter'], dim=-1),
  536. # The area covered
  537. 's_union': lambda: torch.prod(self['pred_wh'], dim=-1) +
  538. torch.prod(self['target_wh'], dim=-1) - self['s_inter'],
  539. # The smallest enclosing box
  540. 'wh_box': lambda: self['max_coord'][..., 2: 4] - self['min_coord'][..., :2],
  541. 's_box': lambda: torch.prod(self['wh_box'], dim=-1),
  542. 'l2_box': lambda: torch.square(self['wh_box']).sum(dim=-1),
  543. # The central points' connection of the bounding boxes
  544. 'd_center': lambda: self['pred_xy'] - self['target_xy'],
  545. 'l2_center': lambda: torch.square(self['d_center']).sum(dim=-1),
  546. # IoU / Inner-IoU / Focaler-IoU
  547. 'iou': lambda: (1 - get_inner_iou(pred, target, xywh=False, ratio=ratio).squeeze()) if self.inner_iou else (1 - ((self['s_inter'] / self['s_union'] - d) / (u - d)).clamp(0, 1) if self.focaler_iou else 1 - self['s_inter'] / self['s_union']),
  548. }
  549. if self.training:
  550. self.iou_mean.mul_(1 - self.momentum)
  551. self.iou_mean.add_(self.momentum * self['iou'].detach().mean())
  552. ret = self._scaled_loss(getattr(self, f'_{self.ltype}')(**kwargs)), self['iou']
  553. delattr(self, '_fget')
  554. return ret if ret_iou else ret[0]
  555. def _scaled_loss(self, loss, iou=None):
  556. if isinstance(self.monotonous, bool):
  557. beta = (self['iou'].detach() if iou is None else iou) / self.iou_mean
  558. if self.monotonous:
  559. loss *= beta.sqrt()
  560. else:
  561. divisor = self.delta * torch.pow(self.alpha, beta - self.delta)
  562. loss *= beta / divisor
  563. return loss
  564. def _IoU(self):
  565. return self['iou']
  566. def _WIoU(self):
  567. dist = torch.exp(self['l2_center'] / self['l2_box'].detach())
  568. return dist * self['iou']
  569. def _EIoU(self):
  570. penalty = self['l2_center'] / self['l2_box'] \
  571. + torch.square(self['d_center'] / self['wh_box']).sum(dim=-1)
  572. return self['iou'] + penalty
  573. def _GIoU(self):
  574. return self['iou'] + (self['s_box'] - self['s_union']) / self['s_box']
  575. def _DIoU(self):
  576. return self['iou'] + self['l2_center'] / self['l2_box']
  577. def _CIoU(self, eps=1e-4):
  578. v = 4 / math.pi ** 2 * \
  579. (torch.atan(self['pred_wh'][..., 0] / (self['pred_wh'][..., 1] + eps)) -
  580. torch.atan(self['target_wh'][..., 0] / (self['target_wh'][..., 1] + eps))) ** 2
  581. alpha = v / (self['iou'] + v)
  582. return self['iou'] + self['l2_center'] / self['l2_box'] + alpha.detach() * v
  583. def _SIoU(self, theta=4):
  584. # Angle Cost
  585. angle = torch.arcsin(torch.abs(self['d_center']).min(dim=-1)[0] / (self['l2_center'].sqrt() + 1e-4))
  586. angle = torch.sin(2 * angle) - 2
  587. # Dist Cost
  588. dist = angle[..., None] * torch.square(self['d_center'] / self['wh_box'])
  589. dist = 2 - torch.exp(dist[..., 0]) - torch.exp(dist[..., 1])
  590. # Shape Cost
  591. d_shape = torch.abs(self['pred_wh'] - self['target_wh'])
  592. big_shape = torch.maximum(self['pred_wh'], self['target_wh'])
  593. w_shape = 1 - torch.exp(- d_shape[..., 0] / big_shape[..., 0])
  594. h_shape = 1 - torch.exp(- d_shape[..., 1] / big_shape[..., 1])
  595. shape = w_shape ** theta + h_shape ** theta
  596. return self['iou'] + (dist + shape) / 2
  597. def _MPDIoU(self, mpdiou_hw):
  598. d1 = (self['target'][..., 0] - self['pred'][..., 0]) ** 2 + (self['target'][..., 1] - self['pred'][..., 1]) ** 2
  599. d2 = (self['target'][..., 2] - self['pred'][..., 2]) ** 2 + (self['target'][..., 3] - self['pred'][..., 3]) ** 2
  600. return self['iou'] + d1 / mpdiou_hw + d2 / mpdiou_hw
  601. def _ShapeIoU(self, scale=0.0):
  602. b1_x1, b1_y1, b1_x2, b1_y2 = self['pred'].chunk(4, -1)
  603. b2_x1, b2_y1, b2_x2, b2_y2 = self['target'].chunk(4, -1)
  604. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + 1e-7
  605. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + 1e-7
  606. #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance #Shape-Distance
  607. ww = 2 * torch.pow(w2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  608. hh = 2 * torch.pow(h2, scale) / (torch.pow(w2, scale) + torch.pow(h2, scale))
  609. cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex width
  610. ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
  611. c2 = cw ** 2 + ch ** 2 + 1e-7 # convex diagonal squared
  612. center_distance_x = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2) / 4
  613. center_distance_y = ((b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4
  614. center_distance = hh * center_distance_x + ww * center_distance_y
  615. distance = center_distance / c2
  616. #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape #Shape-Shape
  617. omiga_w = hh * torch.abs(w1 - w2) / torch.max(w1, w2)
  618. omiga_h = ww * torch.abs(h1 - h2) / torch.max(h1, h2)
  619. shape_cost = torch.pow(1 - torch.exp(-1 * omiga_w), 4) + torch.pow(1 - torch.exp(-1 * omiga_h), 4)
  620. return self['iou'] + distance.squeeze() + 0.5 * shape_cost.squeeze()
  621. def _PIoU(self):
  622. b1_x1, b1_y1, b1_x2, b1_y2 = self['pred'].chunk(4, -1)
  623. b2_x1, b2_y1, b2_x2, b2_y2 = self['target'].chunk(4, -1)
  624. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + 1e-7
  625. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + 1e-7
  626. dw1 = torch.abs(b1_x2.minimum(b1_x1)-b2_x2.minimum(b2_x1))
  627. dw2 = torch.abs(b1_x2.maximum(b1_x1)-b2_x2.maximum(b2_x1))
  628. dh1 = torch.abs(b1_y2.minimum(b1_y1)-b2_y2.minimum(b2_y1))
  629. dh2 = torch.abs(b1_y2.maximum(b1_y1)-b2_y2.maximum(b2_y1))
  630. P = ((dw1+dw2)/torch.abs(w2)+(dh1+dh2)/torch.abs(h2))/4
  631. piou_v1 = self['iou'] - torch.exp(-P.squeeze()**2) + 1
  632. return piou_v1
  633. def _PIoU2(self, Lambda=1.3):
  634. b1_x1, b1_y1, b1_x2, b1_y2 = self['pred'].chunk(4, -1)
  635. b2_x1, b2_y1, b2_x2, b2_y2 = self['target'].chunk(4, -1)
  636. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + 1e-7
  637. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + 1e-7
  638. dw1 = torch.abs(b1_x2.minimum(b1_x1)-b2_x2.minimum(b2_x1))
  639. dw2 = torch.abs(b1_x2.maximum(b1_x1)-b2_x2.maximum(b2_x1))
  640. dh1 = torch.abs(b1_y2.minimum(b1_y1)-b2_y2.minimum(b2_y1))
  641. dh2 = torch.abs(b1_y2.maximum(b1_y1)-b2_y2.maximum(b2_y1))
  642. P = ((dw1+dw2)/torch.abs(w2)+(dh1+dh2)/torch.abs(h2))/4
  643. piou_v1 = self['iou'] - torch.exp(-P.squeeze()**2) + 1
  644. q=torch.exp(-P.squeeze())
  645. x=q*Lambda
  646. return 3*x*torch.exp(-x**2)*piou_v1
  647. def __repr__(self):
  648. return f'{self.__name__}(iou_mean={self.iou_mean.item():.3f})'
  649. __name__ = property(lambda self: self.ltype)
  650. def mask_iou(mask1, mask2, eps=1e-7):
  651. """
  652. Calculate masks IoU.
  653. Args:
  654. mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the
  655. product of image width and height.
  656. mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the
  657. product of image width and height.
  658. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  659. Returns:
  660. (torch.Tensor): A tensor of shape (N, M) representing masks IoU.
  661. """
  662. intersection = torch.matmul(mask1, mask2.T).clamp_(0)
  663. union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
  664. return intersection / (union + eps)
  665. def kpt_iou(kpt1, kpt2, area, sigma, eps=1e-7):
  666. """
  667. Calculate Object Keypoint Similarity (OKS).
  668. Args:
  669. kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.
  670. kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.
  671. area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.
  672. sigma (list): A list containing 17 values representing keypoint scales.
  673. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  674. Returns:
  675. (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.
  676. """
  677. d = (kpt1[:, None, :, 0] - kpt2[..., 0]).pow(2) + (kpt1[:, None, :, 1] - kpt2[..., 1]).pow(2) # (N, M, 17)
  678. sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype) # (17, )
  679. kpt_mask = kpt1[..., 2] != 0 # (N, 17)
  680. e = d / ((2 * sigma).pow(2) * (area[:, None, None] + eps) * 2) # from cocoeval
  681. # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2 # from formula
  682. return ((-e).exp() * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)
  683. def _get_covariance_matrix(boxes):
  684. """
  685. Generating covariance matrix from obbs.
  686. Args:
  687. boxes (torch.Tensor): A tensor of shape (N, 5) representing rotated bounding boxes, with xywhr format.
  688. Returns:
  689. (torch.Tensor): Covariance metrixs corresponding to original rotated bounding boxes.
  690. """
  691. # Gaussian bounding boxes, ignore the center points (the first two columns) because they are not needed here.
  692. gbbs = torch.cat((boxes[:, 2:4].pow(2) / 12, boxes[:, 4:]), dim=-1)
  693. a, b, c = gbbs.split(1, dim=-1)
  694. cos = c.cos()
  695. sin = c.sin()
  696. cos2 = cos.pow(2)
  697. sin2 = sin.pow(2)
  698. return a * cos2 + b * sin2, a * sin2 + b * cos2, (a - b) * cos * sin
  699. def probiou(obb1, obb2, CIoU=False, eps=1e-7):
  700. """
  701. Calculate the prob IoU between oriented bounding boxes, https://arxiv.org/pdf/2106.06072v1.pdf.
  702. Args:
  703. obb1 (torch.Tensor): A tensor of shape (N, 5) representing ground truth obbs, with xywhr format.
  704. obb2 (torch.Tensor): A tensor of shape (N, 5) representing predicted obbs, with xywhr format.
  705. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  706. Returns:
  707. (torch.Tensor): A tensor of shape (N, ) representing obb similarities.
  708. """
  709. x1, y1 = obb1[..., :2].split(1, dim=-1)
  710. x2, y2 = obb2[..., :2].split(1, dim=-1)
  711. a1, b1, c1 = _get_covariance_matrix(obb1)
  712. a2, b2, c2 = _get_covariance_matrix(obb2)
  713. t1 = (
  714. ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
  715. ) * 0.25
  716. t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
  717. t3 = (
  718. ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
  719. / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
  720. + eps
  721. ).log() * 0.5
  722. bd = (t1 + t2 + t3).clamp(eps, 100.0)
  723. hd = (1.0 - (-bd).exp() + eps).sqrt()
  724. iou = 1 - hd
  725. if CIoU: # only include the wh aspect ratio part
  726. w1, h1 = obb1[..., 2:4].split(1, dim=-1)
  727. w2, h2 = obb2[..., 2:4].split(1, dim=-1)
  728. v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
  729. with torch.no_grad():
  730. alpha = v / (v - iou + (1 + eps))
  731. return iou - v * alpha # CIoU
  732. return iou
  733. def batch_probiou(obb1, obb2, eps=1e-7):
  734. """
  735. Calculate the prob IoU between oriented bounding boxes, https://arxiv.org/pdf/2106.06072v1.pdf.
  736. Args:
  737. obb1 (torch.Tensor | np.ndarray): A tensor of shape (N, 5) representing ground truth obbs, with xywhr format.
  738. obb2 (torch.Tensor | np.ndarray): A tensor of shape (M, 5) representing predicted obbs, with xywhr format.
  739. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  740. Returns:
  741. (torch.Tensor): A tensor of shape (N, M) representing obb similarities.
  742. """
  743. obb1 = torch.from_numpy(obb1) if isinstance(obb1, np.ndarray) else obb1
  744. obb2 = torch.from_numpy(obb2) if isinstance(obb2, np.ndarray) else obb2
  745. x1, y1 = obb1[..., :2].split(1, dim=-1)
  746. x2, y2 = (x.squeeze(-1)[None] for x in obb2[..., :2].split(1, dim=-1))
  747. a1, b1, c1 = _get_covariance_matrix(obb1)
  748. a2, b2, c2 = (x.squeeze(-1)[None] for x in _get_covariance_matrix(obb2))
  749. t1 = (
  750. ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
  751. ) * 0.25
  752. t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
  753. t3 = (
  754. ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
  755. / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
  756. + eps
  757. ).log() * 0.5
  758. bd = (t1 + t2 + t3).clamp(eps, 100.0)
  759. hd = (1.0 - (-bd).exp() + eps).sqrt()
  760. return 1 - hd
  761. def smooth_BCE(eps=0.1):
  762. """
  763. Computes smoothed positive and negative Binary Cross-Entropy targets.
  764. This function calculates positive and negative label smoothing BCE targets based on a given epsilon value.
  765. For implementation details, refer to https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441.
  766. Args:
  767. eps (float, optional): The epsilon value for label smoothing. Defaults to 0.1.
  768. Returns:
  769. (tuple): A tuple containing the positive and negative label smoothing BCE targets.
  770. """
  771. return 1.0 - 0.5 * eps, 0.5 * eps
  772. class ConfusionMatrix:
  773. """
  774. A class for calculating and updating a confusion matrix for object detection and classification tasks.
  775. Attributes:
  776. task (str): The type of task, either 'detect' or 'classify'.
  777. matrix (np.ndarray): The confusion matrix, with dimensions depending on the task.
  778. nc (int): The number of classes.
  779. conf (float): The confidence threshold for detections.
  780. iou_thres (float): The Intersection over Union threshold.
  781. """
  782. def __init__(self, nc, conf=0.25, iou_thres=0.45, task="detect"):
  783. """Initialize attributes for the YOLO model."""
  784. self.task = task
  785. self.matrix = np.zeros((nc + 1, nc + 1)) if self.task == "detect" else np.zeros((nc, nc))
  786. self.nc = nc # number of classes
  787. self.conf = 0.25 if conf in {None, 0.001} else conf # apply 0.25 if default val conf is passed
  788. self.iou_thres = iou_thres
  789. def process_cls_preds(self, preds, targets):
  790. """
  791. Update confusion matrix for classification task.
  792. Args:
  793. preds (Array[N, min(nc,5)]): Predicted class labels.
  794. targets (Array[N, 1]): Ground truth class labels.
  795. """
  796. preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)
  797. for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):
  798. self.matrix[p][t] += 1
  799. def process_batch(self, detections, gt_bboxes, gt_cls):
  800. """
  801. Update confusion matrix for object detection task.
  802. Args:
  803. detections (Array[N, 6] | Array[N, 7]): Detected bounding boxes and their associated information.
  804. Each row should contain (x1, y1, x2, y2, conf, class)
  805. or with an additional element `angle` when it's obb.
  806. gt_bboxes (Array[M, 4]| Array[N, 5]): Ground truth bounding boxes with xyxy/xyxyr format.
  807. gt_cls (Array[M]): The class labels.
  808. """
  809. if gt_cls.shape[0] == 0: # Check if labels is empty
  810. if detections is not None:
  811. detections = detections[detections[:, 4] > self.conf]
  812. detection_classes = detections[:, 5].int()
  813. for dc in detection_classes:
  814. self.matrix[dc, self.nc] += 1 # false positives
  815. return
  816. if detections is None:
  817. gt_classes = gt_cls.int()
  818. for gc in gt_classes:
  819. self.matrix[self.nc, gc] += 1 # background FN
  820. return
  821. detections = detections[detections[:, 4] > self.conf]
  822. gt_classes = gt_cls.int()
  823. detection_classes = detections[:, 5].int()
  824. is_obb = detections.shape[1] == 7 and gt_bboxes.shape[1] == 5 # with additional `angle` dimension
  825. iou = (
  826. batch_probiou(gt_bboxes, torch.cat([detections[:, :4], detections[:, -1:]], dim=-1))
  827. if is_obb
  828. else box_iou(gt_bboxes, detections[:, :4])
  829. )
  830. x = torch.where(iou > self.iou_thres)
  831. if x[0].shape[0]:
  832. matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
  833. if x[0].shape[0] > 1:
  834. matches = matches[matches[:, 2].argsort()[::-1]]
  835. matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
  836. matches = matches[matches[:, 2].argsort()[::-1]]
  837. matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
  838. else:
  839. matches = np.zeros((0, 3))
  840. n = matches.shape[0] > 0
  841. m0, m1, _ = matches.transpose().astype(int)
  842. for i, gc in enumerate(gt_classes):
  843. j = m0 == i
  844. if n and sum(j) == 1:
  845. self.matrix[detection_classes[m1[j]], gc] += 1 # correct
  846. else:
  847. self.matrix[self.nc, gc] += 1 # true background
  848. if n:
  849. for i, dc in enumerate(detection_classes):
  850. if not any(m1 == i):
  851. self.matrix[dc, self.nc] += 1 # predicted background
  852. def matrix(self):
  853. """Returns the confusion matrix."""
  854. return self.matrix
  855. def tp_fp(self):
  856. """Returns true positives and false positives."""
  857. tp = self.matrix.diagonal() # true positives
  858. fp = self.matrix.sum(1) - tp # false positives
  859. # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
  860. return (tp[:-1], fp[:-1]) if self.task == "detect" else (tp, fp) # remove background class if task=detect
  861. @TryExcept("WARNING ⚠️ ConfusionMatrix plot failure")
  862. @plt_settings()
  863. def plot(self, normalize=True, save_dir="", names=(), on_plot=None):
  864. """
  865. Plot the confusion matrix using seaborn and save it to a file.
  866. Args:
  867. normalize (bool): Whether to normalize the confusion matrix.
  868. save_dir (str): Directory where the plot will be saved.
  869. names (tuple): Names of classes, used as labels on the plot.
  870. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  871. """
  872. import seaborn # scope for faster 'import ultralytics'
  873. array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1) # normalize columns
  874. array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
  875. fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)
  876. nc, nn = self.nc, len(names) # number of classes, names
  877. seaborn.set_theme(font_scale=1.0 if nc < 50 else 0.8) # for label size
  878. labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
  879. ticklabels = (list(names) + ["background"]) if labels else "auto"
  880. with warnings.catch_warnings():
  881. warnings.simplefilter("ignore") # suppress empty matrix RuntimeWarning: All-NaN slice encountered
  882. seaborn.heatmap(
  883. array,
  884. ax=ax,
  885. annot=nc < 30,
  886. annot_kws={"size": 8},
  887. cmap="Blues",
  888. fmt=".2f" if normalize else ".0f",
  889. square=True,
  890. vmin=0.0,
  891. xticklabels=ticklabels,
  892. yticklabels=ticklabels,
  893. ).set_facecolor((1, 1, 1))
  894. title = "Confusion Matrix" + " Normalized" * normalize
  895. ax.set_xlabel("True")
  896. ax.set_ylabel("Predicted")
  897. ax.set_title(title)
  898. plot_fname = Path(save_dir) / f'{title.lower().replace(" ", "_")}.png'
  899. fig.savefig(plot_fname, dpi=250)
  900. plt.close(fig)
  901. try:
  902. TrainSdk.save_output_model(plot_fname)
  903. except:
  904. pass
  905. if on_plot:
  906. on_plot(plot_fname)
  907. def print(self):
  908. """Print the confusion matrix to the console."""
  909. for i in range(self.nc + 1):
  910. LOGGER.info(" ".join(map(str, self.matrix[i])))
  911. def smooth(y, f=0.05):
  912. """Box filter of fraction f."""
  913. nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
  914. p = np.ones(nf // 2) # ones padding
  915. yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
  916. return np.convolve(yp, np.ones(nf) / nf, mode="valid") # y-smoothed
  917. @plt_settings()
  918. def plot_pr_curve(px, py, ap, save_dir=Path("pr_curve.png"), names=(), on_plot=None):
  919. """Plots a precision-recall curve."""
  920. fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
  921. py = np.stack(py, axis=1)
  922. if 0 < len(names) < 21: # display per-class legend if < 21 classes
  923. for i, y in enumerate(py.T):
  924. ax.plot(px, y, linewidth=1, label=f"{names[i]} {ap[i, 0]:.3f}") # plot(recall, precision)
  925. else:
  926. ax.plot(px, py, linewidth=1, color="grey") # plot(recall, precision)
  927. ax.plot(px, py.mean(1), linewidth=3, color="blue", label="all classes %.3f mAP@0.5" % ap[:, 0].mean())
  928. ax.set_xlabel("Recall")
  929. ax.set_ylabel("Precision")
  930. ax.set_xlim(0, 1)
  931. ax.set_ylim(0, 1)
  932. ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
  933. ax.set_title("Precision-Recall Curve")
  934. fig.savefig(save_dir, dpi=250)
  935. plt.close(fig)
  936. try:
  937. TrainSdk.save_output_model(save_dir)
  938. except:
  939. pass
  940. if on_plot:
  941. on_plot(save_dir)
  942. @plt_settings()
  943. def plot_mc_curve(px, py, save_dir=Path("mc_curve.png"), names=(), xlabel="Confidence", ylabel="Metric", on_plot=None):
  944. """Plots a metric-confidence curve."""
  945. fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
  946. if 0 < len(names) < 21: # display per-class legend if < 21 classes
  947. for i, y in enumerate(py):
  948. ax.plot(px, y, linewidth=1, label=f"{names[i]}") # plot(confidence, metric)
  949. else:
  950. ax.plot(px, py.T, linewidth=1, color="grey") # plot(confidence, metric)
  951. y = smooth(py.mean(0), 0.05)
  952. ax.plot(px, y, linewidth=3, color="blue", label=f"all classes {y.max():.2f} at {px[y.argmax()]:.3f}")
  953. ax.set_xlabel(xlabel)
  954. ax.set_ylabel(ylabel)
  955. ax.set_xlim(0, 1)
  956. ax.set_ylim(0, 1)
  957. ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
  958. ax.set_title(f"{ylabel}-Confidence Curve")
  959. fig.savefig(save_dir, dpi=250)
  960. plt.close(fig)
  961. try:
  962. TrainSdk.save_output_model(save_dir)
  963. except:
  964. pass
  965. if on_plot:
  966. on_plot(save_dir)
  967. def compute_ap(recall, precision):
  968. """
  969. Compute the average precision (AP) given the recall and precision curves.
  970. Args:
  971. recall (list): The recall curve.
  972. precision (list): The precision curve.
  973. Returns:
  974. (float): Average precision.
  975. (np.ndarray): Precision envelope curve.
  976. (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.
  977. """
  978. # Append sentinel values to beginning and end
  979. mrec = np.concatenate(([0.0], recall, [1.0]))
  980. mpre = np.concatenate(([1.0], precision, [0.0]))
  981. # Compute the precision envelope
  982. mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
  983. # Integrate area under curve
  984. method = "interp" # methods: 'continuous', 'interp'
  985. if method == "interp":
  986. x = np.linspace(0, 1, 101) # 101-point interp (COCO)
  987. ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
  988. else: # 'continuous'
  989. i = np.where(mrec[1:] != mrec[:-1])[0] # points where x-axis (recall) changes
  990. ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
  991. return ap, mpre, mrec
  992. def ap_per_class(
  993. tp, conf, pred_cls, target_cls, plot=False, on_plot=None, save_dir=Path(), names=(), eps=1e-16, prefix=""
  994. ):
  995. """
  996. Computes the average precision per class for object detection evaluation.
  997. Args:
  998. tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).
  999. conf (np.ndarray): Array of confidence scores of the detections.
  1000. pred_cls (np.ndarray): Array of predicted classes of the detections.
  1001. target_cls (np.ndarray): Array of true classes of the detections.
  1002. plot (bool, optional): Whether to plot PR curves or not. Defaults to False.
  1003. on_plot (func, optional): A callback to pass plots path and data when they are rendered. Defaults to None.
  1004. save_dir (Path, optional): Directory to save the PR curves. Defaults to an empty path.
  1005. names (tuple, optional): Tuple of class names to plot PR curves. Defaults to an empty tuple.
  1006. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-16.
  1007. prefix (str, optional): A prefix string for saving the plot files. Defaults to an empty string.
  1008. Returns:
  1009. (tuple): A tuple of six arrays and one array of unique classes, where:
  1010. tp (np.ndarray): True positive counts at threshold given by max F1 metric for each class.Shape: (nc,).
  1011. fp (np.ndarray): False positive counts at threshold given by max F1 metric for each class. Shape: (nc,).
  1012. p (np.ndarray): Precision values at threshold given by max F1 metric for each class. Shape: (nc,).
  1013. r (np.ndarray): Recall values at threshold given by max F1 metric for each class. Shape: (nc,).
  1014. f1 (np.ndarray): F1-score values at threshold given by max F1 metric for each class. Shape: (nc,).
  1015. ap (np.ndarray): Average precision for each class at different IoU thresholds. Shape: (nc, 10).
  1016. unique_classes (np.ndarray): An array of unique classes that have data. Shape: (nc,).
  1017. p_curve (np.ndarray): Precision curves for each class. Shape: (nc, 1000).
  1018. r_curve (np.ndarray): Recall curves for each class. Shape: (nc, 1000).
  1019. f1_curve (np.ndarray): F1-score curves for each class. Shape: (nc, 1000).
  1020. x (np.ndarray): X-axis values for the curves. Shape: (1000,).
  1021. prec_values: Precision values at mAP@0.5 for each class. Shape: (nc, 1000).
  1022. """
  1023. # Sort by objectness
  1024. i = np.argsort(-conf)
  1025. tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
  1026. # Find unique classes
  1027. unique_classes, nt = np.unique(target_cls, return_counts=True)
  1028. nc = unique_classes.shape[0] # number of classes, number of detections
  1029. # Create Precision-Recall curve and compute AP for each class
  1030. x, prec_values = np.linspace(0, 1, 1000), []
  1031. # Average precision, precision and recall curves
  1032. ap, p_curve, r_curve = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
  1033. for ci, c in enumerate(unique_classes):
  1034. i = pred_cls == c
  1035. n_l = nt[ci] # number of labels
  1036. n_p = i.sum() # number of predictions
  1037. if n_p == 0 or n_l == 0:
  1038. continue
  1039. # Accumulate FPs and TPs
  1040. fpc = (1 - tp[i]).cumsum(0)
  1041. tpc = tp[i].cumsum(0)
  1042. # Recall
  1043. recall = tpc / (n_l + eps) # recall curve
  1044. r_curve[ci] = np.interp(-x, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
  1045. # Precision
  1046. precision = tpc / (tpc + fpc) # precision curve
  1047. p_curve[ci] = np.interp(-x, -conf[i], precision[:, 0], left=1) # p at pr_score
  1048. # AP from recall-precision curve
  1049. for j in range(tp.shape[1]):
  1050. ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
  1051. if plot and j == 0:
  1052. prec_values.append(np.interp(x, mrec, mpre)) # precision at mAP@0.5
  1053. prec_values = np.array(prec_values) # (nc, 1000)
  1054. # Compute F1 (harmonic mean of precision and recall)
  1055. f1_curve = 2 * p_curve * r_curve / (p_curve + r_curve + eps)
  1056. names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data
  1057. names = dict(enumerate(names)) # to dict
  1058. if plot:
  1059. plot_pr_curve(x, prec_values, ap, save_dir / f"{prefix}PR_curve.png", names, on_plot=on_plot)
  1060. plot_mc_curve(x, f1_curve, save_dir / f"{prefix}F1_curve.png", names, ylabel="F1", on_plot=on_plot)
  1061. plot_mc_curve(x, p_curve, save_dir / f"{prefix}P_curve.png", names, ylabel="Precision", on_plot=on_plot)
  1062. plot_mc_curve(x, r_curve, save_dir / f"{prefix}R_curve.png", names, ylabel="Recall", on_plot=on_plot)
  1063. i = smooth(f1_curve.mean(0), 0.1).argmax() # max F1 index
  1064. p, r, f1 = p_curve[:, i], r_curve[:, i], f1_curve[:, i] # max-F1 precision, recall, F1 values
  1065. tp = (r * nt).round() # true positives
  1066. fp = (tp / (p + eps) - tp).round() # false positives
  1067. return tp, fp, p, r, f1, ap, unique_classes.astype(int), p_curve, r_curve, f1_curve, x, prec_values
  1068. class Metric(SimpleClass):
  1069. """
  1070. Class for computing evaluation metrics for YOLOv8 model.
  1071. Attributes:
  1072. p (list): Precision for each class. Shape: (nc,).
  1073. r (list): Recall for each class. Shape: (nc,).
  1074. f1 (list): F1 score for each class. Shape: (nc,).
  1075. all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
  1076. ap_class_index (list): Index of class for each AP score. Shape: (nc,).
  1077. nc (int): Number of classes.
  1078. Methods:
  1079. ap50(): AP at IoU threshold of 0.5 for all classes. Returns: List of AP scores. Shape: (nc,) or [].
  1080. ap(): AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: List of AP scores. Shape: (nc,) or [].
  1081. mp(): Mean precision of all classes. Returns: Float.
  1082. mr(): Mean recall of all classes. Returns: Float.
  1083. map50(): Mean AP at IoU threshold of 0.5 for all classes. Returns: Float.
  1084. map75(): Mean AP at IoU threshold of 0.75 for all classes. Returns: Float.
  1085. map(): Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: Float.
  1086. mean_results(): Mean of results, returns mp, mr, map50, map.
  1087. class_result(i): Class-aware result, returns p[i], r[i], ap50[i], ap[i].
  1088. maps(): mAP of each class. Returns: Array of mAP scores, shape: (nc,).
  1089. fitness(): Model fitness as a weighted combination of metrics. Returns: Float.
  1090. update(results): Update metric attributes with new evaluation results.
  1091. """
  1092. def __init__(self) -> None:
  1093. """Initializes a Metric instance for computing evaluation metrics for the YOLOv8 model."""
  1094. self.p = [] # (nc, )
  1095. self.r = [] # (nc, )
  1096. self.f1 = [] # (nc, )
  1097. self.all_ap = [] # (nc, 10)
  1098. self.ap_class_index = [] # (nc, )
  1099. self.nc = 0
  1100. @property
  1101. def ap50(self):
  1102. """
  1103. Returns the Average Precision (AP) at an IoU threshold of 0.5 for all classes.
  1104. Returns:
  1105. (np.ndarray, list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.
  1106. """
  1107. return self.all_ap[:, 0] if len(self.all_ap) else []
  1108. @property
  1109. def ap(self):
  1110. """
  1111. Returns the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.
  1112. Returns:
  1113. (np.ndarray, list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.
  1114. """
  1115. return self.all_ap.mean(1) if len(self.all_ap) else []
  1116. @property
  1117. def mp(self):
  1118. """
  1119. Returns the Mean Precision of all classes.
  1120. Returns:
  1121. (float): The mean precision of all classes.
  1122. """
  1123. return self.p.mean() if len(self.p) else 0.0
  1124. @property
  1125. def mr(self):
  1126. """
  1127. Returns the Mean Recall of all classes.
  1128. Returns:
  1129. (float): The mean recall of all classes.
  1130. """
  1131. return self.r.mean() if len(self.r) else 0.0
  1132. @property
  1133. def map50(self):
  1134. """
  1135. Returns the mean Average Precision (mAP) at an IoU threshold of 0.5.
  1136. Returns:
  1137. (float): The mAP at an IoU threshold of 0.5.
  1138. """
  1139. return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0
  1140. @property
  1141. def map75(self):
  1142. """
  1143. Returns the mean Average Precision (mAP) at an IoU threshold of 0.75.
  1144. Returns:
  1145. (float): The mAP at an IoU threshold of 0.75.
  1146. """
  1147. return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0
  1148. @property
  1149. def map(self):
  1150. """
  1151. Returns the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
  1152. Returns:
  1153. (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
  1154. """
  1155. return self.all_ap.mean() if len(self.all_ap) else 0.0
  1156. def mean_results(self):
  1157. """Mean of results, return mp, mr, map50, map."""
  1158. return [self.mp, self.mr, self.map50, self.map]
  1159. def class_result(self, i):
  1160. """Class-aware result, return p[i], r[i], ap50[i], ap[i]."""
  1161. return self.p[i], self.r[i], self.ap50[i], self.ap[i]
  1162. @property
  1163. def maps(self):
  1164. """MAP of each class."""
  1165. maps = np.zeros(self.nc) + self.map
  1166. for i, c in enumerate(self.ap_class_index):
  1167. maps[c] = self.ap[i]
  1168. return maps
  1169. def fitness(self):
  1170. """Model fitness as a weighted combination of metrics."""
  1171. w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
  1172. return (np.array(self.mean_results()) * w).sum()
  1173. def update(self, results):
  1174. """
  1175. Updates the evaluation metrics of the model with a new set of results.
  1176. Args:
  1177. results (tuple): A tuple containing the following evaluation metrics:
  1178. - p (list): Precision for each class. Shape: (nc,).
  1179. - r (list): Recall for each class. Shape: (nc,).
  1180. - f1 (list): F1 score for each class. Shape: (nc,).
  1181. - all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
  1182. - ap_class_index (list): Index of class for each AP score. Shape: (nc,).
  1183. Side Effects:
  1184. Updates the class attributes `self.p`, `self.r`, `self.f1`, `self.all_ap`, and `self.ap_class_index` based
  1185. on the values provided in the `results` tuple.
  1186. """
  1187. (
  1188. self.p,
  1189. self.r,
  1190. self.f1,
  1191. self.all_ap,
  1192. self.ap_class_index,
  1193. self.p_curve,
  1194. self.r_curve,
  1195. self.f1_curve,
  1196. self.px,
  1197. self.prec_values,
  1198. ) = results
  1199. @property
  1200. def curves(self):
  1201. """Returns a list of curves for accessing specific metrics curves."""
  1202. return []
  1203. @property
  1204. def curves_results(self):
  1205. """Returns a list of curves for accessing specific metrics curves."""
  1206. return [
  1207. [self.px, self.prec_values, "Recall", "Precision"],
  1208. [self.px, self.f1_curve, "Confidence", "F1"],
  1209. [self.px, self.p_curve, "Confidence", "Precision"],
  1210. [self.px, self.r_curve, "Confidence", "Recall"],
  1211. ]
  1212. class DetMetrics(SimpleClass):
  1213. """
  1214. This class is a utility class for computing detection metrics such as precision, recall, and mean average precision
  1215. (mAP) of an object detection model.
  1216. Args:
  1217. save_dir (Path): A path to the directory where the output plots will be saved. Defaults to current directory.
  1218. plot (bool): A flag that indicates whether to plot precision-recall curves for each class. Defaults to False.
  1219. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  1220. names (tuple of str): A tuple of strings that represents the names of the classes. Defaults to an empty tuple.
  1221. Attributes:
  1222. save_dir (Path): A path to the directory where the output plots will be saved.
  1223. plot (bool): A flag that indicates whether to plot the precision-recall curves for each class.
  1224. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  1225. names (tuple of str): A tuple of strings that represents the names of the classes.
  1226. box (Metric): An instance of the Metric class for storing the results of the detection metrics.
  1227. speed (dict): A dictionary for storing the execution time of different parts of the detection process.
  1228. Methods:
  1229. process(tp, conf, pred_cls, target_cls): Updates the metric results with the latest batch of predictions.
  1230. keys: Returns a list of keys for accessing the computed detection metrics.
  1231. mean_results: Returns a list of mean values for the computed detection metrics.
  1232. class_result(i): Returns a list of values for the computed detection metrics for a specific class.
  1233. maps: Returns a dictionary of mean average precision (mAP) values for different IoU thresholds.
  1234. fitness: Computes the fitness score based on the computed detection metrics.
  1235. ap_class_index: Returns a list of class indices sorted by their average precision (AP) values.
  1236. results_dict: Returns a dictionary that maps detection metric keys to their computed values.
  1237. curves: TODO
  1238. curves_results: TODO
  1239. """
  1240. def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names=()) -> None:
  1241. """Initialize a DetMetrics instance with a save directory, plot flag, callback function, and class names."""
  1242. self.save_dir = save_dir
  1243. self.plot = plot
  1244. self.on_plot = on_plot
  1245. self.names = names
  1246. self.box = Metric()
  1247. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  1248. self.task = "detect"
  1249. def process(self, tp, conf, pred_cls, target_cls):
  1250. """Process predicted results for object detection and update metrics."""
  1251. results = ap_per_class(
  1252. tp,
  1253. conf,
  1254. pred_cls,
  1255. target_cls,
  1256. plot=self.plot,
  1257. save_dir=self.save_dir,
  1258. names=self.names,
  1259. on_plot=self.on_plot,
  1260. )[2:]
  1261. self.box.nc = len(self.names)
  1262. self.box.update(results)
  1263. @property
  1264. def keys(self):
  1265. """Returns a list of keys for accessing specific metrics."""
  1266. return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
  1267. def mean_results(self):
  1268. """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95."""
  1269. return self.box.mean_results()
  1270. def class_result(self, i):
  1271. """Return the result of evaluating the performance of an object detection model on a specific class."""
  1272. return self.box.class_result(i)
  1273. @property
  1274. def maps(self):
  1275. """Returns mean Average Precision (mAP) scores per class."""
  1276. return self.box.maps
  1277. @property
  1278. def fitness(self):
  1279. """Returns the fitness of box object."""
  1280. return self.box.fitness()
  1281. @property
  1282. def ap_class_index(self):
  1283. """Returns the average precision index per class."""
  1284. return self.box.ap_class_index
  1285. @property
  1286. def results_dict(self):
  1287. """Returns dictionary of computed performance metrics and statistics."""
  1288. return dict(zip(self.keys + ["fitness"], self.mean_results() + [self.fitness]))
  1289. @property
  1290. def curves(self):
  1291. """Returns a list of curves for accessing specific metrics curves."""
  1292. return ["Precision-Recall(B)", "F1-Confidence(B)", "Precision-Confidence(B)", "Recall-Confidence(B)"]
  1293. @property
  1294. def curves_results(self):
  1295. """Returns dictionary of computed performance metrics and statistics."""
  1296. return self.box.curves_results
  1297. class SegmentMetrics(SimpleClass):
  1298. """
  1299. Calculates and aggregates detection and segmentation metrics over a given set of classes.
  1300. Args:
  1301. save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.
  1302. plot (bool): Whether to save the detection and segmentation plots. Default is False.
  1303. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  1304. names (list): List of class names. Default is an empty list.
  1305. Attributes:
  1306. save_dir (Path): Path to the directory where the output plots should be saved.
  1307. plot (bool): Whether to save the detection and segmentation plots.
  1308. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  1309. names (list): List of class names.
  1310. box (Metric): An instance of the Metric class to calculate box detection metrics.
  1311. seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.
  1312. speed (dict): Dictionary to store the time taken in different phases of inference.
  1313. Methods:
  1314. process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.
  1315. mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.
  1316. class_result(i): Returns the detection and segmentation metrics of class `i`.
  1317. maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.
  1318. fitness: Returns the fitness scores, which are a single weighted combination of metrics.
  1319. ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).
  1320. results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.
  1321. """
  1322. def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names=()) -> None:
  1323. """Initialize a SegmentMetrics instance with a save directory, plot flag, callback function, and class names."""
  1324. self.save_dir = save_dir
  1325. self.plot = plot
  1326. self.on_plot = on_plot
  1327. self.names = names
  1328. self.box = Metric()
  1329. self.seg = Metric()
  1330. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  1331. self.task = "segment"
  1332. def process(self, tp, tp_m, conf, pred_cls, target_cls):
  1333. """
  1334. Processes the detection and segmentation metrics over the given set of predictions.
  1335. Args:
  1336. tp (list): List of True Positive boxes.
  1337. tp_m (list): List of True Positive masks.
  1338. conf (list): List of confidence scores.
  1339. pred_cls (list): List of predicted classes.
  1340. target_cls (list): List of target classes.
  1341. """
  1342. results_mask = ap_per_class(
  1343. tp_m,
  1344. conf,
  1345. pred_cls,
  1346. target_cls,
  1347. plot=self.plot,
  1348. on_plot=self.on_plot,
  1349. save_dir=self.save_dir,
  1350. names=self.names,
  1351. prefix="Mask",
  1352. )[2:]
  1353. self.seg.nc = len(self.names)
  1354. self.seg.update(results_mask)
  1355. results_box = ap_per_class(
  1356. tp,
  1357. conf,
  1358. pred_cls,
  1359. target_cls,
  1360. plot=self.plot,
  1361. on_plot=self.on_plot,
  1362. save_dir=self.save_dir,
  1363. names=self.names,
  1364. prefix="Box",
  1365. )[2:]
  1366. self.box.nc = len(self.names)
  1367. self.box.update(results_box)
  1368. @property
  1369. def keys(self):
  1370. """Returns a list of keys for accessing metrics."""
  1371. return [
  1372. "metrics/precision(B)",
  1373. "metrics/recall(B)",
  1374. "metrics/mAP50(B)",
  1375. "metrics/mAP50-95(B)",
  1376. "metrics/precision(M)",
  1377. "metrics/recall(M)",
  1378. "metrics/mAP50(M)",
  1379. "metrics/mAP50-95(M)",
  1380. ]
  1381. def mean_results(self):
  1382. """Return the mean metrics for bounding box and segmentation results."""
  1383. return self.box.mean_results() + self.seg.mean_results()
  1384. def class_result(self, i):
  1385. """Returns classification results for a specified class index."""
  1386. return self.box.class_result(i) + self.seg.class_result(i)
  1387. @property
  1388. def maps(self):
  1389. """Returns mAP scores for object detection and semantic segmentation models."""
  1390. return self.box.maps + self.seg.maps
  1391. @property
  1392. def fitness(self):
  1393. """Get the fitness score for both segmentation and bounding box models."""
  1394. return self.seg.fitness() + self.box.fitness()
  1395. @property
  1396. def ap_class_index(self):
  1397. """Boxes and masks have the same ap_class_index."""
  1398. return self.box.ap_class_index
  1399. @property
  1400. def results_dict(self):
  1401. """Returns results of object detection model for evaluation."""
  1402. return dict(zip(self.keys + ["fitness"], self.mean_results() + [self.fitness]))
  1403. @property
  1404. def curves(self):
  1405. """Returns a list of curves for accessing specific metrics curves."""
  1406. return [
  1407. "Precision-Recall(B)",
  1408. "F1-Confidence(B)",
  1409. "Precision-Confidence(B)",
  1410. "Recall-Confidence(B)",
  1411. "Precision-Recall(M)",
  1412. "F1-Confidence(M)",
  1413. "Precision-Confidence(M)",
  1414. "Recall-Confidence(M)",
  1415. ]
  1416. @property
  1417. def curves_results(self):
  1418. """Returns dictionary of computed performance metrics and statistics."""
  1419. return self.box.curves_results + self.seg.curves_results
  1420. class PoseMetrics(SegmentMetrics):
  1421. """
  1422. Calculates and aggregates detection and pose metrics over a given set of classes.
  1423. Args:
  1424. save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.
  1425. plot (bool): Whether to save the detection and segmentation plots. Default is False.
  1426. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  1427. names (list): List of class names. Default is an empty list.
  1428. Attributes:
  1429. save_dir (Path): Path to the directory where the output plots should be saved.
  1430. plot (bool): Whether to save the detection and segmentation plots.
  1431. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  1432. names (list): List of class names.
  1433. box (Metric): An instance of the Metric class to calculate box detection metrics.
  1434. pose (Metric): An instance of the Metric class to calculate mask segmentation metrics.
  1435. speed (dict): Dictionary to store the time taken in different phases of inference.
  1436. Methods:
  1437. process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.
  1438. mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.
  1439. class_result(i): Returns the detection and segmentation metrics of class `i`.
  1440. maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.
  1441. fitness: Returns the fitness scores, which are a single weighted combination of metrics.
  1442. ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).
  1443. results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.
  1444. """
  1445. def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names=()) -> None:
  1446. """Initialize the PoseMetrics class with directory path, class names, and plotting options."""
  1447. super().__init__(save_dir, plot, names)
  1448. self.save_dir = save_dir
  1449. self.plot = plot
  1450. self.on_plot = on_plot
  1451. self.names = names
  1452. self.box = Metric()
  1453. self.pose = Metric()
  1454. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  1455. self.task = "pose"
  1456. def process(self, tp, tp_p, conf, pred_cls, target_cls):
  1457. """
  1458. Processes the detection and pose metrics over the given set of predictions.
  1459. Args:
  1460. tp (list): List of True Positive boxes.
  1461. tp_p (list): List of True Positive keypoints.
  1462. conf (list): List of confidence scores.
  1463. pred_cls (list): List of predicted classes.
  1464. target_cls (list): List of target classes.
  1465. """
  1466. results_pose = ap_per_class(
  1467. tp_p,
  1468. conf,
  1469. pred_cls,
  1470. target_cls,
  1471. plot=self.plot,
  1472. on_plot=self.on_plot,
  1473. save_dir=self.save_dir,
  1474. names=self.names,
  1475. prefix="Pose",
  1476. )[2:]
  1477. self.pose.nc = len(self.names)
  1478. self.pose.update(results_pose)
  1479. results_box = ap_per_class(
  1480. tp,
  1481. conf,
  1482. pred_cls,
  1483. target_cls,
  1484. plot=self.plot,
  1485. on_plot=self.on_plot,
  1486. save_dir=self.save_dir,
  1487. names=self.names,
  1488. prefix="Box",
  1489. )[2:]
  1490. self.box.nc = len(self.names)
  1491. self.box.update(results_box)
  1492. @property
  1493. def keys(self):
  1494. """Returns list of evaluation metric keys."""
  1495. return [
  1496. "metrics/precision(B)",
  1497. "metrics/recall(B)",
  1498. "metrics/mAP50(B)",
  1499. "metrics/mAP50-95(B)",
  1500. "metrics/precision(P)",
  1501. "metrics/recall(P)",
  1502. "metrics/mAP50(P)",
  1503. "metrics/mAP50-95(P)",
  1504. ]
  1505. def mean_results(self):
  1506. """Return the mean results of box and pose."""
  1507. return self.box.mean_results() + self.pose.mean_results()
  1508. def class_result(self, i):
  1509. """Return the class-wise detection results for a specific class i."""
  1510. return self.box.class_result(i) + self.pose.class_result(i)
  1511. @property
  1512. def maps(self):
  1513. """Returns the mean average precision (mAP) per class for both box and pose detections."""
  1514. return self.box.maps + self.pose.maps
  1515. @property
  1516. def fitness(self):
  1517. """Computes classification metrics and speed using the `targets` and `pred` inputs."""
  1518. return self.pose.fitness() + self.box.fitness()
  1519. @property
  1520. def curves(self):
  1521. """Returns a list of curves for accessing specific metrics curves."""
  1522. return [
  1523. "Precision-Recall(B)",
  1524. "F1-Confidence(B)",
  1525. "Precision-Confidence(B)",
  1526. "Recall-Confidence(B)",
  1527. "Precision-Recall(P)",
  1528. "F1-Confidence(P)",
  1529. "Precision-Confidence(P)",
  1530. "Recall-Confidence(P)",
  1531. ]
  1532. @property
  1533. def curves_results(self):
  1534. """Returns dictionary of computed performance metrics and statistics."""
  1535. return self.box.curves_results + self.pose.curves_results
  1536. class ClassifyMetrics(SimpleClass):
  1537. """
  1538. Class for computing classification metrics including top-1 and top-5 accuracy.
  1539. Attributes:
  1540. top1 (float): The top-1 accuracy.
  1541. top5 (float): The top-5 accuracy.
  1542. speed (Dict[str, float]): A dictionary containing the time taken for each step in the pipeline.
  1543. fitness (float): The fitness of the model, which is equal to top-5 accuracy.
  1544. results_dict (Dict[str, Union[float, str]]): A dictionary containing the classification metrics and fitness.
  1545. keys (List[str]): A list of keys for the results_dict.
  1546. Methods:
  1547. process(targets, pred): Processes the targets and predictions to compute classification metrics.
  1548. """
  1549. def __init__(self) -> None:
  1550. """Initialize a ClassifyMetrics instance."""
  1551. self.top1 = 0
  1552. self.top5 = 0
  1553. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  1554. self.task = "classify"
  1555. def process(self, targets, pred):
  1556. """Target classes and predicted classes."""
  1557. pred, targets = torch.cat(pred), torch.cat(targets)
  1558. correct = (targets[:, None] == pred).float()
  1559. acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
  1560. self.top1, self.top5 = acc.mean(0).tolist()
  1561. @property
  1562. def fitness(self):
  1563. """Returns mean of top-1 and top-5 accuracies as fitness score."""
  1564. return (self.top1 + self.top5) / 2
  1565. @property
  1566. def results_dict(self):
  1567. """Returns a dictionary with model's performance metrics and fitness score."""
  1568. return dict(zip(self.keys + ["fitness"], [self.top1, self.top5, self.fitness]))
  1569. @property
  1570. def keys(self):
  1571. """Returns a list of keys for the results_dict property."""
  1572. return ["metrics/accuracy_top1", "metrics/accuracy_top5"]
  1573. @property
  1574. def curves(self):
  1575. """Returns a list of curves for accessing specific metrics curves."""
  1576. return []
  1577. @property
  1578. def curves_results(self):
  1579. """Returns a list of curves for accessing specific metrics curves."""
  1580. return []
  1581. class OBBMetrics(SimpleClass):
  1582. def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names=()) -> None:
  1583. """Initialize an OBBMetrics instance with directory, plotting, callback, and class names."""
  1584. self.save_dir = save_dir
  1585. self.plot = plot
  1586. self.on_plot = on_plot
  1587. self.names = names
  1588. self.box = Metric()
  1589. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  1590. def process(self, tp, conf, pred_cls, target_cls):
  1591. """Process predicted results for object detection and update metrics."""
  1592. results = ap_per_class(
  1593. tp,
  1594. conf,
  1595. pred_cls,
  1596. target_cls,
  1597. plot=self.plot,
  1598. save_dir=self.save_dir,
  1599. names=self.names,
  1600. on_plot=self.on_plot,
  1601. )[2:]
  1602. self.box.nc = len(self.names)
  1603. self.box.update(results)
  1604. @property
  1605. def keys(self):
  1606. """Returns a list of keys for accessing specific metrics."""
  1607. return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
  1608. def mean_results(self):
  1609. """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95."""
  1610. return self.box.mean_results()
  1611. def class_result(self, i):
  1612. """Return the result of evaluating the performance of an object detection model on a specific class."""
  1613. return self.box.class_result(i)
  1614. @property
  1615. def maps(self):
  1616. """Returns mean Average Precision (mAP) scores per class."""
  1617. return self.box.maps
  1618. @property
  1619. def fitness(self):
  1620. """Returns the fitness of box object."""
  1621. return self.box.fitness()
  1622. @property
  1623. def ap_class_index(self):
  1624. """Returns the average precision index per class."""
  1625. return self.box.ap_class_index
  1626. @property
  1627. def results_dict(self):
  1628. """Returns dictionary of computed performance metrics and statistics."""
  1629. return dict(zip(self.keys + ["fitness"], self.mean_results() + [self.fitness]))
  1630. @property
  1631. def curves(self):
  1632. """Returns a list of curves for accessing specific metrics curves."""
  1633. return []
  1634. @property
  1635. def curves_results(self):
  1636. """Returns a list of curves for accessing specific metrics curves."""
  1637. return []