metrics.py 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970
  1. # Ultralytics YOLO 🚀, AGPL-3.0 license
  2. """
  3. Model validation metrics
  4. """
  5. import math
  6. import warnings
  7. from pathlib import Path
  8. import matplotlib.pyplot as plt
  9. import numpy as np
  10. import torch
  11. from ultralytics.utils import LOGGER, SimpleClass, TryExcept, plt_settings
  12. OKS_SIGMA = np.array([.26, .25, .25, .35, .35, .79, .79, .72, .72, .62, .62, 1.07, 1.07, .87, .87, .89, .89]) / 10.0
  13. def bbox_ioa(box1, box2, iou=False, eps=1e-7):
  14. """
  15. Calculate the intersection over box2 area given box1 and box2. Boxes are in x1y1x2y2 format.
  16. Args:
  17. box1 (np.array): A numpy array of shape (n, 4) representing n bounding boxes.
  18. box2 (np.array): A numpy array of shape (m, 4) representing m bounding boxes.
  19. iou (bool): Calculate the standard iou if True else return inter_area/box2_area.
  20. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  21. Returns:
  22. (np.array): A numpy array of shape (n, m) representing the intersection over box2 area.
  23. """
  24. # Get the coordinates of bounding boxes
  25. b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
  26. b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
  27. # Intersection area
  28. inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * \
  29. (np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)).clip(0)
  30. # box2 area
  31. area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
  32. if iou:
  33. box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
  34. area = area + box1_area[:, None] - inter_area
  35. # Intersection over box2 area
  36. return inter_area / (area + eps)
  37. def box_iou(box1, box2, eps=1e-7):
  38. """
  39. Calculate intersection-over-union (IoU) of boxes.
  40. Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
  41. Based on https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
  42. Args:
  43. box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes.
  44. box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes.
  45. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  46. Returns:
  47. (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.
  48. """
  49. # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
  50. (a1, a2), (b1, b2) = box1.unsqueeze(1).chunk(2, 2), box2.unsqueeze(0).chunk(2, 2)
  51. inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp_(0).prod(2)
  52. # IoU = inter / (area1 + area2 - inter)
  53. return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
  54. def bbox_iou(box1, box2, xywh=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
  55. """
  56. Calculate Intersection over Union (IoU) of box1(1, 4) to box2(n, 4).
  57. Args:
  58. box1 (torch.Tensor): A tensor representing a single bounding box with shape (1, 4).
  59. box2 (torch.Tensor): A tensor representing n bounding boxes with shape (n, 4).
  60. xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in
  61. (x1, y1, x2, y2) format. Defaults to True.
  62. GIoU (bool, optional): If True, calculate Generalized IoU. Defaults to False.
  63. DIoU (bool, optional): If True, calculate Distance IoU. Defaults to False.
  64. CIoU (bool, optional): If True, calculate Complete IoU. Defaults to False.
  65. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  66. Returns:
  67. (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
  68. """
  69. # Get the coordinates of bounding boxes
  70. if xywh: # transform from xywh to xyxy
  71. (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
  72. w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
  73. b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
  74. b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
  75. else: # x1, y1, x2, y2 = box1
  76. b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
  77. b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
  78. w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
  79. w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
  80. # Intersection area
  81. inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * \
  82. (b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)).clamp_(0)
  83. # Union Area
  84. union = w1 * h1 + w2 * h2 - inter + eps
  85. # IoU
  86. iou = inter / union
  87. if CIoU or DIoU or GIoU:
  88. cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
  89. ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
  90. if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
  91. c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
  92. rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 + (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center dist ** 2
  93. if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
  94. v = (4 / math.pi ** 2) * (torch.atan(w2 / h2) - torch.atan(w1 / h1)).pow(2)
  95. with torch.no_grad():
  96. alpha = v / (v - iou + (1 + eps))
  97. return iou - (rho2 / c2 + v * alpha) # CIoU
  98. return iou - rho2 / c2 # DIoU
  99. c_area = cw * ch + eps # convex area
  100. return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
  101. return iou # IoU
  102. def mask_iou(mask1, mask2, eps=1e-7):
  103. """
  104. Calculate masks IoU.
  105. Args:
  106. mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the
  107. product of image width and height.
  108. mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the
  109. product of image width and height.
  110. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  111. Returns:
  112. (torch.Tensor): A tensor of shape (N, M) representing masks IoU.
  113. """
  114. intersection = torch.matmul(mask1, mask2.T).clamp_(0)
  115. union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
  116. return intersection / (union + eps)
  117. def kpt_iou(kpt1, kpt2, area, sigma, eps=1e-7):
  118. """
  119. Calculate Object Keypoint Similarity (OKS).
  120. Args:
  121. kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.
  122. kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.
  123. area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.
  124. sigma (list): A list containing 17 values representing keypoint scales.
  125. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-7.
  126. Returns:
  127. (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.
  128. """
  129. d = (kpt1[:, None, :, 0] - kpt2[..., 0]) ** 2 + (kpt1[:, None, :, 1] - kpt2[..., 1]) ** 2 # (N, M, 17)
  130. sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype) # (17, )
  131. kpt_mask = kpt1[..., 2] != 0 # (N, 17)
  132. e = d / (2 * sigma) ** 2 / (area[:, None, None] + eps) / 2 # from cocoeval
  133. # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2 # from formula
  134. return (torch.exp(-e) * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)
  135. def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
  136. # return positive, negative label smoothing BCE targets
  137. return 1.0 - 0.5 * eps, 0.5 * eps
  138. class ConfusionMatrix:
  139. """
  140. A class for calculating and updating a confusion matrix for object detection and classification tasks.
  141. Attributes:
  142. task (str): The type of task, either 'detect' or 'classify'.
  143. matrix (np.array): The confusion matrix, with dimensions depending on the task.
  144. nc (int): The number of classes.
  145. conf (float): The confidence threshold for detections.
  146. iou_thres (float): The Intersection over Union threshold.
  147. """
  148. def __init__(self, nc, conf=0.25, iou_thres=0.45, task='detect'):
  149. """Initialize attributes for the YOLO model."""
  150. self.task = task
  151. self.matrix = np.zeros((nc + 1, nc + 1)) if self.task == 'detect' else np.zeros((nc, nc))
  152. self.nc = nc # number of classes
  153. self.conf = conf
  154. self.iou_thres = iou_thres
  155. def process_cls_preds(self, preds, targets):
  156. """
  157. Update confusion matrix for classification task
  158. Args:
  159. preds (Array[N, min(nc,5)]): Predicted class labels.
  160. targets (Array[N, 1]): Ground truth class labels.
  161. """
  162. preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)
  163. for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):
  164. self.matrix[p][t] += 1
  165. def process_batch(self, detections, labels):
  166. """
  167. Update confusion matrix for object detection task.
  168. Args:
  169. detections (Array[N, 6]): Detected bounding boxes and their associated information.
  170. Each row should contain (x1, y1, x2, y2, conf, class).
  171. labels (Array[M, 5]): Ground truth bounding boxes and their associated class labels.
  172. Each row should contain (class, x1, y1, x2, y2).
  173. """
  174. if detections is None:
  175. gt_classes = labels.int()
  176. for gc in gt_classes:
  177. self.matrix[self.nc, gc] += 1 # background FN
  178. return
  179. detections = detections[detections[:, 4] > self.conf]
  180. gt_classes = labels[:, 0].int()
  181. detection_classes = detections[:, 5].int()
  182. iou = box_iou(labels[:, 1:], detections[:, :4])
  183. x = torch.where(iou > self.iou_thres)
  184. if x[0].shape[0]:
  185. matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
  186. if x[0].shape[0] > 1:
  187. matches = matches[matches[:, 2].argsort()[::-1]]
  188. matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
  189. matches = matches[matches[:, 2].argsort()[::-1]]
  190. matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
  191. else:
  192. matches = np.zeros((0, 3))
  193. n = matches.shape[0] > 0
  194. m0, m1, _ = matches.transpose().astype(int)
  195. for i, gc in enumerate(gt_classes):
  196. j = m0 == i
  197. if n and sum(j) == 1:
  198. self.matrix[detection_classes[m1[j]], gc] += 1 # correct
  199. else:
  200. self.matrix[self.nc, gc] += 1 # true background
  201. if n:
  202. for i, dc in enumerate(detection_classes):
  203. if not any(m1 == i):
  204. self.matrix[dc, self.nc] += 1 # predicted background
  205. def matrix(self):
  206. """Returns the confusion matrix."""
  207. return self.matrix
  208. def tp_fp(self):
  209. """Returns true positives and false positives."""
  210. tp = self.matrix.diagonal() # true positives
  211. fp = self.matrix.sum(1) - tp # false positives
  212. # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
  213. return (tp[:-1], fp[:-1]) if self.task == 'detect' else (tp, fp) # remove background class if task=detect
  214. @TryExcept('WARNING ⚠️ ConfusionMatrix plot failure')
  215. @plt_settings()
  216. def plot(self, normalize=True, save_dir='', names=(), on_plot=None):
  217. """
  218. Plot the confusion matrix using seaborn and save it to a file.
  219. Args:
  220. normalize (bool): Whether to normalize the confusion matrix.
  221. save_dir (str): Directory where the plot will be saved.
  222. names (tuple): Names of classes, used as labels on the plot.
  223. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  224. """
  225. import seaborn as sn
  226. array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-9) if normalize else 1) # normalize columns
  227. array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
  228. fig, ax = plt.subplots(1, 1, figsize=(12, 9), tight_layout=True)
  229. nc, nn = self.nc, len(names) # number of classes, names
  230. sn.set(font_scale=1.0 if nc < 50 else 0.8) # for label size
  231. labels = (0 < nn < 99) and (nn == nc) # apply names to ticklabels
  232. ticklabels = (list(names) + ['background']) if labels else 'auto'
  233. with warnings.catch_warnings():
  234. warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered
  235. sn.heatmap(array,
  236. ax=ax,
  237. annot=nc < 30,
  238. annot_kws={
  239. 'size': 8},
  240. cmap='Blues',
  241. fmt='.2f' if normalize else '.0f',
  242. square=True,
  243. vmin=0.0,
  244. xticklabels=ticklabels,
  245. yticklabels=ticklabels).set_facecolor((1, 1, 1))
  246. title = 'Confusion Matrix' + ' Normalized' * normalize
  247. ax.set_xlabel('True')
  248. ax.set_ylabel('Predicted')
  249. ax.set_title(title)
  250. plot_fname = Path(save_dir) / f'{title.lower().replace(" ", "_")}.png'
  251. fig.savefig(plot_fname, dpi=250)
  252. plt.close(fig)
  253. if on_plot:
  254. on_plot(plot_fname)
  255. def print(self):
  256. """
  257. Print the confusion matrix to the console.
  258. """
  259. for i in range(self.nc + 1):
  260. LOGGER.info(' '.join(map(str, self.matrix[i])))
  261. def smooth(y, f=0.05):
  262. """Box filter of fraction f."""
  263. nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
  264. p = np.ones(nf // 2) # ones padding
  265. yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
  266. return np.convolve(yp, np.ones(nf) / nf, mode='valid') # y-smoothed
  267. @plt_settings()
  268. def plot_pr_curve(px, py, ap, save_dir=Path('pr_curve.png'), names=(), on_plot=None):
  269. """Plots a precision-recall curve."""
  270. fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
  271. py = np.stack(py, axis=1)
  272. if 0 < len(names) < 21: # display per-class legend if < 21 classes
  273. for i, y in enumerate(py.T):
  274. ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
  275. else:
  276. ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
  277. ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
  278. ax.set_xlabel('Recall')
  279. ax.set_ylabel('Precision')
  280. ax.set_xlim(0, 1)
  281. ax.set_ylim(0, 1)
  282. ax.legend(bbox_to_anchor=(1.04, 1), loc='upper left')
  283. ax.set_title('Precision-Recall Curve')
  284. fig.savefig(save_dir, dpi=250)
  285. plt.close(fig)
  286. if on_plot:
  287. on_plot(save_dir)
  288. @plt_settings()
  289. def plot_mc_curve(px, py, save_dir=Path('mc_curve.png'), names=(), xlabel='Confidence', ylabel='Metric', on_plot=None):
  290. """Plots a metric-confidence curve."""
  291. fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
  292. if 0 < len(names) < 21: # display per-class legend if < 21 classes
  293. for i, y in enumerate(py):
  294. ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
  295. else:
  296. ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
  297. y = smooth(py.mean(0), 0.05)
  298. ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
  299. ax.set_xlabel(xlabel)
  300. ax.set_ylabel(ylabel)
  301. ax.set_xlim(0, 1)
  302. ax.set_ylim(0, 1)
  303. ax.legend(bbox_to_anchor=(1.04, 1), loc='upper left')
  304. ax.set_title(f'{ylabel}-Confidence Curve')
  305. fig.savefig(save_dir, dpi=250)
  306. plt.close(fig)
  307. if on_plot:
  308. on_plot(save_dir)
  309. def compute_ap(recall, precision):
  310. """
  311. Compute the average precision (AP) given the recall and precision curves.
  312. Args:
  313. recall (list): The recall curve.
  314. precision (list): The precision curve.
  315. Returns:
  316. (float): Average precision.
  317. (np.ndarray): Precision envelope curve.
  318. (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.
  319. """
  320. # Append sentinel values to beginning and end
  321. mrec = np.concatenate(([0.0], recall, [1.0]))
  322. mpre = np.concatenate(([1.0], precision, [0.0]))
  323. # Compute the precision envelope
  324. mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
  325. # Integrate area under curve
  326. method = 'interp' # methods: 'continuous', 'interp'
  327. if method == 'interp':
  328. x = np.linspace(0, 1, 101) # 101-point interp (COCO)
  329. ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
  330. else: # 'continuous'
  331. i = np.where(mrec[1:] != mrec[:-1])[0] # points where x-axis (recall) changes
  332. ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
  333. return ap, mpre, mrec
  334. def ap_per_class(tp,
  335. conf,
  336. pred_cls,
  337. target_cls,
  338. plot=False,
  339. on_plot=None,
  340. save_dir=Path(),
  341. names=(),
  342. eps=1e-16,
  343. prefix=''):
  344. """
  345. Computes the average precision per class for object detection evaluation.
  346. Args:
  347. tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).
  348. conf (np.ndarray): Array of confidence scores of the detections.
  349. pred_cls (np.ndarray): Array of predicted classes of the detections.
  350. target_cls (np.ndarray): Array of true classes of the detections.
  351. plot (bool, optional): Whether to plot PR curves or not. Defaults to False.
  352. on_plot (func, optional): A callback to pass plots path and data when they are rendered. Defaults to None.
  353. save_dir (Path, optional): Directory to save the PR curves. Defaults to an empty path.
  354. names (tuple, optional): Tuple of class names to plot PR curves. Defaults to an empty tuple.
  355. eps (float, optional): A small value to avoid division by zero. Defaults to 1e-16.
  356. prefix (str, optional): A prefix string for saving the plot files. Defaults to an empty string.
  357. Returns:
  358. (tuple): A tuple of six arrays and one array of unique classes, where:
  359. tp (np.ndarray): True positive counts for each class.
  360. fp (np.ndarray): False positive counts for each class.
  361. p (np.ndarray): Precision values at each confidence threshold.
  362. r (np.ndarray): Recall values at each confidence threshold.
  363. f1 (np.ndarray): F1-score values at each confidence threshold.
  364. ap (np.ndarray): Average precision for each class at different IoU thresholds.
  365. unique_classes (np.ndarray): An array of unique classes that have data.
  366. """
  367. # Sort by objectness
  368. i = np.argsort(-conf)
  369. tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
  370. # Find unique classes
  371. unique_classes, nt = np.unique(target_cls, return_counts=True)
  372. nc = unique_classes.shape[0] # number of classes, number of detections
  373. # Create Precision-Recall curve and compute AP for each class
  374. px, py = np.linspace(0, 1, 1000), [] # for plotting
  375. ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
  376. for ci, c in enumerate(unique_classes):
  377. i = pred_cls == c
  378. n_l = nt[ci] # number of labels
  379. n_p = i.sum() # number of predictions
  380. if n_p == 0 or n_l == 0:
  381. continue
  382. # Accumulate FPs and TPs
  383. fpc = (1 - tp[i]).cumsum(0)
  384. tpc = tp[i].cumsum(0)
  385. # Recall
  386. recall = tpc / (n_l + eps) # recall curve
  387. r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
  388. # Precision
  389. precision = tpc / (tpc + fpc) # precision curve
  390. p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
  391. # AP from recall-precision curve
  392. for j in range(tp.shape[1]):
  393. ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
  394. if plot and j == 0:
  395. py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
  396. # Compute F1 (harmonic mean of precision and recall)
  397. f1 = 2 * p * r / (p + r + eps)
  398. names = [v for k, v in names.items() if k in unique_classes] # list: only classes that have data
  399. names = dict(enumerate(names)) # to dict
  400. if plot:
  401. plot_pr_curve(px, py, ap, save_dir / f'{prefix}PR_curve.png', names, on_plot=on_plot)
  402. plot_mc_curve(px, f1, save_dir / f'{prefix}F1_curve.png', names, ylabel='F1', on_plot=on_plot)
  403. plot_mc_curve(px, p, save_dir / f'{prefix}P_curve.png', names, ylabel='Precision', on_plot=on_plot)
  404. plot_mc_curve(px, r, save_dir / f'{prefix}R_curve.png', names, ylabel='Recall', on_plot=on_plot)
  405. i = smooth(f1.mean(0), 0.1).argmax() # max F1 index
  406. p, r, f1 = p[:, i], r[:, i], f1[:, i]
  407. tp = (r * nt).round() # true positives
  408. fp = (tp / (p + eps) - tp).round() # false positives
  409. return tp, fp, p, r, f1, ap, unique_classes.astype(int)
  410. class Metric(SimpleClass):
  411. """
  412. Class for computing evaluation metrics for YOLOv8 model.
  413. Attributes:
  414. p (list): Precision for each class. Shape: (nc,).
  415. r (list): Recall for each class. Shape: (nc,).
  416. f1 (list): F1 score for each class. Shape: (nc,).
  417. all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
  418. ap_class_index (list): Index of class for each AP score. Shape: (nc,).
  419. nc (int): Number of classes.
  420. Methods:
  421. ap50(): AP at IoU threshold of 0.5 for all classes. Returns: List of AP scores. Shape: (nc,) or [].
  422. ap(): AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: List of AP scores. Shape: (nc,) or [].
  423. mp(): Mean precision of all classes. Returns: Float.
  424. mr(): Mean recall of all classes. Returns: Float.
  425. map50(): Mean AP at IoU threshold of 0.5 for all classes. Returns: Float.
  426. map75(): Mean AP at IoU threshold of 0.75 for all classes. Returns: Float.
  427. map(): Mean AP at IoU thresholds from 0.5 to 0.95 for all classes. Returns: Float.
  428. mean_results(): Mean of results, returns mp, mr, map50, map.
  429. class_result(i): Class-aware result, returns p[i], r[i], ap50[i], ap[i].
  430. maps(): mAP of each class. Returns: Array of mAP scores, shape: (nc,).
  431. fitness(): Model fitness as a weighted combination of metrics. Returns: Float.
  432. update(results): Update metric attributes with new evaluation results.
  433. """
  434. def __init__(self) -> None:
  435. self.p = [] # (nc, )
  436. self.r = [] # (nc, )
  437. self.f1 = [] # (nc, )
  438. self.all_ap = [] # (nc, 10)
  439. self.ap_class_index = [] # (nc, )
  440. self.nc = 0
  441. @property
  442. def ap50(self):
  443. """
  444. Returns the Average Precision (AP) at an IoU threshold of 0.5 for all classes.
  445. Returns:
  446. (np.ndarray, list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.
  447. """
  448. return self.all_ap[:, 0] if len(self.all_ap) else []
  449. @property
  450. def ap(self):
  451. """
  452. Returns the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.
  453. Returns:
  454. (np.ndarray, list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.
  455. """
  456. return self.all_ap.mean(1) if len(self.all_ap) else []
  457. @property
  458. def mp(self):
  459. """
  460. Returns the Mean Precision of all classes.
  461. Returns:
  462. (float): The mean precision of all classes.
  463. """
  464. return self.p.mean() if len(self.p) else 0.0
  465. @property
  466. def mr(self):
  467. """
  468. Returns the Mean Recall of all classes.
  469. Returns:
  470. (float): The mean recall of all classes.
  471. """
  472. return self.r.mean() if len(self.r) else 0.0
  473. @property
  474. def map50(self):
  475. """
  476. Returns the mean Average Precision (mAP) at an IoU threshold of 0.5.
  477. Returns:
  478. (float): The mAP50 at an IoU threshold of 0.5.
  479. """
  480. return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0
  481. @property
  482. def map75(self):
  483. """
  484. Returns the mean Average Precision (mAP) at an IoU threshold of 0.75.
  485. Returns:
  486. (float): The mAP50 at an IoU threshold of 0.75.
  487. """
  488. return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0
  489. @property
  490. def map(self):
  491. """
  492. Returns the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
  493. Returns:
  494. (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
  495. """
  496. return self.all_ap.mean() if len(self.all_ap) else 0.0
  497. def mean_results(self):
  498. """Mean of results, return mp, mr, map50, map."""
  499. return [self.mp, self.mr, self.map50, self.map]
  500. def class_result(self, i):
  501. """class-aware result, return p[i], r[i], ap50[i], ap[i]."""
  502. return self.p[i], self.r[i], self.ap50[i], self.ap[i]
  503. @property
  504. def maps(self):
  505. """mAP of each class."""
  506. maps = np.zeros(self.nc) + self.map
  507. for i, c in enumerate(self.ap_class_index):
  508. maps[c] = self.ap[i]
  509. return maps
  510. def fitness(self):
  511. """Model fitness as a weighted combination of metrics."""
  512. w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
  513. return (np.array(self.mean_results()) * w).sum()
  514. def update(self, results):
  515. """
  516. Args:
  517. results (tuple): A tuple of (p, r, ap, f1, ap_class)
  518. """
  519. self.p, self.r, self.f1, self.all_ap, self.ap_class_index = results
  520. class DetMetrics(SimpleClass):
  521. """
  522. This class is a utility class for computing detection metrics such as precision, recall, and mean average precision
  523. (mAP) of an object detection model.
  524. Args:
  525. save_dir (Path): A path to the directory where the output plots will be saved. Defaults to current directory.
  526. plot (bool): A flag that indicates whether to plot precision-recall curves for each class. Defaults to False.
  527. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  528. names (tuple of str): A tuple of strings that represents the names of the classes. Defaults to an empty tuple.
  529. Attributes:
  530. save_dir (Path): A path to the directory where the output plots will be saved.
  531. plot (bool): A flag that indicates whether to plot the precision-recall curves for each class.
  532. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  533. names (tuple of str): A tuple of strings that represents the names of the classes.
  534. box (Metric): An instance of the Metric class for storing the results of the detection metrics.
  535. speed (dict): A dictionary for storing the execution time of different parts of the detection process.
  536. Methods:
  537. process(tp, conf, pred_cls, target_cls): Updates the metric results with the latest batch of predictions.
  538. keys: Returns a list of keys for accessing the computed detection metrics.
  539. mean_results: Returns a list of mean values for the computed detection metrics.
  540. class_result(i): Returns a list of values for the computed detection metrics for a specific class.
  541. maps: Returns a dictionary of mean average precision (mAP) values for different IoU thresholds.
  542. fitness: Computes the fitness score based on the computed detection metrics.
  543. ap_class_index: Returns a list of class indices sorted by their average precision (AP) values.
  544. results_dict: Returns a dictionary that maps detection metric keys to their computed values.
  545. """
  546. def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:
  547. self.save_dir = save_dir
  548. self.plot = plot
  549. self.on_plot = on_plot
  550. self.names = names
  551. self.box = Metric()
  552. self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}
  553. def process(self, tp, conf, pred_cls, target_cls):
  554. """Process predicted results for object detection and update metrics."""
  555. results = ap_per_class(tp,
  556. conf,
  557. pred_cls,
  558. target_cls,
  559. plot=self.plot,
  560. save_dir=self.save_dir,
  561. names=self.names,
  562. on_plot=self.on_plot)[2:]
  563. self.box.nc = len(self.names)
  564. self.box.update(results)
  565. @property
  566. def keys(self):
  567. """Returns a list of keys for accessing specific metrics."""
  568. return ['metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)']
  569. def mean_results(self):
  570. """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95."""
  571. return self.box.mean_results()
  572. def class_result(self, i):
  573. """Return the result of evaluating the performance of an object detection model on a specific class."""
  574. return self.box.class_result(i)
  575. @property
  576. def maps(self):
  577. """Returns mean Average Precision (mAP) scores per class."""
  578. return self.box.maps
  579. @property
  580. def fitness(self):
  581. """Returns the fitness of box object."""
  582. return self.box.fitness()
  583. @property
  584. def ap_class_index(self):
  585. """Returns the average precision index per class."""
  586. return self.box.ap_class_index
  587. @property
  588. def results_dict(self):
  589. """Returns dictionary of computed performance metrics and statistics."""
  590. return dict(zip(self.keys + ['fitness'], self.mean_results() + [self.fitness]))
  591. class SegmentMetrics(SimpleClass):
  592. """
  593. Calculates and aggregates detection and segmentation metrics over a given set of classes.
  594. Args:
  595. save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.
  596. plot (bool): Whether to save the detection and segmentation plots. Default is False.
  597. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  598. names (list): List of class names. Default is an empty list.
  599. Attributes:
  600. save_dir (Path): Path to the directory where the output plots should be saved.
  601. plot (bool): Whether to save the detection and segmentation plots.
  602. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  603. names (list): List of class names.
  604. box (Metric): An instance of the Metric class to calculate box detection metrics.
  605. seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.
  606. speed (dict): Dictionary to store the time taken in different phases of inference.
  607. Methods:
  608. process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.
  609. mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.
  610. class_result(i): Returns the detection and segmentation metrics of class `i`.
  611. maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.
  612. fitness: Returns the fitness scores, which are a single weighted combination of metrics.
  613. ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).
  614. results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.
  615. """
  616. def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:
  617. self.save_dir = save_dir
  618. self.plot = plot
  619. self.on_plot = on_plot
  620. self.names = names
  621. self.box = Metric()
  622. self.seg = Metric()
  623. self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}
  624. def process(self, tp_b, tp_m, conf, pred_cls, target_cls):
  625. """
  626. Processes the detection and segmentation metrics over the given set of predictions.
  627. Args:
  628. tp_b (list): List of True Positive boxes.
  629. tp_m (list): List of True Positive masks.
  630. conf (list): List of confidence scores.
  631. pred_cls (list): List of predicted classes.
  632. target_cls (list): List of target classes.
  633. """
  634. results_mask = ap_per_class(tp_m,
  635. conf,
  636. pred_cls,
  637. target_cls,
  638. plot=self.plot,
  639. on_plot=self.on_plot,
  640. save_dir=self.save_dir,
  641. names=self.names,
  642. prefix='Mask')[2:]
  643. self.seg.nc = len(self.names)
  644. self.seg.update(results_mask)
  645. results_box = ap_per_class(tp_b,
  646. conf,
  647. pred_cls,
  648. target_cls,
  649. plot=self.plot,
  650. on_plot=self.on_plot,
  651. save_dir=self.save_dir,
  652. names=self.names,
  653. prefix='Box')[2:]
  654. self.box.nc = len(self.names)
  655. self.box.update(results_box)
  656. @property
  657. def keys(self):
  658. """Returns a list of keys for accessing metrics."""
  659. return [
  660. 'metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)',
  661. 'metrics/precision(M)', 'metrics/recall(M)', 'metrics/mAP50(M)', 'metrics/mAP50-95(M)']
  662. def mean_results(self):
  663. """Return the mean metrics for bounding box and segmentation results."""
  664. return self.box.mean_results() + self.seg.mean_results()
  665. def class_result(self, i):
  666. """Returns classification results for a specified class index."""
  667. return self.box.class_result(i) + self.seg.class_result(i)
  668. @property
  669. def maps(self):
  670. """Returns mAP scores for object detection and semantic segmentation models."""
  671. return self.box.maps + self.seg.maps
  672. @property
  673. def fitness(self):
  674. """Get the fitness score for both segmentation and bounding box models."""
  675. return self.seg.fitness() + self.box.fitness()
  676. @property
  677. def ap_class_index(self):
  678. """Boxes and masks have the same ap_class_index."""
  679. return self.box.ap_class_index
  680. @property
  681. def results_dict(self):
  682. """Returns results of object detection model for evaluation."""
  683. return dict(zip(self.keys + ['fitness'], self.mean_results() + [self.fitness]))
  684. class PoseMetrics(SegmentMetrics):
  685. """
  686. Calculates and aggregates detection and pose metrics over a given set of classes.
  687. Args:
  688. save_dir (Path): Path to the directory where the output plots should be saved. Default is the current directory.
  689. plot (bool): Whether to save the detection and segmentation plots. Default is False.
  690. on_plot (func): An optional callback to pass plots path and data when they are rendered. Defaults to None.
  691. names (list): List of class names. Default is an empty list.
  692. Attributes:
  693. save_dir (Path): Path to the directory where the output plots should be saved.
  694. plot (bool): Whether to save the detection and segmentation plots.
  695. on_plot (func): An optional callback to pass plots path and data when they are rendered.
  696. names (list): List of class names.
  697. box (Metric): An instance of the Metric class to calculate box detection metrics.
  698. pose (Metric): An instance of the Metric class to calculate mask segmentation metrics.
  699. speed (dict): Dictionary to store the time taken in different phases of inference.
  700. Methods:
  701. process(tp_m, tp_b, conf, pred_cls, target_cls): Processes metrics over the given set of predictions.
  702. mean_results(): Returns the mean of the detection and segmentation metrics over all the classes.
  703. class_result(i): Returns the detection and segmentation metrics of class `i`.
  704. maps: Returns the mean Average Precision (mAP) scores for IoU thresholds ranging from 0.50 to 0.95.
  705. fitness: Returns the fitness scores, which are a single weighted combination of metrics.
  706. ap_class_index: Returns the list of indices of classes used to compute Average Precision (AP).
  707. results_dict: Returns the dictionary containing all the detection and segmentation metrics and fitness score.
  708. """
  709. def __init__(self, save_dir=Path('.'), plot=False, on_plot=None, names=()) -> None:
  710. super().__init__(save_dir, plot, names)
  711. self.save_dir = save_dir
  712. self.plot = plot
  713. self.on_plot = on_plot
  714. self.names = names
  715. self.box = Metric()
  716. self.pose = Metric()
  717. self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}
  718. def process(self, tp_b, tp_p, conf, pred_cls, target_cls):
  719. """
  720. Processes the detection and pose metrics over the given set of predictions.
  721. Args:
  722. tp_b (list): List of True Positive boxes.
  723. tp_p (list): List of True Positive keypoints.
  724. conf (list): List of confidence scores.
  725. pred_cls (list): List of predicted classes.
  726. target_cls (list): List of target classes.
  727. """
  728. results_pose = ap_per_class(tp_p,
  729. conf,
  730. pred_cls,
  731. target_cls,
  732. plot=self.plot,
  733. on_plot=self.on_plot,
  734. save_dir=self.save_dir,
  735. names=self.names,
  736. prefix='Pose')[2:]
  737. self.pose.nc = len(self.names)
  738. self.pose.update(results_pose)
  739. results_box = ap_per_class(tp_b,
  740. conf,
  741. pred_cls,
  742. target_cls,
  743. plot=self.plot,
  744. on_plot=self.on_plot,
  745. save_dir=self.save_dir,
  746. names=self.names,
  747. prefix='Box')[2:]
  748. self.box.nc = len(self.names)
  749. self.box.update(results_box)
  750. @property
  751. def keys(self):
  752. """Returns list of evaluation metric keys."""
  753. return [
  754. 'metrics/precision(B)', 'metrics/recall(B)', 'metrics/mAP50(B)', 'metrics/mAP50-95(B)',
  755. 'metrics/precision(P)', 'metrics/recall(P)', 'metrics/mAP50(P)', 'metrics/mAP50-95(P)']
  756. def mean_results(self):
  757. """Return the mean results of box and pose."""
  758. return self.box.mean_results() + self.pose.mean_results()
  759. def class_result(self, i):
  760. """Return the class-wise detection results for a specific class i."""
  761. return self.box.class_result(i) + self.pose.class_result(i)
  762. @property
  763. def maps(self):
  764. """Returns the mean average precision (mAP) per class for both box and pose detections."""
  765. return self.box.maps + self.pose.maps
  766. @property
  767. def fitness(self):
  768. """Computes classification metrics and speed using the `targets` and `pred` inputs."""
  769. return self.pose.fitness() + self.box.fitness()
  770. class ClassifyMetrics(SimpleClass):
  771. """
  772. Class for computing classification metrics including top-1 and top-5 accuracy.
  773. Attributes:
  774. top1 (float): The top-1 accuracy.
  775. top5 (float): The top-5 accuracy.
  776. speed (Dict[str, float]): A dictionary containing the time taken for each step in the pipeline.
  777. Properties:
  778. fitness (float): The fitness of the model, which is equal to top-5 accuracy.
  779. results_dict (Dict[str, Union[float, str]]): A dictionary containing the classification metrics and fitness.
  780. keys (List[str]): A list of keys for the results_dict.
  781. Methods:
  782. process(targets, pred): Processes the targets and predictions to compute classification metrics.
  783. """
  784. def __init__(self) -> None:
  785. self.top1 = 0
  786. self.top5 = 0
  787. self.speed = {'preprocess': 0.0, 'inference': 0.0, 'loss': 0.0, 'postprocess': 0.0}
  788. def process(self, targets, pred):
  789. """Target classes and predicted classes."""
  790. pred, targets = torch.cat(pred), torch.cat(targets)
  791. correct = (targets[:, None] == pred).float()
  792. acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
  793. self.top1, self.top5 = acc.mean(0).tolist()
  794. @property
  795. def fitness(self):
  796. """Returns mean of top-1 and top-5 accuracies as fitness score."""
  797. return (self.top1 + self.top5) / 2
  798. @property
  799. def results_dict(self):
  800. """Returns a dictionary with model's performance metrics and fitness score."""
  801. return dict(zip(self.keys + ['fitness'], [self.top1, self.top5, self.fitness]))
  802. @property
  803. def keys(self):
  804. """Returns a list of keys for the results_dict property."""
  805. return ['metrics/accuracy_top1', 'metrics/accuracy_top5']