metrics.py 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308
  1. # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/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. OKS_SIGMA = (
  11. 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])
  12. / 10.0
  13. )
  14. def bbox_ioa(box1, box2, iou=False, eps=1e-7):
  15. """
  16. Calculate the intersection over box2 area given box1 and box2. Boxes are in x1y1x2y2 format.
  17. Args:
  18. box1 (np.ndarray): A numpy array of shape (n, 4) representing n bounding boxes.
  19. box2 (np.ndarray): A numpy array of shape (m, 4) representing m bounding boxes.
  20. iou (bool): Calculate the standard IoU if True else return inter_area/box2_area.
  21. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  22. Returns:
  23. (np.ndarray): A numpy array of shape (n, m) representing the intersection over box2 area.
  24. """
  25. # Get the coordinates of bounding boxes
  26. b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
  27. b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
  28. # Intersection area
  29. inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * (
  30. np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)
  31. ).clip(0)
  32. # Box2 area
  33. area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
  34. if iou:
  35. box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
  36. area = area + box1_area[:, None] - inter_area
  37. # Intersection over box2 area
  38. return inter_area / (area + eps)
  39. def box_iou(box1, box2, eps=1e-7):
  40. """
  41. Calculate intersection-over-union (IoU) of boxes. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
  42. Based on https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py.
  43. Args:
  44. box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes.
  45. box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes.
  46. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  47. Returns:
  48. (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.
  49. """
  50. # NOTE: Need .float() to get accurate iou values
  51. # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
  52. (a1, a2), (b1, b2) = box1.float().unsqueeze(1).chunk(2, 2), box2.float().unsqueeze(0).chunk(2, 2)
  53. inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp_(0).prod(2)
  54. # IoU = inter / (area1 + area2 - inter)
  55. return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
  56. def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
  57. """
  58. Calculates the Intersection over Union (IoU) between bounding boxes.
  59. This function supports various shapes for `box1` and `box2` as long as the last dimension is 4.
  60. For instance, you may pass tensors shaped like (4,), (N, 4), (B, N, 4), or (B, N, 1, 4).
  61. Internally, the code will split the last dimension into (x, y, w, h) if `xywh=True`,
  62. or (x1, y1, x2, y2) if `xywh=False`.
  63. Args:
  64. box1 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
  65. box2 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
  66. xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in
  67. (x1, y1, x2, y2) format. Defaults to True.
  68. GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.
  69. DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.
  70. CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.
  71. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  72. Returns:
  73. (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
  74. """
  75. # Get the coordinates of bounding boxes
  76. if xywh: # transform from xywh to xyxy
  77. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  78. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  79. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  80. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  81. else: # x1, y1, x2, y2 = box1
  82. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  83. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  84. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  85. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  86. # Intersection area
  87. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * (
  88. b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)
  89. ).clamp_(0)
  90. # Union Area
  91. union = w1 * h1 + w2 * h2 - inter + eps
  92. # IoU
  93. iou = inter / union
  94. if CIoU or DIoU or GIoU:
  95. cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
  96. ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
  97. if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  98. c2 = cw.pow(2) + ch.pow(2) + eps # convex diagonal squared
  99. rho2 = (
  100. (b2_x1 + b2_x2 - b1_x1 - b1_x2).pow(2) + (b2_y1 + b2_y2 - b1_y1 - b1_y2).pow(2)
  101. ) / 4 # center dist**2
  102. if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  103. v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
  104. with torch.no_grad():
  105. alpha = v / (v - iou + (1 + eps))
  106. return iou - (rho2 / c2 + v * alpha) # CIoU
  107. return iou - rho2 / c2 # DIoU
  108. c_area = cw * ch + eps # convex area
  109. return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
  110. return iou # IoU
  111. def mask_iou(mask1, mask2, eps=1e-7):
  112. """
  113. Calculate masks IoU.
  114. Args:
  115. mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the
  116. product of image width and height.
  117. mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the
  118. product of image width and height.
  119. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  120. Returns:
  121. (torch.Tensor): A tensor of shape (N, M) representing masks IoU.
  122. """
  123. intersection = torch.matmul(mask1, mask2.T).clamp_(0)
  124. union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
  125. return intersection / (union + eps)
  126. def kpt_iou(kpt1, kpt2, area, sigma, eps=1e-7):
  127. """
  128. Calculate Object Keypoint Similarity (OKS).
  129. Args:
  130. kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.
  131. kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.
  132. area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.
  133. sigma (list): A list containing 17 values representing keypoint scales.
  134. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  135. Returns:
  136. (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.
  137. """
  138. d = (kpt1[:, None, :, 0] - kpt2[..., 0]).pow(2) + (kpt1[:, None, :, 1] - kpt2[..., 1]).pow(2) # (N, M, 17)
  139. sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype) # (17, )
  140. kpt_mask = kpt1[..., 2] != 0 # (N, 17)
  141. e = d / ((2 * sigma).pow(2) * (area[:, None, None] + eps) * 2) # from cocoeval
  142. # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2 # from formula
  143. return ((-e).exp() * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)
  144. def _get_covariance_matrix(boxes):
  145. """
  146. Generating covariance matrix from obbs.
  147. Args:
  148. boxes (torch.Tensor): A tensor of shape (N, 5) representing rotated bounding boxes, with xywhr format.
  149. Returns:
  150. (torch.Tensor): Covariance matrices corresponding to original rotated bounding boxes.
  151. """
  152. # Gaussian bounding boxes, ignore the center points (the first two columns) because they are not needed here.
  153. gbbs = torch.cat((boxes[:, 2:4].pow(2) / 12, boxes[:, 4:]), dim=-1)
  154. a, b, c = gbbs.split(1, dim=-1)
  155. cos = c.cos()
  156. sin = c.sin()
  157. cos2 = cos.pow(2)
  158. sin2 = sin.pow(2)
  159. return a * cos2 + b * sin2, a * sin2 + b * cos2, (a - b) * cos * sin
  160. def probiou(obb1, obb2, CIoU=False, eps=1e-7):
  161. """
  162. Calculate probabilistic IoU between oriented bounding boxes.
  163. Implements the algorithm from https://arxiv.org/pdf/2106.06072v1.pdf.
  164. Args:
  165. obb1 (torch.Tensor): Ground truth OBBs, shape (N, 5), format xywhr.
  166. obb2 (torch.Tensor): Predicted OBBs, shape (N, 5), format xywhr.
  167. CIoU (bool, optional): If True, calculate CIoU. Defaults to False.
  168. eps (float, optional): Small value to avoid division by zero. Defaults to 1e-7.
  169. Returns:
  170. (torch.Tensor): OBB similarities, shape (N,).
  171. Note:
  172. OBB format: [center_x, center_y, width, height, rotation_angle].
  173. If CIoU is True, returns CIoU instead of IoU.
  174. """
  175. x1, y1 = obb1[..., :2].split(1, dim=-1)
  176. x2, y2 = obb2[..., :2].split(1, dim=-1)
  177. a1, b1, c1 = _get_covariance_matrix(obb1)
  178. a2, b2, c2 = _get_covariance_matrix(obb2)
  179. t1 = (
  180. ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
  181. ) * 0.25
  182. t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
  183. t3 = (
  184. ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
  185. / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
  186. + eps
  187. ).log() * 0.5
  188. bd = (t1 + t2 + t3).clamp(eps, 100.0)
  189. hd = (1.0 - (-bd).exp() + eps).sqrt()
  190. iou = 1 - hd
  191. if CIoU: # only include the wh aspect ratio part
  192. w1, h1 = obb1[..., 2:4].split(1, dim=-1)
  193. w2, h2 = obb2[..., 2:4].split(1, dim=-1)
  194. v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
  195. with torch.no_grad():
  196. alpha = v / (v - iou + (1 + eps))
  197. return iou - v * alpha # CIoU
  198. return iou
  199. def batch_probiou(obb1, obb2, eps=1e-7):
  200. """
  201. Calculate the prob IoU between oriented bounding boxes, https://arxiv.org/pdf/2106.06072v1.pdf.
  202. Args:
  203. obb1 (torch.Tensor | np.ndarray): A tensor of shape (N, 5) representing ground truth obbs, with xywhr format.
  204. obb2 (torch.Tensor | np.ndarray): A tensor of shape (M, 5) representing predicted obbs, with xywhr format.
  205. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  206. Returns:
  207. (torch.Tensor): A tensor of shape (N, M) representing obb similarities.
  208. """
  209. obb1 = torch.from_numpy(obb1) if isinstance(obb1, np.ndarray) else obb1
  210. obb2 = torch.from_numpy(obb2) if isinstance(obb2, np.ndarray) else obb2
  211. x1, y1 = obb1[..., :2].split(1, dim=-1)
  212. x2, y2 = (x.squeeze(-1)[None] for x in obb2[..., :2].split(1, dim=-1))
  213. a1, b1, c1 = _get_covariance_matrix(obb1)
  214. a2, b2, c2 = (x.squeeze(-1)[None] for x in _get_covariance_matrix(obb2))
  215. t1 = (
  216. ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
  217. ) * 0.25
  218. t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
  219. t3 = (
  220. ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
  221. / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
  222. + eps
  223. ).log() * 0.5
  224. bd = (t1 + t2 + t3).clamp(eps, 100.0)
  225. hd = (1.0 - (-bd).exp() + eps).sqrt()
  226. return 1 - hd
  227. def smooth_bce(eps=0.1):
  228. """
  229. Computes smoothed positive and negative Binary Cross-Entropy targets.
  230. This function calculates positive and negative label smoothing BCE targets based on a given epsilon value.
  231. For implementation details, refer to https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441.
  232. Args:
  233. eps (float, optional): The epsilon value for label smoothing. Defaults to 0.1.
  234. Returns:
  235. (tuple): A tuple containing the positive and negative label smoothing BCE targets.
  236. """
  237. return 1.0 - 0.5 * eps, 0.5 * eps
  238. class ConfusionMatrix:
  239. """
  240. A class for calculating and updating a confusion matrix for object detection and classification tasks.
  241. Attributes:
  242. task (str): The type of task, either 'detect' or 'classify'.
  243. matrix (np.ndarray): The confusion matrix, with dimensions depending on the task.
  244. nc (int): The number of classes.
  245. conf (float): The confidence threshold for detections.
  246. iou_thres (float): The Intersection over Union threshold.
  247. """
  248. def __init__(self, nc, conf=0.25, iou_thres=0.45, task="detect"):
  249. """Initialize attributes for the YOLO model."""
  250. self.task = task
  251. self.matrix = np.zeros((nc + 1, nc + 1)) if self.task == "detect" else np.zeros((nc, nc))
  252. self.nc = nc # number of classes
  253. self.conf = 0.25 if conf in {None, 0.001} else conf # apply 0.25 if default val conf is passed
  254. self.iou_thres = iou_thres
  255. def process_cls_preds(self, preds, targets):
  256. """
  257. Update confusion matrix for classification task.
  258. Args:
  259. preds (Array[N, min(nc,5)]): Predicted class labels.
  260. targets (Array[N, 1]): Ground truth class labels.
  261. """
  262. preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)
  263. for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):
  264. self.matrix[p][t] += 1
  265. def process_batch(self, detections, gt_bboxes, gt_cls):
  266. """
  267. Update confusion matrix for object detection task.
  268. Args:
  269. detections (Array[N, 6] | Array[N, 7]): Detected bounding boxes and their associated information.
  270. Each row should contain (x1, y1, x2, y2, conf, class)
  271. or with an additional element `angle` when it's obb.
  272. gt_bboxes (Array[M, 4]| Array[N, 5]): Ground truth bounding boxes with xyxy/xyxyr format.
  273. gt_cls (Array[M]): The class labels.
  274. """
  275. if gt_cls.shape[0] == 0: # Check if labels is empty
  276. if detections is not None:
  277. detections = detections[detections[:, 4] > self.conf]
  278. detection_classes = detections[:, 5].int()
  279. for dc in detection_classes:
  280. self.matrix[dc, self.nc] += 1 # false positives
  281. return
  282. if detections is None:
  283. gt_classes = gt_cls.int()
  284. for gc in gt_classes:
  285. self.matrix[self.nc, gc] += 1 # background FN
  286. return
  287. detections = detections[detections[:, 4] > self.conf]
  288. gt_classes = gt_cls.int()
  289. detection_classes = detections[:, 5].int()
  290. is_obb = detections.shape[1] == 7 and gt_bboxes.shape[1] == 5 # with additional `angle` dimension
  291. iou = (
  292. batch_probiou(gt_bboxes, torch.cat([detections[:, :4], detections[:, -1:]], dim=-1))
  293. if is_obb
  294. else box_iou(gt_bboxes, detections[:, :4])
  295. )
  296. x = torch.where(iou > self.iou_thres)
  297. if x[0].shape[0]:
  298. matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
  299. if x[0].shape[0] > 1:
  300. matches = matches[matches[:, 2].argsort()[::-1]]
  301. matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
  302. matches = matches[matches[:, 2].argsort()[::-1]]
  303. matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
  304. else:
  305. matches = np.zeros((0, 3))
  306. n = matches.shape[0] > 0
  307. m0, m1, _ = matches.transpose().astype(int)
  308. for i, gc in enumerate(gt_classes):
  309. j = m0 == i
  310. if n and sum(j) == 1:
  311. self.matrix[detection_classes[m1[j]], gc] += 1 # correct
  312. else:
  313. self.matrix[self.nc, gc] += 1 # true background
  314. for i, dc in enumerate(detection_classes):
  315. if not any(m1 == i):
  316. self.matrix[dc, self.nc] += 1 # predicted background
  317. def matrix(self):
  318. """Returns the confusion matrix."""
  319. return self.matrix
  320. def tp_fp(self):
  321. """Returns true positives and false positives."""
  322. tp = self.matrix.diagonal() # true positives
  323. fp = self.matrix.sum(1) - tp # false positives
  324. # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
  325. return (tp[:-1], fp[:-1]) if self.task == "detect" else (tp, fp) # remove background class if task=detect
  326. @TryExcept("WARNING ⚠️ ConfusionMatrix plot failure")
  327. @plt_settings()
  328. def plot(self, normalize=True, save_dir="", names=(), on_plot=None):
  329. """
  330. Plot the confusion matrix using seaborn and save it to a file.
  331. Args:
  332. normalize (bool): Whether to normalize the confusion matrix.
  333. save_dir (str): Directory where the plot will be saved.
  334. names (tuple): Names of classes, used as labels on the plot.
  335. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  336. """
  337. import seaborn # scope for faster 'import ultralytics'
  338. array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1) # normalize columns
  339. array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
  340. fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)
  341. nc, nn = self.nc, len(names) # number of classes, names
  342. seaborn.set_theme(font_scale=1.0 if nc < 50 else 0.8) # for label size
  343. labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
  344. ticklabels = (list(names) + ["background"]) if labels else "auto"
  345. with warnings.catch_warnings():
  346. warnings.simplefilter("ignore") # suppress empty matrix RuntimeWarning: All-NaN slice encountered
  347. seaborn.heatmap(
  348. array,
  349. ax=ax,
  350. annot=nc < 30,
  351. annot_kws={"size": 8},
  352. cmap="Blues",
  353. fmt=".2f" if normalize else ".0f",
  354. square=True,
  355. vmin=0.0,
  356. xticklabels=ticklabels,
  357. yticklabels=ticklabels,
  358. ).set_facecolor((1, 1, 1))
  359. title = "Confusion Matrix" + " Normalized" * normalize
  360. ax.set_xlabel("True")
  361. ax.set_ylabel("Predicted")
  362. ax.set_title(title)
  363. plot_fname = Path(save_dir) / f"{title.lower().replace(' ', '_')}.png"
  364. fig.savefig(plot_fname, dpi=250)
  365. plt.close(fig)
  366. if on_plot:
  367. on_plot(plot_fname)
  368. def print(self):
  369. """Print the confusion matrix to the console."""
  370. for i in range(self.nc + 1):
  371. LOGGER.info(" ".join(map(str, self.matrix[i])))
  372. def smooth(y, f=0.05):
  373. """Box filter of fraction f."""
  374. nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
  375. p = np.ones(nf // 2) # ones padding
  376. yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
  377. return np.convolve(yp, np.ones(nf) / nf, mode="valid") # y-smoothed
  378. @plt_settings()
  379. def plot_pr_curve(px, py, ap, save_dir=Path("pr_curve.png"), names={}, on_plot=None):
  380. """Plots a precision-recall curve."""
  381. fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
  382. py = np.stack(py, axis=1)
  383. if 0 < len(names) < 21: # display per-class legend if < 21 classes
  384. for i, y in enumerate(py.T):
  385. ax.plot(px, y, linewidth=1, label=f"{names[i]} {ap[i, 0]:.3f}") # plot(recall, precision)
  386. else:
  387. ax.plot(px, py, linewidth=1, color="grey") # plot(recall, precision)
  388. ax.plot(px, py.mean(1), linewidth=3, color="blue", label=f"all classes {ap[:, 0].mean():.3f} mAP@0.5")
  389. ax.set_xlabel("Recall")
  390. ax.set_ylabel("Precision")
  391. ax.set_xlim(0, 1)
  392. ax.set_ylim(0, 1)
  393. ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
  394. ax.set_title("Precision-Recall Curve")
  395. fig.savefig(save_dir, dpi=250)
  396. plt.close(fig)
  397. if on_plot:
  398. on_plot(save_dir)
  399. @plt_settings()
  400. def plot_mc_curve(px, py, save_dir=Path("mc_curve.png"), names={}, xlabel="Confidence", ylabel="Metric", on_plot=None):
  401. """Plots a metric-confidence curve."""
  402. fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
  403. if 0 < len(names) < 21: # display per-class legend if < 21 classes
  404. for i, y in enumerate(py):
  405. ax.plot(px, y, linewidth=1, label=f"{names[i]}") # plot(confidence, metric)
  406. else:
  407. ax.plot(px, py.T, linewidth=1, color="grey") # plot(confidence, metric)
  408. y = smooth(py.mean(0), 0.05)
  409. ax.plot(px, y, linewidth=3, color="blue", label=f"all classes {y.max():.2f} at {px[y.argmax()]:.3f}")
  410. ax.set_xlabel(xlabel)
  411. ax.set_ylabel(ylabel)
  412. ax.set_xlim(0, 1)
  413. ax.set_ylim(0, 1)
  414. ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
  415. ax.set_title(f"{ylabel}-Confidence Curve")
  416. fig.savefig(save_dir, dpi=250)
  417. plt.close(fig)
  418. if on_plot:
  419. on_plot(save_dir)
  420. def compute_ap(recall, precision):
  421. """
  422. Compute the average precision (AP) given the recall and precision curves.
  423. Args:
  424. recall (list): The recall curve.
  425. precision (list): The precision curve.
  426. Returns:
  427. (float): Average precision.
  428. (np.ndarray): Precision envelope curve.
  429. (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.
  430. """
  431. # Append sentinel values to beginning and end
  432. mrec = np.concatenate(([0.0], recall, [1.0]))
  433. mpre = np.concatenate(([1.0], precision, [0.0]))
  434. # Compute the precision envelope
  435. mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
  436. # Integrate area under curve
  437. method = "interp" # methods: 'continuous', 'interp'
  438. if method == "interp":
  439. x = np.linspace(0, 1, 101) # 101-point interp (COCO)
  440. ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
  441. else: # 'continuous'
  442. i = np.where(mrec[1:] != mrec[:-1])[0] # points where x-axis (recall) changes
  443. ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
  444. return ap, mpre, mrec
  445. def ap_per_class(
  446. tp, conf, pred_cls, target_cls, plot=False, on_plot=None, save_dir=Path(), names={}, eps=1e-16, prefix=""
  447. ):
  448. """
  449. Computes the average precision per class for object detection evaluation.
  450. Args:
  451. tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).
  452. conf (np.ndarray): Array of confidence scores of the detections.
  453. pred_cls (np.ndarray): Array of predicted classes of the detections.
  454. target_cls (np.ndarray): Array of true classes of the detections.
  455. plot (bool, optional): Whether to plot PR curves or not. Defaults to False.
  456. on_plot (func, optional): A callback to pass plots path and data when they are rendered. Defaults to None.
  457. save_dir (Path, optional): Directory to save the PR curves. Defaults to an empty path.
  458. names (dict, optional): Dict of class names to plot PR curves. Defaults to an empty tuple.
  459. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-16.
  460. prefix (str, optional): A prefix string for saving the plot files. Defaults to an empty string.
  461. Returns:
  462. tp (np.ndarray): True positive counts at threshold given by max F1 metric for each class.Shape: (nc,).
  463. fp (np.ndarray): False positive counts at threshold given by max F1 metric for each class. Shape: (nc,).
  464. p (np.ndarray): Precision values at threshold given by max F1 metric for each class. Shape: (nc,).
  465. r (np.ndarray): Recall values at threshold given by max F1 metric for each class. Shape: (nc,).
  466. f1 (np.ndarray): F1-score values at threshold given by max F1 metric for each class. Shape: (nc,).
  467. ap (np.ndarray): Average precision for each class at different IoU thresholds. Shape: (nc, 10).
  468. unique_classes (np.ndarray): An array of unique classes that have data. Shape: (nc,).
  469. p_curve (np.ndarray): Precision curves for each class. Shape: (nc, 1000).
  470. r_curve (np.ndarray): Recall curves for each class. Shape: (nc, 1000).
  471. f1_curve (np.ndarray): F1-score curves for each class. Shape: (nc, 1000).
  472. x (np.ndarray): X-axis values for the curves. Shape: (1000,).
  473. prec_values (np.ndarray): Precision values at mAP@0.5 for each class. Shape: (nc, 1000).
  474. """
  475. # Sort by objectness
  476. i = np.argsort(-conf)
  477. tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
  478. # Find unique classes
  479. unique_classes, nt = np.unique(target_cls, return_counts=True)
  480. nc = unique_classes.shape[0] # number of classes, number of detections
  481. # Create Precision-Recall curve and compute AP for each class
  482. x, prec_values = np.linspace(0, 1, 1000), []
  483. # Average precision, precision and recall curves
  484. ap, p_curve, r_curve = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
  485. for ci, c in enumerate(unique_classes):
  486. i = pred_cls == c
  487. n_l = nt[ci] # number of labels
  488. n_p = i.sum() # number of predictions
  489. if n_p == 0 or n_l == 0:
  490. continue
  491. # Accumulate FPs and TPs
  492. fpc = (1 - tp[i]).cumsum(0)
  493. tpc = tp[i].cumsum(0)
  494. # Recall
  495. recall = tpc / (n_l + eps) # recall curve
  496. r_curve[ci] = np.interp(-x, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
  497. # Precision
  498. precision = tpc / (tpc + fpc) # precision curve
  499. p_curve[ci] = np.interp(-x, -conf[i], precision[:, 0], left=1) # p at pr_score
  500. # AP from recall-precision curve
  501. for j in range(tp.shape[1]):
  502. ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
  503. if j == 0:
  504. prec_values.append(np.interp(x, mrec, mpre)) # precision at mAP@0.5
  505. prec_values = np.array(prec_values) # (nc, 1000)
  506. # Compute F1 (harmonic mean of precision and recall)
  507. f1_curve = 2 * p_curve * r_curve / (p_curve + r_curve + eps)
  508. names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data
  509. names = dict(enumerate(names)) # to dict
  510. if plot:
  511. plot_pr_curve(x, prec_values, ap, save_dir / f"{prefix}PR_curve.png", names, on_plot=on_plot)
  512. plot_mc_curve(x, f1_curve, save_dir / f"{prefix}F1_curve.png", names, ylabel="F1", on_plot=on_plot)
  513. plot_mc_curve(x, p_curve, save_dir / f"{prefix}P_curve.png", names, ylabel="Precision", on_plot=on_plot)
  514. plot_mc_curve(x, r_curve, save_dir / f"{prefix}R_curve.png", names, ylabel="Recall", on_plot=on_plot)
  515. i = smooth(f1_curve.mean(0), 0.1).argmax() # max F1 index
  516. p, r, f1 = p_curve[:, i], r_curve[:, i], f1_curve[:, i] # max-F1 precision, recall, F1 values
  517. tp = (r * nt).round() # true positives
  518. fp = (tp / (p + eps) - tp).round() # false positives
  519. return tp, fp, p, r, f1, ap, unique_classes.astype(int), p_curve, r_curve, f1_curve, x, prec_values
  520. class Metric(SimpleClass):
  521. """
  522. Class for computing evaluation metrics for YOLOv8 model.
  523. Attributes:
  524. p (list): Precision for each class. Shape: (nc,).
  525. r (list): Recall for each class. Shape: (nc,).
  526. f1 (list): F1 score for each class. Shape: (nc,).
  527. all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
  528. ap_class_index (list): Index of class for each AP score. Shape: (nc,).
  529. nc (int): Number of classes.
  530. Methods:
  531. ap50(): AP at IoU threshold of 0.5 for all classes. Returns: List of AP scores. Shape: (nc,) or [].
  532. ap(): AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: List of AP scores. Shape: (nc,) or [].
  533. mp(): Mean precision of all classes. Returns: Float.
  534. mr(): Mean recall of all classes. Returns: Float.
  535. map50(): Mean AP at IoU threshold of 0.5 for all classes. Returns: Float.
  536. map75(): Mean AP at IoU threshold of 0.75 for all classes. Returns: Float.
  537. map(): Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: Float.
  538. mean_results(): Mean of results, returns mp, mr, map50, map.
  539. class_result(i): Class-aware result, returns p[i], r[i], ap50[i], ap[i].
  540. maps(): mAP of each class. Returns: Array of mAP scores, shape: (nc,).
  541. fitness(): Model fitness as a weighted combination of metrics. Returns: Float.
  542. update(results): Update metric attributes with new evaluation results.
  543. """
  544. def __init__(self) -> None:
  545. """Initializes a Metric instance for computing evaluation metrics for the YOLOv8 model."""
  546. self.p = [] # (nc, )
  547. self.r = [] # (nc, )
  548. self.f1 = [] # (nc, )
  549. self.all_ap = [] # (nc, 10)
  550. self.ap_class_index = [] # (nc, )
  551. self.nc = 0
  552. @property
  553. def ap50(self):
  554. """
  555. Returns the Average Precision (AP) at an IoU threshold of 0.5 for all classes.
  556. Returns:
  557. (np.ndarray, list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.
  558. """
  559. return self.all_ap[:, 0] if len(self.all_ap) else []
  560. @property
  561. def ap75(self):
  562. """
  563. Returns the Average Precision (AP) at an IoU threshold of 0.75 for all classes.
  564. Returns:
  565. (np.ndarray, list): Array of shape (nc,) with AP75 values per class, or an empty list if not available.
  566. """
  567. return self.all_ap[:, 5] if len(self.all_ap) else []
  568. @property
  569. def ap(self):
  570. """
  571. Returns the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.
  572. Returns:
  573. (np.ndarray, list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.
  574. """
  575. return self.all_ap.mean(1) if len(self.all_ap) else []
  576. @property
  577. def mp(self):
  578. """
  579. Returns the Mean Precision of all classes.
  580. Returns:
  581. (float): The mean precision of all classes.
  582. """
  583. return self.p.mean() if len(self.p) else 0.0
  584. @property
  585. def mr(self):
  586. """
  587. Returns the Mean Recall of all classes.
  588. Returns:
  589. (float): The mean recall of all classes.
  590. """
  591. return self.r.mean() if len(self.r) else 0.0
  592. @property
  593. def map50(self):
  594. """
  595. Returns the mean Average Precision (mAP) at an IoU threshold of 0.5.
  596. Returns:
  597. (float): The mAP at an IoU threshold of 0.5.
  598. """
  599. return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0
  600. @property
  601. def map75(self):
  602. """
  603. Returns the mean Average Precision (mAP) at an IoU threshold of 0.75.
  604. Returns:
  605. (float): The mAP at an IoU threshold of 0.75.
  606. """
  607. return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0
  608. @property
  609. def map(self):
  610. """
  611. Returns the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
  612. Returns:
  613. (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
  614. """
  615. return self.all_ap.mean() if len(self.all_ap) else 0.0
  616. def mean_results(self):
  617. """Mean of results, return mp, mr, map50, map."""
  618. return [self.mp, self.mr, self.map50, self.map75,self.map]
  619. def class_result(self, i):
  620. """Class-aware result, return p[i], r[i], ap50[i], ap[i]."""
  621. return self.p[i], self.r[i], self.ap50[i], self.ap75[i], self.ap[i]
  622. @property
  623. def maps(self):
  624. """MAP of each class."""
  625. maps = np.zeros(self.nc) + self.map
  626. for i, c in enumerate(self.ap_class_index):
  627. maps[c] = self.ap[i]
  628. return maps
  629. def fitness(self):
  630. """Model fitness as a weighted combination of metrics."""
  631. w = [0.0, 0.0, 0.0, 0.0, 1.0] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
  632. return (np.array(self.mean_results()) * w).sum()
  633. def update(self, results):
  634. """
  635. Updates the evaluation metrics of the model with a new set of results.
  636. Args:
  637. results (tuple): A tuple containing the following evaluation metrics:
  638. - p (list): Precision for each class. Shape: (nc,).
  639. - r (list): Recall for each class. Shape: (nc,).
  640. - f1 (list): F1 score for each class. Shape: (nc,).
  641. - all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
  642. - ap_class_index (list): Index of class for each AP score. Shape: (nc,).
  643. Side Effects:
  644. Updates the class attributes `self.p`, `self.r`, `self.f1`, `self.all_ap`, and `self.ap_class_index` based
  645. on the values provided in the `results` tuple.
  646. """
  647. (
  648. self.p,
  649. self.r,
  650. self.f1,
  651. self.all_ap,
  652. self.ap_class_index,
  653. self.p_curve,
  654. self.r_curve,
  655. self.f1_curve,
  656. self.px,
  657. self.prec_values,
  658. ) = results
  659. @property
  660. def curves(self):
  661. """Returns a list of curves for accessing specific metrics curves."""
  662. return []
  663. @property
  664. def curves_results(self):
  665. """Returns a list of curves for accessing specific metrics curves."""
  666. return [
  667. [self.px, self.prec_values, "Recall", "Precision"],
  668. [self.px, self.f1_curve, "Confidence", "F1"],
  669. [self.px, self.p_curve, "Confidence", "Precision"],
  670. [self.px, self.r_curve, "Confidence", "Recall"],
  671. ]
  672. class DetMetrics(SimpleClass):
  673. """
  674. Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP) of an
  675. object detection model.
  676. Args:
  677. save_dir (Path): A path to the directory where the output plots will be saved. Defaults to current directory.
  678. plot (bool): A flag that indicates whether to plot precision-recall curves for each class. Defaults to False.
  679. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  680. names (dict of str): A dict of strings that represents the names of the classes. Defaults to an empty tuple.
  681. Attributes:
  682. save_dir (Path): A path to the directory where the output plots will be saved.
  683. plot (bool): A flag that indicates whether to plot the precision-recall curves for each class.
  684. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  685. names (dict of str): A dict of strings that represents the names of the classes.
  686. box (Metric): An instance of the Metric class for storing the results of the detection metrics.
  687. speed (dict): A dictionary for storing the execution time of different parts of the detection process.
  688. Methods:
  689. process(tp, conf, pred_cls, target_cls): Updates the metric results with the latest batch of predictions.
  690. keys: Returns a list of keys for accessing the computed detection metrics.
  691. mean_results: Returns a list of mean values for the computed detection metrics.
  692. class_result(i): Returns a list of values for the computed detection metrics for a specific class.
  693. maps: Returns a dictionary of mean average precision (mAP) values for different IoU thresholds.
  694. fitness: Computes the fitness score based on the computed detection metrics.
  695. ap_class_index: Returns a list of class indices sorted by their average precision (AP) values.
  696. results_dict: Returns a dictionary that maps detection metric keys to their computed values.
  697. curves: TODO
  698. curves_results: TODO
  699. """
  700. def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names={}) -> None:
  701. """Initialize a DetMetrics instance with a save directory, plot flag, callback function, and class names."""
  702. self.save_dir = save_dir
  703. self.plot = plot
  704. self.on_plot = on_plot
  705. self.names = names
  706. self.box = Metric()
  707. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  708. self.task = "detect"
  709. def process(self, tp, conf, pred_cls, target_cls):
  710. """Process predicted results for object detection and update metrics."""
  711. results = ap_per_class(
  712. tp,
  713. conf,
  714. pred_cls,
  715. target_cls,
  716. plot=self.plot,
  717. save_dir=self.save_dir,
  718. names=self.names,
  719. on_plot=self.on_plot,
  720. )[2:]
  721. self.box.nc = len(self.names)
  722. self.box.update(results)
  723. @property
  724. def keys(self):
  725. """Returns a list of keys for accessing specific metrics."""
  726. return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP75(B)", "metrics/mAP50-95(B)"]
  727. def mean_results(self):
  728. """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95."""
  729. return self.box.mean_results()
  730. def class_result(self, i):
  731. """Return the result of evaluating the performance of an object detection model on a specific class."""
  732. return self.box.class_result(i)
  733. @property
  734. def maps(self):
  735. """Returns mean Average Precision (mAP) scores per class."""
  736. return self.box.maps
  737. @property
  738. def fitness(self):
  739. """Returns the fitness of box object."""
  740. return self.box.fitness()
  741. @property
  742. def ap_class_index(self):
  743. """Returns the average precision index per class."""
  744. return self.box.ap_class_index
  745. @property
  746. def results_dict(self):
  747. """Returns dictionary of computed performance metrics and statistics."""
  748. return dict(zip(self.keys + ["fitness"], self.mean_results() + [self.fitness]))
  749. @property
  750. def curves(self):
  751. """Returns a list of curves for accessing specific metrics curves."""
  752. return ["Precision-Recall(B)", "F1-Confidence(B)", "Precision-Confidence(B)", "Recall-Confidence(B)"]
  753. @property
  754. def curves_results(self):
  755. """Returns dictionary of computed performance metrics and statistics."""
  756. return self.box.curves_results
  757. class SegmentMetrics(SimpleClass):
  758. """
  759. Calculates and aggregates detection and segmentation metrics over a given set of classes.
  760. Args:
  761. save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.
  762. plot (bool): Whether to save the detection and segmentation plots. Default is False.
  763. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  764. names (list): List of class names. Default is an empty list.
  765. Attributes:
  766. save_dir (Path): Path to the directory where the output plots should be saved.
  767. plot (bool): Whether to save the detection and segmentation plots.
  768. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  769. names (list): List of class names.
  770. box (Metric): An instance of the Metric class to calculate box detection metrics.
  771. seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.
  772. speed (dict): Dictionary to store the time taken in different phases of inference.
  773. Methods:
  774. process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.
  775. mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.
  776. class_result(i): Returns the detection and segmentation metrics of class `i`.
  777. maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.
  778. fitness: Returns the fitness scores, which are a single weighted combination of metrics.
  779. ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).
  780. results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.
  781. """
  782. def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names=()) -> None:
  783. """Initialize a SegmentMetrics instance with a save directory, plot flag, callback function, and class names."""
  784. self.save_dir = save_dir
  785. self.plot = plot
  786. self.on_plot = on_plot
  787. self.names = names
  788. self.box = Metric()
  789. self.seg = Metric()
  790. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  791. self.task = "segment"
  792. def process(self, tp, tp_m, conf, pred_cls, target_cls):
  793. """
  794. Processes the detection and segmentation metrics over the given set of predictions.
  795. Args:
  796. tp (list): List of True Positive boxes.
  797. tp_m (list): List of True Positive masks.
  798. conf (list): List of confidence scores.
  799. pred_cls (list): List of predicted classes.
  800. target_cls (list): List of target classes.
  801. """
  802. results_mask = ap_per_class(
  803. tp_m,
  804. conf,
  805. pred_cls,
  806. target_cls,
  807. plot=self.plot,
  808. on_plot=self.on_plot,
  809. save_dir=self.save_dir,
  810. names=self.names,
  811. prefix="Mask",
  812. )[2:]
  813. self.seg.nc = len(self.names)
  814. self.seg.update(results_mask)
  815. results_box = ap_per_class(
  816. tp,
  817. conf,
  818. pred_cls,
  819. target_cls,
  820. plot=self.plot,
  821. on_plot=self.on_plot,
  822. save_dir=self.save_dir,
  823. names=self.names,
  824. prefix="Box",
  825. )[2:]
  826. self.box.nc = len(self.names)
  827. self.box.update(results_box)
  828. @property
  829. def keys(self):
  830. """Returns a list of keys for accessing metrics."""
  831. return [
  832. "metrics/precision(B)",
  833. "metrics/recall(B)",
  834. "metrics/mAP50(B)",
  835. "metrics/mAP75(B)",
  836. "metrics/mAP50-95(B)",
  837. "metrics/precision(M)",
  838. "metrics/recall(M)",
  839. "metrics/mAP50(M)",
  840. "metrics/mAP75(M)",
  841. "metrics/mAP50-95(M)",
  842. ]
  843. def mean_results(self):
  844. """Return the mean metrics for bounding box and segmentation results."""
  845. return self.box.mean_results() + self.seg.mean_results()
  846. def class_result(self, i):
  847. """Returns classification results for a specified class index."""
  848. return self.box.class_result(i) + self.seg.class_result(i)
  849. @property
  850. def maps(self):
  851. """Returns mAP scores for object detection and semantic segmentation models."""
  852. return self.box.maps + self.seg.maps
  853. @property
  854. def fitness(self):
  855. """Get the fitness score for both segmentation and bounding box models."""
  856. return self.seg.fitness() + self.box.fitness()
  857. @property
  858. def ap_class_index(self):
  859. """Boxes and masks have the same ap_class_index."""
  860. return self.box.ap_class_index
  861. @property
  862. def results_dict(self):
  863. """Returns results of object detection model for evaluation."""
  864. return dict(zip(self.keys + ["fitness"], self.mean_results() + [self.fitness]))
  865. @property
  866. def curves(self):
  867. """Returns a list of curves for accessing specific metrics curves."""
  868. return [
  869. "Precision-Recall(B)",
  870. "F1-Confidence(B)",
  871. "Precision-Confidence(B)",
  872. "Recall-Confidence(B)",
  873. "Precision-Recall(M)",
  874. "F1-Confidence(M)",
  875. "Precision-Confidence(M)",
  876. "Recall-Confidence(M)",
  877. ]
  878. @property
  879. def curves_results(self):
  880. """Returns dictionary of computed performance metrics and statistics."""
  881. return self.box.curves_results + self.seg.curves_results
  882. class PoseMetrics(SegmentMetrics):
  883. """
  884. Calculates and aggregates detection and pose metrics over a given set of classes.
  885. Args:
  886. save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.
  887. plot (bool): Whether to save the detection and segmentation plots. Default is False.
  888. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  889. names (list): List of class names. Default is an empty list.
  890. Attributes:
  891. save_dir (Path): Path to the directory where the output plots should be saved.
  892. plot (bool): Whether to save the detection and segmentation plots.
  893. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  894. names (list): List of class names.
  895. box (Metric): An instance of the Metric class to calculate box detection metrics.
  896. pose (Metric): An instance of the Metric class to calculate mask segmentation metrics.
  897. speed (dict): Dictionary to store the time taken in different phases of inference.
  898. Methods:
  899. process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.
  900. mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.
  901. class_result(i): Returns the detection and segmentation metrics of class `i`.
  902. maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.
  903. fitness: Returns the fitness scores, which are a single weighted combination of metrics.
  904. ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).
  905. results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.
  906. """
  907. def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names=()) -> None:
  908. """Initialize the PoseMetrics class with directory path, class names, and plotting options."""
  909. super().__init__(save_dir, plot, names)
  910. self.save_dir = save_dir
  911. self.plot = plot
  912. self.on_plot = on_plot
  913. self.names = names
  914. self.box = Metric()
  915. self.pose = Metric()
  916. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  917. self.task = "pose"
  918. def process(self, tp, tp_p, conf, pred_cls, target_cls):
  919. """
  920. Processes the detection and pose metrics over the given set of predictions.
  921. Args:
  922. tp (list): List of True Positive boxes.
  923. tp_p (list): List of True Positive keypoints.
  924. conf (list): List of confidence scores.
  925. pred_cls (list): List of predicted classes.
  926. target_cls (list): List of target classes.
  927. """
  928. results_pose = ap_per_class(
  929. tp_p,
  930. conf,
  931. pred_cls,
  932. target_cls,
  933. plot=self.plot,
  934. on_plot=self.on_plot,
  935. save_dir=self.save_dir,
  936. names=self.names,
  937. prefix="Pose",
  938. )[2:]
  939. self.pose.nc = len(self.names)
  940. self.pose.update(results_pose)
  941. results_box = ap_per_class(
  942. tp,
  943. conf,
  944. pred_cls,
  945. target_cls,
  946. plot=self.plot,
  947. on_plot=self.on_plot,
  948. save_dir=self.save_dir,
  949. names=self.names,
  950. prefix="Box",
  951. )[2:]
  952. self.box.nc = len(self.names)
  953. self.box.update(results_box)
  954. @property
  955. def keys(self):
  956. """Returns list of evaluation metric keys."""
  957. return [
  958. "metrics/precision(B)",
  959. "metrics/recall(B)",
  960. "metrics/mAP50(B)",
  961. "metrics/mAP75(B)",
  962. "metrics/mAP50-95(B)",
  963. "metrics/precision(P)",
  964. "metrics/recall(P)",
  965. "metrics/mAP50(P)",
  966. "metrics/mAP75(P)",
  967. "metrics/mAP50-95(P)",
  968. ]
  969. def mean_results(self):
  970. """Return the mean results of box and pose."""
  971. return self.box.mean_results() + self.pose.mean_results()
  972. def class_result(self, i):
  973. """Return the class-wise detection results for a specific class i."""
  974. return self.box.class_result(i) + self.pose.class_result(i)
  975. @property
  976. def maps(self):
  977. """Returns the mean average precision (mAP) per class for both box and pose detections."""
  978. return self.box.maps + self.pose.maps
  979. @property
  980. def fitness(self):
  981. """Computes classification metrics and speed using the `targets` and `pred` inputs."""
  982. return self.pose.fitness() + self.box.fitness()
  983. @property
  984. def curves(self):
  985. """Returns a list of curves for accessing specific metrics curves."""
  986. return [
  987. "Precision-Recall(B)",
  988. "F1-Confidence(B)",
  989. "Precision-Confidence(B)",
  990. "Recall-Confidence(B)",
  991. "Precision-Recall(P)",
  992. "F1-Confidence(P)",
  993. "Precision-Confidence(P)",
  994. "Recall-Confidence(P)",
  995. ]
  996. @property
  997. def curves_results(self):
  998. """Returns dictionary of computed performance metrics and statistics."""
  999. return self.box.curves_results + self.pose.curves_results
  1000. class ClassifyMetrics(SimpleClass):
  1001. """
  1002. Class for computing classification metrics including top-1 and top-5 accuracy.
  1003. Attributes:
  1004. top1 (float): The top-1 accuracy.
  1005. top5 (float): The top-5 accuracy.
  1006. speed (Dict[str, float]): A dictionary containing the time taken for each step in the pipeline.
  1007. fitness (float): The fitness of the model, which is equal to top-5 accuracy.
  1008. results_dict (Dict[str, Union[float, str]]): A dictionary containing the classification metrics and fitness.
  1009. keys (List[str]): A list of keys for the results_dict.
  1010. Methods:
  1011. process(targets, pred): Processes the targets and predictions to compute classification metrics.
  1012. """
  1013. def __init__(self) -> None:
  1014. """Initialize a ClassifyMetrics instance."""
  1015. self.top1 = 0
  1016. self.top5 = 0
  1017. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  1018. self.task = "classify"
  1019. def process(self, targets, pred):
  1020. """Target classes and predicted classes."""
  1021. pred, targets = torch.cat(pred), torch.cat(targets)
  1022. correct = (targets[:, None] == pred).float()
  1023. acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
  1024. self.top1, self.top5 = acc.mean(0).tolist()
  1025. @property
  1026. def fitness(self):
  1027. """Returns mean of top-1 and top-5 accuracies as fitness score."""
  1028. return (self.top1 + self.top5) / 2
  1029. @property
  1030. def results_dict(self):
  1031. """Returns a dictionary with model's performance metrics and fitness score."""
  1032. return dict(zip(self.keys + ["fitness"], [self.top1, self.top5, self.fitness]))
  1033. @property
  1034. def keys(self):
  1035. """Returns a list of keys for the results_dict property."""
  1036. return ["metrics/accuracy_top1", "metrics/accuracy_top5"]
  1037. @property
  1038. def curves(self):
  1039. """Returns a list of curves for accessing specific metrics curves."""
  1040. return []
  1041. @property
  1042. def curves_results(self):
  1043. """Returns a list of curves for accessing specific metrics curves."""
  1044. return []
  1045. class OBBMetrics(SimpleClass):
  1046. """Metrics for evaluating oriented bounding box (OBB) detection, see https://arxiv.org/pdf/2106.06072.pdf."""
  1047. def __init__(self, save_dir=Path("."), plot=False, on_plot=None, names=()) -> None:
  1048. """Initialize an OBBMetrics instance with directory, plotting, callback, and class names."""
  1049. self.save_dir = save_dir
  1050. self.plot = plot
  1051. self.on_plot = on_plot
  1052. self.names = names
  1053. self.box = Metric()
  1054. self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
  1055. def process(self, tp, conf, pred_cls, target_cls):
  1056. """Process predicted results for object detection and update metrics."""
  1057. results = ap_per_class(
  1058. tp,
  1059. conf,
  1060. pred_cls,
  1061. target_cls,
  1062. plot=self.plot,
  1063. save_dir=self.save_dir,
  1064. names=self.names,
  1065. on_plot=self.on_plot,
  1066. )[2:]
  1067. self.box.nc = len(self.names)
  1068. self.box.update(results)
  1069. @property
  1070. def keys(self):
  1071. """Returns a list of keys for accessing specific metrics."""
  1072. return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
  1073. def mean_results(self):
  1074. """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95."""
  1075. return self.box.mean_results()
  1076. def class_result(self, i):
  1077. """Return the result of evaluating the performance of an object detection model on a specific class."""
  1078. return self.box.class_result(i)
  1079. @property
  1080. def maps(self):
  1081. """Returns mean Average Precision (mAP) scores per class."""
  1082. return self.box.maps
  1083. @property
  1084. def fitness(self):
  1085. """Returns the fitness of box object."""
  1086. return self.box.fitness()
  1087. @property
  1088. def ap_class_index(self):
  1089. """Returns the average precision index per class."""
  1090. return self.box.ap_class_index
  1091. @property
  1092. def results_dict(self):
  1093. """Returns dictionary of computed performance metrics and statistics."""
  1094. return dict(zip(self.keys + ["fitness"], self.mean_results() + [self.fitness]))
  1095. @property
  1096. def curves(self):
  1097. """Returns a list of curves for accessing specific metrics curves."""
  1098. return []
  1099. @property
  1100. def curves_results(self):
  1101. """Returns a list of curves for accessing specific metrics curves."""
  1102. return []