ultralytics-opencv-headless 8.3.246__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. tests/__init__.py +23 -0
  2. tests/conftest.py +59 -0
  3. tests/test_cli.py +131 -0
  4. tests/test_cuda.py +216 -0
  5. tests/test_engine.py +157 -0
  6. tests/test_exports.py +309 -0
  7. tests/test_integrations.py +151 -0
  8. tests/test_python.py +777 -0
  9. tests/test_solutions.py +371 -0
  10. ultralytics/__init__.py +48 -0
  11. ultralytics/assets/bus.jpg +0 -0
  12. ultralytics/assets/zidane.jpg +0 -0
  13. ultralytics/cfg/__init__.py +1026 -0
  14. ultralytics/cfg/datasets/Argoverse.yaml +78 -0
  15. ultralytics/cfg/datasets/DOTAv1.5.yaml +37 -0
  16. ultralytics/cfg/datasets/DOTAv1.yaml +36 -0
  17. ultralytics/cfg/datasets/GlobalWheat2020.yaml +68 -0
  18. ultralytics/cfg/datasets/HomeObjects-3K.yaml +32 -0
  19. ultralytics/cfg/datasets/ImageNet.yaml +2025 -0
  20. ultralytics/cfg/datasets/Objects365.yaml +447 -0
  21. ultralytics/cfg/datasets/SKU-110K.yaml +58 -0
  22. ultralytics/cfg/datasets/VOC.yaml +102 -0
  23. ultralytics/cfg/datasets/VisDrone.yaml +87 -0
  24. ultralytics/cfg/datasets/african-wildlife.yaml +25 -0
  25. ultralytics/cfg/datasets/brain-tumor.yaml +22 -0
  26. ultralytics/cfg/datasets/carparts-seg.yaml +44 -0
  27. ultralytics/cfg/datasets/coco-pose.yaml +64 -0
  28. ultralytics/cfg/datasets/coco.yaml +118 -0
  29. ultralytics/cfg/datasets/coco128-seg.yaml +101 -0
  30. ultralytics/cfg/datasets/coco128.yaml +101 -0
  31. ultralytics/cfg/datasets/coco8-grayscale.yaml +103 -0
  32. ultralytics/cfg/datasets/coco8-multispectral.yaml +104 -0
  33. ultralytics/cfg/datasets/coco8-pose.yaml +47 -0
  34. ultralytics/cfg/datasets/coco8-seg.yaml +101 -0
  35. ultralytics/cfg/datasets/coco8.yaml +101 -0
  36. ultralytics/cfg/datasets/construction-ppe.yaml +32 -0
  37. ultralytics/cfg/datasets/crack-seg.yaml +22 -0
  38. ultralytics/cfg/datasets/dog-pose.yaml +52 -0
  39. ultralytics/cfg/datasets/dota8-multispectral.yaml +38 -0
  40. ultralytics/cfg/datasets/dota8.yaml +35 -0
  41. ultralytics/cfg/datasets/hand-keypoints.yaml +50 -0
  42. ultralytics/cfg/datasets/kitti.yaml +27 -0
  43. ultralytics/cfg/datasets/lvis.yaml +1240 -0
  44. ultralytics/cfg/datasets/medical-pills.yaml +21 -0
  45. ultralytics/cfg/datasets/open-images-v7.yaml +663 -0
  46. ultralytics/cfg/datasets/package-seg.yaml +22 -0
  47. ultralytics/cfg/datasets/signature.yaml +21 -0
  48. ultralytics/cfg/datasets/tiger-pose.yaml +41 -0
  49. ultralytics/cfg/datasets/xView.yaml +155 -0
  50. ultralytics/cfg/default.yaml +130 -0
  51. ultralytics/cfg/models/11/yolo11-cls-resnet18.yaml +17 -0
  52. ultralytics/cfg/models/11/yolo11-cls.yaml +33 -0
  53. ultralytics/cfg/models/11/yolo11-obb.yaml +50 -0
  54. ultralytics/cfg/models/11/yolo11-pose.yaml +51 -0
  55. ultralytics/cfg/models/11/yolo11-seg.yaml +50 -0
  56. ultralytics/cfg/models/11/yolo11.yaml +50 -0
  57. ultralytics/cfg/models/11/yoloe-11-seg.yaml +48 -0
  58. ultralytics/cfg/models/11/yoloe-11.yaml +48 -0
  59. ultralytics/cfg/models/12/yolo12-cls.yaml +32 -0
  60. ultralytics/cfg/models/12/yolo12-obb.yaml +48 -0
  61. ultralytics/cfg/models/12/yolo12-pose.yaml +49 -0
  62. ultralytics/cfg/models/12/yolo12-seg.yaml +48 -0
  63. ultralytics/cfg/models/12/yolo12.yaml +48 -0
  64. ultralytics/cfg/models/rt-detr/rtdetr-l.yaml +53 -0
  65. ultralytics/cfg/models/rt-detr/rtdetr-resnet101.yaml +45 -0
  66. ultralytics/cfg/models/rt-detr/rtdetr-resnet50.yaml +45 -0
  67. ultralytics/cfg/models/rt-detr/rtdetr-x.yaml +57 -0
  68. ultralytics/cfg/models/v10/yolov10b.yaml +45 -0
  69. ultralytics/cfg/models/v10/yolov10l.yaml +45 -0
  70. ultralytics/cfg/models/v10/yolov10m.yaml +45 -0
  71. ultralytics/cfg/models/v10/yolov10n.yaml +45 -0
  72. ultralytics/cfg/models/v10/yolov10s.yaml +45 -0
  73. ultralytics/cfg/models/v10/yolov10x.yaml +45 -0
  74. ultralytics/cfg/models/v3/yolov3-spp.yaml +49 -0
  75. ultralytics/cfg/models/v3/yolov3-tiny.yaml +40 -0
  76. ultralytics/cfg/models/v3/yolov3.yaml +49 -0
  77. ultralytics/cfg/models/v5/yolov5-p6.yaml +62 -0
  78. ultralytics/cfg/models/v5/yolov5.yaml +51 -0
  79. ultralytics/cfg/models/v6/yolov6.yaml +56 -0
  80. ultralytics/cfg/models/v8/yoloe-v8-seg.yaml +48 -0
  81. ultralytics/cfg/models/v8/yoloe-v8.yaml +48 -0
  82. ultralytics/cfg/models/v8/yolov8-cls-resnet101.yaml +28 -0
  83. ultralytics/cfg/models/v8/yolov8-cls-resnet50.yaml +28 -0
  84. ultralytics/cfg/models/v8/yolov8-cls.yaml +32 -0
  85. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +58 -0
  86. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +60 -0
  87. ultralytics/cfg/models/v8/yolov8-ghost.yaml +50 -0
  88. ultralytics/cfg/models/v8/yolov8-obb.yaml +49 -0
  89. ultralytics/cfg/models/v8/yolov8-p2.yaml +57 -0
  90. ultralytics/cfg/models/v8/yolov8-p6.yaml +59 -0
  91. ultralytics/cfg/models/v8/yolov8-pose-p6.yaml +60 -0
  92. ultralytics/cfg/models/v8/yolov8-pose.yaml +50 -0
  93. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +49 -0
  94. ultralytics/cfg/models/v8/yolov8-seg-p6.yaml +59 -0
  95. ultralytics/cfg/models/v8/yolov8-seg.yaml +49 -0
  96. ultralytics/cfg/models/v8/yolov8-world.yaml +51 -0
  97. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +49 -0
  98. ultralytics/cfg/models/v8/yolov8.yaml +49 -0
  99. ultralytics/cfg/models/v9/yolov9c-seg.yaml +41 -0
  100. ultralytics/cfg/models/v9/yolov9c.yaml +41 -0
  101. ultralytics/cfg/models/v9/yolov9e-seg.yaml +64 -0
  102. ultralytics/cfg/models/v9/yolov9e.yaml +64 -0
  103. ultralytics/cfg/models/v9/yolov9m.yaml +41 -0
  104. ultralytics/cfg/models/v9/yolov9s.yaml +41 -0
  105. ultralytics/cfg/models/v9/yolov9t.yaml +41 -0
  106. ultralytics/cfg/trackers/botsort.yaml +21 -0
  107. ultralytics/cfg/trackers/bytetrack.yaml +12 -0
  108. ultralytics/data/__init__.py +26 -0
  109. ultralytics/data/annotator.py +66 -0
  110. ultralytics/data/augment.py +2801 -0
  111. ultralytics/data/base.py +435 -0
  112. ultralytics/data/build.py +437 -0
  113. ultralytics/data/converter.py +855 -0
  114. ultralytics/data/dataset.py +834 -0
  115. ultralytics/data/loaders.py +704 -0
  116. ultralytics/data/scripts/download_weights.sh +18 -0
  117. ultralytics/data/scripts/get_coco.sh +61 -0
  118. ultralytics/data/scripts/get_coco128.sh +18 -0
  119. ultralytics/data/scripts/get_imagenet.sh +52 -0
  120. ultralytics/data/split.py +138 -0
  121. ultralytics/data/split_dota.py +344 -0
  122. ultralytics/data/utils.py +798 -0
  123. ultralytics/engine/__init__.py +1 -0
  124. ultralytics/engine/exporter.py +1578 -0
  125. ultralytics/engine/model.py +1124 -0
  126. ultralytics/engine/predictor.py +508 -0
  127. ultralytics/engine/results.py +1522 -0
  128. ultralytics/engine/trainer.py +974 -0
  129. ultralytics/engine/tuner.py +448 -0
  130. ultralytics/engine/validator.py +384 -0
  131. ultralytics/hub/__init__.py +166 -0
  132. ultralytics/hub/auth.py +151 -0
  133. ultralytics/hub/google/__init__.py +174 -0
  134. ultralytics/hub/session.py +422 -0
  135. ultralytics/hub/utils.py +162 -0
  136. ultralytics/models/__init__.py +9 -0
  137. ultralytics/models/fastsam/__init__.py +7 -0
  138. ultralytics/models/fastsam/model.py +79 -0
  139. ultralytics/models/fastsam/predict.py +169 -0
  140. ultralytics/models/fastsam/utils.py +23 -0
  141. ultralytics/models/fastsam/val.py +38 -0
  142. ultralytics/models/nas/__init__.py +7 -0
  143. ultralytics/models/nas/model.py +98 -0
  144. ultralytics/models/nas/predict.py +56 -0
  145. ultralytics/models/nas/val.py +38 -0
  146. ultralytics/models/rtdetr/__init__.py +7 -0
  147. ultralytics/models/rtdetr/model.py +63 -0
  148. ultralytics/models/rtdetr/predict.py +88 -0
  149. ultralytics/models/rtdetr/train.py +89 -0
  150. ultralytics/models/rtdetr/val.py +216 -0
  151. ultralytics/models/sam/__init__.py +25 -0
  152. ultralytics/models/sam/amg.py +275 -0
  153. ultralytics/models/sam/build.py +365 -0
  154. ultralytics/models/sam/build_sam3.py +377 -0
  155. ultralytics/models/sam/model.py +169 -0
  156. ultralytics/models/sam/modules/__init__.py +1 -0
  157. ultralytics/models/sam/modules/blocks.py +1067 -0
  158. ultralytics/models/sam/modules/decoders.py +495 -0
  159. ultralytics/models/sam/modules/encoders.py +794 -0
  160. ultralytics/models/sam/modules/memory_attention.py +298 -0
  161. ultralytics/models/sam/modules/sam.py +1160 -0
  162. ultralytics/models/sam/modules/tiny_encoder.py +979 -0
  163. ultralytics/models/sam/modules/transformer.py +344 -0
  164. ultralytics/models/sam/modules/utils.py +512 -0
  165. ultralytics/models/sam/predict.py +3940 -0
  166. ultralytics/models/sam/sam3/__init__.py +3 -0
  167. ultralytics/models/sam/sam3/decoder.py +546 -0
  168. ultralytics/models/sam/sam3/encoder.py +529 -0
  169. ultralytics/models/sam/sam3/geometry_encoders.py +415 -0
  170. ultralytics/models/sam/sam3/maskformer_segmentation.py +286 -0
  171. ultralytics/models/sam/sam3/model_misc.py +199 -0
  172. ultralytics/models/sam/sam3/necks.py +129 -0
  173. ultralytics/models/sam/sam3/sam3_image.py +339 -0
  174. ultralytics/models/sam/sam3/text_encoder_ve.py +307 -0
  175. ultralytics/models/sam/sam3/vitdet.py +547 -0
  176. ultralytics/models/sam/sam3/vl_combiner.py +160 -0
  177. ultralytics/models/utils/__init__.py +1 -0
  178. ultralytics/models/utils/loss.py +466 -0
  179. ultralytics/models/utils/ops.py +315 -0
  180. ultralytics/models/yolo/__init__.py +7 -0
  181. ultralytics/models/yolo/classify/__init__.py +7 -0
  182. ultralytics/models/yolo/classify/predict.py +90 -0
  183. ultralytics/models/yolo/classify/train.py +202 -0
  184. ultralytics/models/yolo/classify/val.py +216 -0
  185. ultralytics/models/yolo/detect/__init__.py +7 -0
  186. ultralytics/models/yolo/detect/predict.py +122 -0
  187. ultralytics/models/yolo/detect/train.py +227 -0
  188. ultralytics/models/yolo/detect/val.py +507 -0
  189. ultralytics/models/yolo/model.py +430 -0
  190. ultralytics/models/yolo/obb/__init__.py +7 -0
  191. ultralytics/models/yolo/obb/predict.py +56 -0
  192. ultralytics/models/yolo/obb/train.py +79 -0
  193. ultralytics/models/yolo/obb/val.py +302 -0
  194. ultralytics/models/yolo/pose/__init__.py +7 -0
  195. ultralytics/models/yolo/pose/predict.py +65 -0
  196. ultralytics/models/yolo/pose/train.py +110 -0
  197. ultralytics/models/yolo/pose/val.py +248 -0
  198. ultralytics/models/yolo/segment/__init__.py +7 -0
  199. ultralytics/models/yolo/segment/predict.py +109 -0
  200. ultralytics/models/yolo/segment/train.py +69 -0
  201. ultralytics/models/yolo/segment/val.py +307 -0
  202. ultralytics/models/yolo/world/__init__.py +5 -0
  203. ultralytics/models/yolo/world/train.py +173 -0
  204. ultralytics/models/yolo/world/train_world.py +178 -0
  205. ultralytics/models/yolo/yoloe/__init__.py +22 -0
  206. ultralytics/models/yolo/yoloe/predict.py +162 -0
  207. ultralytics/models/yolo/yoloe/train.py +287 -0
  208. ultralytics/models/yolo/yoloe/train_seg.py +122 -0
  209. ultralytics/models/yolo/yoloe/val.py +206 -0
  210. ultralytics/nn/__init__.py +27 -0
  211. ultralytics/nn/autobackend.py +958 -0
  212. ultralytics/nn/modules/__init__.py +182 -0
  213. ultralytics/nn/modules/activation.py +54 -0
  214. ultralytics/nn/modules/block.py +1947 -0
  215. ultralytics/nn/modules/conv.py +669 -0
  216. ultralytics/nn/modules/head.py +1183 -0
  217. ultralytics/nn/modules/transformer.py +793 -0
  218. ultralytics/nn/modules/utils.py +159 -0
  219. ultralytics/nn/tasks.py +1768 -0
  220. ultralytics/nn/text_model.py +356 -0
  221. ultralytics/py.typed +1 -0
  222. ultralytics/solutions/__init__.py +41 -0
  223. ultralytics/solutions/ai_gym.py +108 -0
  224. ultralytics/solutions/analytics.py +264 -0
  225. ultralytics/solutions/config.py +107 -0
  226. ultralytics/solutions/distance_calculation.py +123 -0
  227. ultralytics/solutions/heatmap.py +125 -0
  228. ultralytics/solutions/instance_segmentation.py +86 -0
  229. ultralytics/solutions/object_blurrer.py +89 -0
  230. ultralytics/solutions/object_counter.py +190 -0
  231. ultralytics/solutions/object_cropper.py +87 -0
  232. ultralytics/solutions/parking_management.py +280 -0
  233. ultralytics/solutions/queue_management.py +93 -0
  234. ultralytics/solutions/region_counter.py +133 -0
  235. ultralytics/solutions/security_alarm.py +151 -0
  236. ultralytics/solutions/similarity_search.py +219 -0
  237. ultralytics/solutions/solutions.py +828 -0
  238. ultralytics/solutions/speed_estimation.py +114 -0
  239. ultralytics/solutions/streamlit_inference.py +260 -0
  240. ultralytics/solutions/templates/similarity-search.html +156 -0
  241. ultralytics/solutions/trackzone.py +88 -0
  242. ultralytics/solutions/vision_eye.py +67 -0
  243. ultralytics/trackers/__init__.py +7 -0
  244. ultralytics/trackers/basetrack.py +115 -0
  245. ultralytics/trackers/bot_sort.py +257 -0
  246. ultralytics/trackers/byte_tracker.py +469 -0
  247. ultralytics/trackers/track.py +116 -0
  248. ultralytics/trackers/utils/__init__.py +1 -0
  249. ultralytics/trackers/utils/gmc.py +339 -0
  250. ultralytics/trackers/utils/kalman_filter.py +482 -0
  251. ultralytics/trackers/utils/matching.py +154 -0
  252. ultralytics/utils/__init__.py +1450 -0
  253. ultralytics/utils/autobatch.py +118 -0
  254. ultralytics/utils/autodevice.py +205 -0
  255. ultralytics/utils/benchmarks.py +728 -0
  256. ultralytics/utils/callbacks/__init__.py +5 -0
  257. ultralytics/utils/callbacks/base.py +233 -0
  258. ultralytics/utils/callbacks/clearml.py +146 -0
  259. ultralytics/utils/callbacks/comet.py +625 -0
  260. ultralytics/utils/callbacks/dvc.py +197 -0
  261. ultralytics/utils/callbacks/hub.py +110 -0
  262. ultralytics/utils/callbacks/mlflow.py +134 -0
  263. ultralytics/utils/callbacks/neptune.py +126 -0
  264. ultralytics/utils/callbacks/platform.py +313 -0
  265. ultralytics/utils/callbacks/raytune.py +42 -0
  266. ultralytics/utils/callbacks/tensorboard.py +123 -0
  267. ultralytics/utils/callbacks/wb.py +188 -0
  268. ultralytics/utils/checks.py +1006 -0
  269. ultralytics/utils/cpu.py +85 -0
  270. ultralytics/utils/dist.py +123 -0
  271. ultralytics/utils/downloads.py +529 -0
  272. ultralytics/utils/errors.py +35 -0
  273. ultralytics/utils/events.py +113 -0
  274. ultralytics/utils/export/__init__.py +7 -0
  275. ultralytics/utils/export/engine.py +237 -0
  276. ultralytics/utils/export/imx.py +315 -0
  277. ultralytics/utils/export/tensorflow.py +231 -0
  278. ultralytics/utils/files.py +219 -0
  279. ultralytics/utils/git.py +137 -0
  280. ultralytics/utils/instance.py +484 -0
  281. ultralytics/utils/logger.py +501 -0
  282. ultralytics/utils/loss.py +849 -0
  283. ultralytics/utils/metrics.py +1563 -0
  284. ultralytics/utils/nms.py +337 -0
  285. ultralytics/utils/ops.py +664 -0
  286. ultralytics/utils/patches.py +201 -0
  287. ultralytics/utils/plotting.py +1045 -0
  288. ultralytics/utils/tal.py +403 -0
  289. ultralytics/utils/torch_utils.py +984 -0
  290. ultralytics/utils/tqdm.py +440 -0
  291. ultralytics/utils/triton.py +112 -0
  292. ultralytics/utils/tuner.py +160 -0
  293. ultralytics_opencv_headless-8.3.246.dist-info/METADATA +374 -0
  294. ultralytics_opencv_headless-8.3.246.dist-info/RECORD +298 -0
  295. ultralytics_opencv_headless-8.3.246.dist-info/WHEEL +5 -0
  296. ultralytics_opencv_headless-8.3.246.dist-info/entry_points.txt +3 -0
  297. ultralytics_opencv_headless-8.3.246.dist-info/licenses/LICENSE +661 -0
  298. ultralytics_opencv_headless-8.3.246.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1563 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+ """Model validation metrics."""
3
+
4
+ from __future__ import annotations
5
+
6
+ import math
7
+ import warnings
8
+ from collections import defaultdict
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ import numpy as np
13
+ import torch
14
+
15
+ from ultralytics.utils import LOGGER, DataExportMixin, SimpleClass, TryExcept, checks, plt_settings
16
+
17
+ OKS_SIGMA = (
18
+ np.array(
19
+ [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],
20
+ dtype=np.float32,
21
+ )
22
+ / 10.0
23
+ )
24
+
25
+
26
+ def bbox_ioa(box1: np.ndarray, box2: np.ndarray, iou: bool = False, eps: float = 1e-7) -> np.ndarray:
27
+ """Calculate the intersection over box2 area given box1 and box2.
28
+
29
+ Args:
30
+ box1 (np.ndarray): A numpy array of shape (N, 4) representing N bounding boxes in x1y1x2y2 format.
31
+ box2 (np.ndarray): A numpy array of shape (M, 4) representing M bounding boxes in x1y1x2y2 format.
32
+ iou (bool, optional): Calculate the standard IoU if True else return inter_area/box2_area.
33
+ eps (float, optional): A small value to avoid division by zero.
34
+
35
+ Returns:
36
+ (np.ndarray): A numpy array of shape (N, M) representing the intersection over box2 area.
37
+ """
38
+ # Get the coordinates of bounding boxes
39
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.T
40
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.T
41
+
42
+ # Intersection area
43
+ inter_area = (np.minimum(b1_x2[:, None], b2_x2) - np.maximum(b1_x1[:, None], b2_x1)).clip(0) * (
44
+ np.minimum(b1_y2[:, None], b2_y2) - np.maximum(b1_y1[:, None], b2_y1)
45
+ ).clip(0)
46
+
47
+ # Box2 area
48
+ area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1)
49
+ if iou:
50
+ box1_area = (b1_x2 - b1_x1) * (b1_y2 - b1_y1)
51
+ area = area + box1_area[:, None] - inter_area
52
+
53
+ # Intersection over box2 area
54
+ return inter_area / (area + eps)
55
+
56
+
57
+ def box_iou(box1: torch.Tensor, box2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
58
+ """Calculate intersection-over-union (IoU) of boxes.
59
+
60
+ Args:
61
+ box1 (torch.Tensor): A tensor of shape (N, 4) representing N bounding boxes in (x1, y1, x2, y2) format.
62
+ box2 (torch.Tensor): A tensor of shape (M, 4) representing M bounding boxes in (x1, y1, x2, y2) format.
63
+ eps (float, optional): A small value to avoid division by zero.
64
+
65
+ Returns:
66
+ (torch.Tensor): An NxM tensor containing the pairwise IoU values for every element in box1 and box2.
67
+
68
+ References:
69
+ https://github.com/pytorch/vision/blob/main/torchvision/ops/boxes.py
70
+ """
71
+ # NOTE: Need .float() to get accurate iou values
72
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
73
+ (a1, a2), (b1, b2) = box1.float().unsqueeze(1).chunk(2, 2), box2.float().unsqueeze(0).chunk(2, 2)
74
+ inter = (torch.min(a2, b2) - torch.max(a1, b1)).clamp_(0).prod(2)
75
+
76
+ # IoU = inter / (area1 + area2 - inter)
77
+ return inter / ((a2 - a1).prod(2) + (b2 - b1).prod(2) - inter + eps)
78
+
79
+
80
+ def bbox_iou(
81
+ box1: torch.Tensor,
82
+ box2: torch.Tensor,
83
+ xywh: bool = True,
84
+ GIoU: bool = False,
85
+ DIoU: bool = False,
86
+ CIoU: bool = False,
87
+ eps: float = 1e-7,
88
+ ) -> torch.Tensor:
89
+ """Calculate the Intersection over Union (IoU) between bounding boxes.
90
+
91
+ This function supports various shapes for `box1` and `box2` as long as the last dimension is 4. For instance, you
92
+ may pass tensors shaped like (4,), (N, 4), (B, N, 4), or (B, N, 1, 4). Internally, the code will split the last
93
+ dimension into (x, y, w, h) if `xywh=True`, or (x1, y1, x2, y2) if `xywh=False`.
94
+
95
+ Args:
96
+ box1 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
97
+ box2 (torch.Tensor): A tensor representing one or more bounding boxes, with the last dimension being 4.
98
+ xywh (bool, optional): If True, input boxes are in (x, y, w, h) format. If False, input boxes are in (x1, y1,
99
+ x2, y2) format.
100
+ GIoU (bool, optional): If True, calculate Generalized IoU.
101
+ DIoU (bool, optional): If True, calculate Distance IoU.
102
+ CIoU (bool, optional): If True, calculate Complete IoU.
103
+ eps (float, optional): A small value to avoid division by zero.
104
+
105
+ Returns:
106
+ (torch.Tensor): IoU, GIoU, DIoU, or CIoU values depending on the specified flags.
107
+ """
108
+ # Get the coordinates of bounding boxes
109
+ if xywh: # transform from xywh to xyxy
110
+ (x1, y1, w1, h1), (x2, y2, w2, h2) = box1.chunk(4, -1), box2.chunk(4, -1)
111
+ w1_, h1_, w2_, h2_ = w1 / 2, h1 / 2, w2 / 2, h2 / 2
112
+ b1_x1, b1_x2, b1_y1, b1_y2 = x1 - w1_, x1 + w1_, y1 - h1_, y1 + h1_
113
+ b2_x1, b2_x2, b2_y1, b2_y2 = x2 - w2_, x2 + w2_, y2 - h2_, y2 + h2_
114
+ else: # x1, y1, x2, y2 = box1
115
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1.chunk(4, -1)
116
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2.chunk(4, -1)
117
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
118
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
119
+
120
+ # Intersection area
121
+ inter = (b1_x2.minimum(b2_x2) - b1_x1.maximum(b2_x1)).clamp_(0) * (
122
+ b1_y2.minimum(b2_y2) - b1_y1.maximum(b2_y1)
123
+ ).clamp_(0)
124
+
125
+ # Union Area
126
+ union = w1 * h1 + w2 * h2 - inter + eps
127
+
128
+ # IoU
129
+ iou = inter / union
130
+ if CIoU or DIoU or GIoU:
131
+ cw = b1_x2.maximum(b2_x2) - b1_x1.minimum(b2_x1) # convex (smallest enclosing box) width
132
+ ch = b1_y2.maximum(b2_y2) - b1_y1.minimum(b2_y1) # convex height
133
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
134
+ c2 = cw.pow(2) + ch.pow(2) + eps # convex diagonal squared
135
+ rho2 = (
136
+ (b2_x1 + b2_x2 - b1_x1 - b1_x2).pow(2) + (b2_y1 + b2_y2 - b1_y1 - b1_y2).pow(2)
137
+ ) / 4 # center dist**2
138
+ if CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
139
+ v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
140
+ with torch.no_grad():
141
+ alpha = v / (v - iou + (1 + eps))
142
+ return iou - (rho2 / c2 + v * alpha) # CIoU
143
+ return iou - rho2 / c2 # DIoU
144
+ c_area = cw * ch + eps # convex area
145
+ return iou - (c_area - union) / c_area # GIoU https://arxiv.org/pdf/1902.09630.pdf
146
+ return iou # IoU
147
+
148
+
149
+ def mask_iou(mask1: torch.Tensor, mask2: torch.Tensor, eps: float = 1e-7) -> torch.Tensor:
150
+ """Calculate masks IoU.
151
+
152
+ Args:
153
+ mask1 (torch.Tensor): A tensor of shape (N, n) where N is the number of ground truth objects and n is the
154
+ product of image width and height.
155
+ mask2 (torch.Tensor): A tensor of shape (M, n) where M is the number of predicted objects and n is the product
156
+ of image width and height.
157
+ eps (float, optional): A small value to avoid division by zero.
158
+
159
+ Returns:
160
+ (torch.Tensor): A tensor of shape (N, M) representing masks IoU.
161
+ """
162
+ intersection = torch.matmul(mask1, mask2.T).clamp_(0)
163
+ union = (mask1.sum(1)[:, None] + mask2.sum(1)[None]) - intersection # (area1 + area2) - intersection
164
+ return intersection / (union + eps)
165
+
166
+
167
+ def kpt_iou(
168
+ kpt1: torch.Tensor, kpt2: torch.Tensor, area: torch.Tensor, sigma: list[float], eps: float = 1e-7
169
+ ) -> torch.Tensor:
170
+ """Calculate Object Keypoint Similarity (OKS).
171
+
172
+ Args:
173
+ kpt1 (torch.Tensor): A tensor of shape (N, 17, 3) representing ground truth keypoints.
174
+ kpt2 (torch.Tensor): A tensor of shape (M, 17, 3) representing predicted keypoints.
175
+ area (torch.Tensor): A tensor of shape (N,) representing areas from ground truth.
176
+ sigma (list): A list containing 17 values representing keypoint scales.
177
+ eps (float, optional): A small value to avoid division by zero.
178
+
179
+ Returns:
180
+ (torch.Tensor): A tensor of shape (N, M) representing keypoint similarities.
181
+ """
182
+ d = (kpt1[:, None, :, 0] - kpt2[..., 0]).pow(2) + (kpt1[:, None, :, 1] - kpt2[..., 1]).pow(2) # (N, M, 17)
183
+ sigma = torch.tensor(sigma, device=kpt1.device, dtype=kpt1.dtype) # (17, )
184
+ kpt_mask = kpt1[..., 2] != 0 # (N, 17)
185
+ e = d / ((2 * sigma).pow(2) * (area[:, None, None] + eps) * 2) # from cocoeval
186
+ # e = d / ((area[None, :, None] + eps) * sigma) ** 2 / 2 # from formula
187
+ return ((-e).exp() * kpt_mask[:, None]).sum(-1) / (kpt_mask.sum(-1)[:, None] + eps)
188
+
189
+
190
+ def _get_covariance_matrix(boxes: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
191
+ """Generate covariance matrix from oriented bounding boxes.
192
+
193
+ Args:
194
+ boxes (torch.Tensor): A tensor of shape (N, 5) representing rotated bounding boxes, with xywhr format.
195
+
196
+ Returns:
197
+ (tuple[torch.Tensor, torch.Tensor, torch.Tensor]): Covariance matrix components (a, b, c) where the covariance
198
+ matrix is [[a, c], [c, b]], each of shape (N, 1).
199
+ """
200
+ # Gaussian bounding boxes, ignore the center points (the first two columns) because they are not needed here.
201
+ gbbs = torch.cat((boxes[:, 2:4].pow(2) / 12, boxes[:, 4:]), dim=-1)
202
+ a, b, c = gbbs.split(1, dim=-1)
203
+ cos = c.cos()
204
+ sin = c.sin()
205
+ cos2 = cos.pow(2)
206
+ sin2 = sin.pow(2)
207
+ return a * cos2 + b * sin2, a * sin2 + b * cos2, (a - b) * cos * sin
208
+
209
+
210
+ def probiou(obb1: torch.Tensor, obb2: torch.Tensor, CIoU: bool = False, eps: float = 1e-7) -> torch.Tensor:
211
+ """Calculate probabilistic IoU between oriented bounding boxes.
212
+
213
+ Args:
214
+ obb1 (torch.Tensor): Ground truth OBBs, shape (N, 5), format xywhr.
215
+ obb2 (torch.Tensor): Predicted OBBs, shape (N, 5), format xywhr.
216
+ CIoU (bool, optional): If True, calculate CIoU.
217
+ eps (float, optional): Small value to avoid division by zero.
218
+
219
+ Returns:
220
+ (torch.Tensor): OBB similarities, shape (N,).
221
+
222
+ Notes:
223
+ OBB format: [center_x, center_y, width, height, rotation_angle].
224
+
225
+ References:
226
+ https://arxiv.org/pdf/2106.06072v1.pdf
227
+ """
228
+ x1, y1 = obb1[..., :2].split(1, dim=-1)
229
+ x2, y2 = obb2[..., :2].split(1, dim=-1)
230
+ a1, b1, c1 = _get_covariance_matrix(obb1)
231
+ a2, b2, c2 = _get_covariance_matrix(obb2)
232
+
233
+ t1 = (
234
+ ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
235
+ ) * 0.25
236
+ t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
237
+ t3 = (
238
+ ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
239
+ / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
240
+ + eps
241
+ ).log() * 0.5
242
+ bd = (t1 + t2 + t3).clamp(eps, 100.0)
243
+ hd = (1.0 - (-bd).exp() + eps).sqrt()
244
+ iou = 1 - hd
245
+ if CIoU: # only include the wh aspect ratio part
246
+ w1, h1 = obb1[..., 2:4].split(1, dim=-1)
247
+ w2, h2 = obb2[..., 2:4].split(1, dim=-1)
248
+ v = (4 / math.pi**2) * ((w2 / h2).atan() - (w1 / h1).atan()).pow(2)
249
+ with torch.no_grad():
250
+ alpha = v / (v - iou + (1 + eps))
251
+ return iou - v * alpha # CIoU
252
+ return iou
253
+
254
+
255
+ def batch_probiou(obb1: torch.Tensor | np.ndarray, obb2: torch.Tensor | np.ndarray, eps: float = 1e-7) -> torch.Tensor:
256
+ """Calculate the probabilistic IoU between oriented bounding boxes.
257
+
258
+ Args:
259
+ obb1 (torch.Tensor | np.ndarray): A tensor of shape (N, 5) representing ground truth obbs, with xywhr format.
260
+ obb2 (torch.Tensor | np.ndarray): A tensor of shape (M, 5) representing predicted obbs, with xywhr format.
261
+ eps (float, optional): A small value to avoid division by zero.
262
+
263
+ Returns:
264
+ (torch.Tensor): A tensor of shape (N, M) representing obb similarities.
265
+
266
+ References:
267
+ https://arxiv.org/pdf/2106.06072v1.pdf
268
+ """
269
+ obb1 = torch.from_numpy(obb1) if isinstance(obb1, np.ndarray) else obb1
270
+ obb2 = torch.from_numpy(obb2) if isinstance(obb2, np.ndarray) else obb2
271
+
272
+ x1, y1 = obb1[..., :2].split(1, dim=-1)
273
+ x2, y2 = (x.squeeze(-1)[None] for x in obb2[..., :2].split(1, dim=-1))
274
+ a1, b1, c1 = _get_covariance_matrix(obb1)
275
+ a2, b2, c2 = (x.squeeze(-1)[None] for x in _get_covariance_matrix(obb2))
276
+
277
+ t1 = (
278
+ ((a1 + a2) * (y1 - y2).pow(2) + (b1 + b2) * (x1 - x2).pow(2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)
279
+ ) * 0.25
280
+ t2 = (((c1 + c2) * (x2 - x1) * (y1 - y2)) / ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2) + eps)) * 0.5
281
+ t3 = (
282
+ ((a1 + a2) * (b1 + b2) - (c1 + c2).pow(2))
283
+ / (4 * ((a1 * b1 - c1.pow(2)).clamp_(0) * (a2 * b2 - c2.pow(2)).clamp_(0)).sqrt() + eps)
284
+ + eps
285
+ ).log() * 0.5
286
+ bd = (t1 + t2 + t3).clamp(eps, 100.0)
287
+ hd = (1.0 - (-bd).exp() + eps).sqrt()
288
+ return 1 - hd
289
+
290
+
291
+ def smooth_bce(eps: float = 0.1) -> tuple[float, float]:
292
+ """Compute smoothed positive and negative Binary Cross-Entropy targets.
293
+
294
+ Args:
295
+ eps (float, optional): The epsilon value for label smoothing.
296
+
297
+ Returns:
298
+ pos (float): Positive label smoothing BCE target.
299
+ neg (float): Negative label smoothing BCE target.
300
+
301
+ References:
302
+ https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
303
+ """
304
+ return 1.0 - 0.5 * eps, 0.5 * eps
305
+
306
+
307
+ class ConfusionMatrix(DataExportMixin):
308
+ """A class for calculating and updating a confusion matrix for object detection and classification tasks.
309
+
310
+ Attributes:
311
+ task (str): The type of task, either 'detect' or 'classify'.
312
+ matrix (np.ndarray): The confusion matrix, with dimensions depending on the task.
313
+ nc (int): The number of classes.
314
+ names (list[str]): The names of the classes, used as labels on the plot.
315
+ matches (dict): Contains the indices of ground truths and predictions categorized into TP, FP and FN.
316
+ """
317
+
318
+ def __init__(self, names: dict[int, str] = [], task: str = "detect", save_matches: bool = False):
319
+ """Initialize a ConfusionMatrix instance.
320
+
321
+ Args:
322
+ names (dict[int, str], optional): Names of classes, used as labels on the plot.
323
+ task (str, optional): Type of task, either 'detect' or 'classify'.
324
+ save_matches (bool, optional): Save the indices of GTs, TPs, FPs, FNs for visualization.
325
+ """
326
+ self.task = task
327
+ self.nc = len(names) # number of classes
328
+ self.matrix = np.zeros((self.nc, self.nc)) if self.task == "classify" else np.zeros((self.nc + 1, self.nc + 1))
329
+ self.names = names # name of classes
330
+ self.matches = {} if save_matches else None
331
+
332
+ def _append_matches(self, mtype: str, batch: dict[str, Any], idx: int) -> None:
333
+ """Append the matches to TP, FP, FN or GT list for the last batch.
334
+
335
+ This method updates the matches dictionary by appending specific batch data to the appropriate match type (True
336
+ Positive, False Positive, or False Negative).
337
+
338
+ Args:
339
+ mtype (str): Match type identifier ('TP', 'FP', 'FN' or 'GT').
340
+ batch (dict[str, Any]): Batch data containing detection results with keys like 'bboxes', 'cls', 'conf',
341
+ 'keypoints', 'masks'.
342
+ idx (int): Index of the specific detection to append from the batch.
343
+
344
+ Notes:
345
+ For masks, handles both overlap and non-overlap cases. When masks.max() > 1.0, it indicates
346
+ overlap_mask=True with shape (1, H, W), otherwise uses direct indexing.
347
+ """
348
+ if self.matches is None:
349
+ return
350
+ for k, v in batch.items():
351
+ if k in {"bboxes", "cls", "conf", "keypoints"}:
352
+ self.matches[mtype][k] += v[[idx]]
353
+ elif k == "masks":
354
+ # NOTE: masks.max() > 1.0 means overlap_mask=True with (1, H, W) shape
355
+ self.matches[mtype][k] += [v[0] == idx + 1] if v.max() > 1.0 else [v[idx]]
356
+
357
+ def process_cls_preds(self, preds: list[torch.Tensor], targets: list[torch.Tensor]) -> None:
358
+ """Update confusion matrix for classification task.
359
+
360
+ Args:
361
+ preds (list[N, min(nc,5)]): Predicted class labels.
362
+ targets (list[N, 1]): Ground truth class labels.
363
+ """
364
+ preds, targets = torch.cat(preds)[:, 0], torch.cat(targets)
365
+ for p, t in zip(preds.cpu().numpy(), targets.cpu().numpy()):
366
+ self.matrix[p][t] += 1
367
+
368
+ def process_batch(
369
+ self,
370
+ detections: dict[str, torch.Tensor],
371
+ batch: dict[str, Any],
372
+ conf: float = 0.25,
373
+ iou_thres: float = 0.45,
374
+ ) -> None:
375
+ """Update confusion matrix for object detection task.
376
+
377
+ Args:
378
+ detections (dict[str, torch.Tensor]): Dictionary containing detected bounding boxes and their associated
379
+ information. Should contain 'cls', 'conf', and 'bboxes' keys, where 'bboxes' can be Array[N, 4] for
380
+ regular boxes or Array[N, 5] for OBB with angle.
381
+ batch (dict[str, Any]): Batch dictionary containing ground truth data with 'bboxes' (Array[M, 4]| Array[M,
382
+ 5]) and 'cls' (Array[M]) keys, where M is the number of ground truth objects.
383
+ conf (float, optional): Confidence threshold for detections.
384
+ iou_thres (float, optional): IoU threshold for matching detections to ground truth.
385
+ """
386
+ gt_cls, gt_bboxes = batch["cls"], batch["bboxes"]
387
+ if self.matches is not None: # only if visualization is enabled
388
+ self.matches = {k: defaultdict(list) for k in {"TP", "FP", "FN", "GT"}}
389
+ for i in range(gt_cls.shape[0]):
390
+ self._append_matches("GT", batch, i) # store GT
391
+ is_obb = gt_bboxes.shape[1] == 5 # check if boxes contains angle for OBB
392
+ conf = 0.25 if conf in {None, 0.01 if is_obb else 0.001} else conf # apply 0.25 if default val conf is passed
393
+ no_pred = detections["cls"].shape[0] == 0
394
+ if gt_cls.shape[0] == 0: # Check if labels is empty
395
+ if not no_pred:
396
+ detections = {k: detections[k][detections["conf"] > conf] for k in detections}
397
+ detection_classes = detections["cls"].int().tolist()
398
+ for i, dc in enumerate(detection_classes):
399
+ self.matrix[dc, self.nc] += 1 # FP
400
+ self._append_matches("FP", detections, i)
401
+ return
402
+ if no_pred:
403
+ gt_classes = gt_cls.int().tolist()
404
+ for i, gc in enumerate(gt_classes):
405
+ self.matrix[self.nc, gc] += 1 # FN
406
+ self._append_matches("FN", batch, i)
407
+ return
408
+
409
+ detections = {k: detections[k][detections["conf"] > conf] for k in detections}
410
+ gt_classes = gt_cls.int().tolist()
411
+ detection_classes = detections["cls"].int().tolist()
412
+ bboxes = detections["bboxes"]
413
+ iou = batch_probiou(gt_bboxes, bboxes) if is_obb else box_iou(gt_bboxes, bboxes)
414
+
415
+ x = torch.where(iou > iou_thres)
416
+ if x[0].shape[0]:
417
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
418
+ if x[0].shape[0] > 1:
419
+ matches = matches[matches[:, 2].argsort()[::-1]]
420
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
421
+ matches = matches[matches[:, 2].argsort()[::-1]]
422
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
423
+ else:
424
+ matches = np.zeros((0, 3))
425
+
426
+ n = matches.shape[0] > 0
427
+ m0, m1, _ = matches.transpose().astype(int)
428
+ for i, gc in enumerate(gt_classes):
429
+ j = m0 == i
430
+ if n and sum(j) == 1:
431
+ dc = detection_classes[m1[j].item()]
432
+ self.matrix[dc, gc] += 1 # TP if class is correct else both an FP and an FN
433
+ if dc == gc:
434
+ self._append_matches("TP", detections, m1[j].item())
435
+ else:
436
+ self._append_matches("FP", detections, m1[j].item())
437
+ self._append_matches("FN", batch, i)
438
+ else:
439
+ self.matrix[self.nc, gc] += 1 # FN
440
+ self._append_matches("FN", batch, i)
441
+
442
+ for i, dc in enumerate(detection_classes):
443
+ if not any(m1 == i):
444
+ self.matrix[dc, self.nc] += 1 # FP
445
+ self._append_matches("FP", detections, i)
446
+
447
+ def matrix(self):
448
+ """Return the confusion matrix."""
449
+ return self.matrix
450
+
451
+ def tp_fp(self) -> tuple[np.ndarray, np.ndarray]:
452
+ """Return true positives and false positives.
453
+
454
+ Returns:
455
+ tp (np.ndarray): True positives.
456
+ fp (np.ndarray): False positives.
457
+ """
458
+ tp = self.matrix.diagonal() # true positives
459
+ fp = self.matrix.sum(1) - tp # false positives
460
+ # fn = self.matrix.sum(0) - tp # false negatives (missed detections)
461
+ return (tp, fp) if self.task == "classify" else (tp[:-1], fp[:-1]) # remove background class if task=detect
462
+
463
+ def plot_matches(self, img: torch.Tensor, im_file: str, save_dir: Path) -> None:
464
+ """Plot grid of GT, TP, FP, FN for each image.
465
+
466
+ Args:
467
+ img (torch.Tensor): Image to plot onto.
468
+ im_file (str): Image filename to save visualizations.
469
+ save_dir (Path): Location to save the visualizations to.
470
+ """
471
+ if not self.matches:
472
+ return
473
+ from .ops import xyxy2xywh
474
+ from .plotting import plot_images
475
+
476
+ # Create batch of 4 (GT, TP, FP, FN)
477
+ labels = defaultdict(list)
478
+ for i, mtype in enumerate(["GT", "FP", "TP", "FN"]):
479
+ mbatch = self.matches[mtype]
480
+ if "conf" not in mbatch:
481
+ mbatch["conf"] = torch.tensor([1.0] * len(mbatch["bboxes"]), device=img.device)
482
+ mbatch["batch_idx"] = torch.ones(len(mbatch["bboxes"]), device=img.device) * i
483
+ for k in mbatch.keys():
484
+ labels[k] += mbatch[k]
485
+
486
+ labels = {k: torch.stack(v, 0) if len(v) else torch.empty(0) for k, v in labels.items()}
487
+ if self.task != "obb" and labels["bboxes"].shape[0]:
488
+ labels["bboxes"] = xyxy2xywh(labels["bboxes"])
489
+ (save_dir / "visualizations").mkdir(parents=True, exist_ok=True)
490
+ plot_images(
491
+ labels,
492
+ img.repeat(4, 1, 1, 1),
493
+ paths=["Ground Truth", "False Positives", "True Positives", "False Negatives"],
494
+ fname=save_dir / "visualizations" / Path(im_file).name,
495
+ names=self.names,
496
+ max_subplots=4,
497
+ conf_thres=0.001,
498
+ )
499
+
500
+ @TryExcept(msg="ConfusionMatrix plot failure")
501
+ @plt_settings()
502
+ def plot(self, normalize: bool = True, save_dir: str = "", on_plot=None):
503
+ """Plot the confusion matrix using matplotlib and save it to a file.
504
+
505
+ Args:
506
+ normalize (bool, optional): Whether to normalize the confusion matrix.
507
+ save_dir (str, optional): Directory where the plot will be saved.
508
+ on_plot (callable, optional): An optional callback to pass plots path and data when they are rendered.
509
+ """
510
+ import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
511
+
512
+ array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1) # normalize columns
513
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
514
+
515
+ fig, ax = plt.subplots(1, 1, figsize=(12, 9))
516
+ names, n = list(self.names.values()), self.nc
517
+ if self.nc >= 100: # downsample for large class count
518
+ k = max(2, self.nc // 60) # step size for downsampling, always > 1
519
+ keep_idx = slice(None, None, k) # create slice instead of array
520
+ names = names[keep_idx] # slice class names
521
+ array = array[keep_idx, :][:, keep_idx] # slice matrix rows and cols
522
+ n = (self.nc + k - 1) // k # number of retained classes
523
+ nc = nn = n if self.task == "classify" else n + 1 # adjust for background if needed
524
+ ticklabels = ([*names, "background"]) if (0 < nn < 99) and (nn == nc) else "auto"
525
+ xy_ticks = np.arange(len(ticklabels))
526
+ tick_fontsize = max(6, 15 - 0.1 * nc) # Minimum size is 6
527
+ label_fontsize = max(6, 12 - 0.1 * nc)
528
+ title_fontsize = max(6, 12 - 0.1 * nc)
529
+ btm = max(0.1, 0.25 - 0.001 * nc) # Minimum value is 0.1
530
+ with warnings.catch_warnings():
531
+ warnings.simplefilter("ignore") # suppress empty matrix RuntimeWarning: All-NaN slice encountered
532
+ im = ax.imshow(array, cmap="Blues", vmin=0.0, interpolation="none")
533
+ ax.xaxis.set_label_position("bottom")
534
+ if nc < 30: # Add score for each cell of confusion matrix
535
+ color_threshold = 0.45 * (1 if normalize else np.nanmax(array)) # text color threshold
536
+ for i, row in enumerate(array[:nc]):
537
+ for j, val in enumerate(row[:nc]):
538
+ val = array[i, j]
539
+ if np.isnan(val):
540
+ continue
541
+ ax.text(
542
+ j,
543
+ i,
544
+ f"{val:.2f}" if normalize else f"{int(val)}",
545
+ ha="center",
546
+ va="center",
547
+ fontsize=10,
548
+ color="white" if val > color_threshold else "black",
549
+ )
550
+ cbar = fig.colorbar(im, ax=ax, fraction=0.046, pad=0.05)
551
+ title = "Confusion Matrix" + " Normalized" * normalize
552
+ ax.set_xlabel("True", fontsize=label_fontsize, labelpad=10)
553
+ ax.set_ylabel("Predicted", fontsize=label_fontsize, labelpad=10)
554
+ ax.set_title(title, fontsize=title_fontsize, pad=20)
555
+ ax.set_xticks(xy_ticks)
556
+ ax.set_yticks(xy_ticks)
557
+ ax.tick_params(axis="x", bottom=True, top=False, labelbottom=True, labeltop=False)
558
+ ax.tick_params(axis="y", left=True, right=False, labelleft=True, labelright=False)
559
+ if ticklabels != "auto":
560
+ ax.set_xticklabels(ticklabels, fontsize=tick_fontsize, rotation=90, ha="center")
561
+ ax.set_yticklabels(ticklabels, fontsize=tick_fontsize)
562
+ for s in {"left", "right", "bottom", "top", "outline"}:
563
+ if s != "outline":
564
+ ax.spines[s].set_visible(False) # Confusion matrix plot don't have outline
565
+ cbar.ax.spines[s].set_visible(False)
566
+ fig.subplots_adjust(left=0, right=0.84, top=0.94, bottom=btm) # Adjust layout to ensure equal margins
567
+ plot_fname = Path(save_dir) / f"{title.lower().replace(' ', '_')}.png"
568
+ fig.savefig(plot_fname, dpi=250)
569
+ plt.close(fig)
570
+ if on_plot:
571
+ # Pass confusion matrix data for interactive plotting (raw counts only, normalization done on frontend)
572
+ on_plot(plot_fname, {"type": "confusion_matrix", "matrix": self.matrix.tolist()})
573
+
574
+ def print(self):
575
+ """Print the confusion matrix to the console."""
576
+ for i in range(self.matrix.shape[0]):
577
+ LOGGER.info(" ".join(map(str, self.matrix[i])))
578
+
579
+ def summary(self, normalize: bool = False, decimals: int = 5) -> list[dict[str, float]]:
580
+ """Generate a summarized representation of the confusion matrix as a list of dictionaries, with optional
581
+ normalization. This is useful for exporting the matrix to various formats such as CSV, XML, HTML, JSON,
582
+ or SQL.
583
+
584
+ Args:
585
+ normalize (bool): Whether to normalize the confusion matrix values.
586
+ decimals (int): Number of decimal places to round the output values to.
587
+
588
+ Returns:
589
+ (list[dict[str, float]]): A list of dictionaries, each representing one predicted class with corresponding
590
+ values for all actual classes.
591
+
592
+ Examples:
593
+ >>> results = model.val(data="coco8.yaml", plots=True)
594
+ >>> cm_dict = results.confusion_matrix.summary(normalize=True, decimals=5)
595
+ >>> print(cm_dict)
596
+ """
597
+ import re
598
+
599
+ names = list(self.names.values()) if self.task == "classify" else [*list(self.names.values()), "background"]
600
+ clean_names, seen = [], set()
601
+ for name in names:
602
+ clean_name = re.sub(r"[^a-zA-Z0-9_]", "_", name)
603
+ original_clean = clean_name
604
+ counter = 1
605
+ while clean_name.lower() in seen:
606
+ clean_name = f"{original_clean}_{counter}"
607
+ counter += 1
608
+ seen.add(clean_name.lower())
609
+ clean_names.append(clean_name)
610
+ array = (self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1e-9) if normalize else 1)).round(decimals)
611
+ return [
612
+ dict({"Predicted": clean_names[i]}, **{clean_names[j]: array[i, j] for j in range(len(clean_names))})
613
+ for i in range(len(clean_names))
614
+ ]
615
+
616
+
617
+ def smooth(y: np.ndarray, f: float = 0.05) -> np.ndarray:
618
+ """Box filter of fraction f."""
619
+ nf = round(len(y) * f * 2) // 2 + 1 # number of filter elements (must be odd)
620
+ p = np.ones(nf // 2) # ones padding
621
+ yp = np.concatenate((p * y[0], y, p * y[-1]), 0) # y padded
622
+ return np.convolve(yp, np.ones(nf) / nf, mode="valid") # y-smoothed
623
+
624
+
625
+ @plt_settings()
626
+ def plot_pr_curve(
627
+ px: np.ndarray,
628
+ py: np.ndarray,
629
+ ap: np.ndarray,
630
+ save_dir: Path = Path("pr_curve.png"),
631
+ names: dict[int, str] = {},
632
+ on_plot=None,
633
+ ):
634
+ """Plot precision-recall curve.
635
+
636
+ Args:
637
+ px (np.ndarray): X values for the PR curve.
638
+ py (np.ndarray): Y values for the PR curve.
639
+ ap (np.ndarray): Average precision values.
640
+ save_dir (Path, optional): Path to save the plot.
641
+ names (dict[int, str], optional): Dictionary mapping class indices to class names.
642
+ on_plot (callable, optional): Function to call after plot is saved.
643
+ """
644
+ import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
645
+
646
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
647
+ py = np.stack(py, axis=1)
648
+
649
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
650
+ for i, y in enumerate(py.T):
651
+ ax.plot(px, y, linewidth=1, label=f"{names[i]} {ap[i, 0]:.3f}") # plot(recall, precision)
652
+ else:
653
+ ax.plot(px, py, linewidth=1, color="gray") # plot(recall, precision)
654
+
655
+ ax.plot(px, py.mean(1), linewidth=3, color="blue", label=f"all classes {ap[:, 0].mean():.3f} mAP@0.5")
656
+ ax.set_xlabel("Recall")
657
+ ax.set_ylabel("Precision")
658
+ ax.set_xlim(0, 1)
659
+ ax.set_ylim(0, 1)
660
+ ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
661
+ ax.set_title("Precision-Recall Curve")
662
+ fig.savefig(save_dir, dpi=250)
663
+ plt.close(fig)
664
+ if on_plot:
665
+ # Pass PR curve data for interactive plotting (class names stored at model level)
666
+ on_plot(save_dir, {"type": "pr_curve", "x": px.tolist(), "y": py.tolist(), "ap": ap.tolist()})
667
+
668
+
669
+ @plt_settings()
670
+ def plot_mc_curve(
671
+ px: np.ndarray,
672
+ py: np.ndarray,
673
+ save_dir: Path = Path("mc_curve.png"),
674
+ names: dict[int, str] = {},
675
+ xlabel: str = "Confidence",
676
+ ylabel: str = "Metric",
677
+ on_plot=None,
678
+ ):
679
+ """Plot metric-confidence curve.
680
+
681
+ Args:
682
+ px (np.ndarray): X values for the metric-confidence curve.
683
+ py (np.ndarray): Y values for the metric-confidence curve.
684
+ save_dir (Path, optional): Path to save the plot.
685
+ names (dict[int, str], optional): Dictionary mapping class indices to class names.
686
+ xlabel (str, optional): X-axis label.
687
+ ylabel (str, optional): Y-axis label.
688
+ on_plot (callable, optional): Function to call after plot is saved.
689
+ """
690
+ import matplotlib.pyplot as plt # scope for faster 'import ultralytics'
691
+
692
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
693
+
694
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
695
+ for i, y in enumerate(py):
696
+ ax.plot(px, y, linewidth=1, label=f"{names[i]}") # plot(confidence, metric)
697
+ else:
698
+ ax.plot(px, py.T, linewidth=1, color="gray") # plot(confidence, metric)
699
+
700
+ y = smooth(py.mean(0), 0.1)
701
+ ax.plot(px, y, linewidth=3, color="blue", label=f"all classes {y.max():.2f} at {px[y.argmax()]:.3f}")
702
+ ax.set_xlabel(xlabel)
703
+ ax.set_ylabel(ylabel)
704
+ ax.set_xlim(0, 1)
705
+ ax.set_ylim(0, 1)
706
+ ax.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
707
+ ax.set_title(f"{ylabel}-Confidence Curve")
708
+ fig.savefig(save_dir, dpi=250)
709
+ plt.close(fig)
710
+ if on_plot:
711
+ # Pass metric-confidence curve data for interactive plotting (class names stored at model level)
712
+ on_plot(save_dir, {"type": f"{ylabel.lower()}_curve", "x": px.tolist(), "y": py.tolist()})
713
+
714
+
715
+ def compute_ap(recall: list[float], precision: list[float]) -> tuple[float, np.ndarray, np.ndarray]:
716
+ """Compute the average precision (AP) given the recall and precision curves.
717
+
718
+ Args:
719
+ recall (list): The recall curve.
720
+ precision (list): The precision curve.
721
+
722
+ Returns:
723
+ ap (float): Average precision.
724
+ mpre (np.ndarray): Precision envelope curve.
725
+ mrec (np.ndarray): Modified recall curve with sentinel values added at the beginning and end.
726
+ """
727
+ # Append sentinel values to beginning and end
728
+ mrec = np.concatenate(([0.0], recall, [1.0]))
729
+ mpre = np.concatenate(([1.0], precision, [0.0]))
730
+
731
+ # Compute the precision envelope
732
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
733
+
734
+ # Integrate area under curve
735
+ method = "interp" # methods: 'continuous', 'interp'
736
+ if method == "interp":
737
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
738
+ func = np.trapezoid if checks.check_version(np.__version__, ">=2.0") else np.trapz # np.trapz deprecated
739
+ ap = func(np.interp(x, mrec, mpre), x) # integrate
740
+ else: # 'continuous'
741
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x-axis (recall) changes
742
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
743
+
744
+ return ap, mpre, mrec
745
+
746
+
747
+ def ap_per_class(
748
+ tp: np.ndarray,
749
+ conf: np.ndarray,
750
+ pred_cls: np.ndarray,
751
+ target_cls: np.ndarray,
752
+ plot: bool = False,
753
+ on_plot=None,
754
+ save_dir: Path = Path(),
755
+ names: dict[int, str] = {},
756
+ eps: float = 1e-16,
757
+ prefix: str = "",
758
+ ) -> tuple:
759
+ """Compute the average precision per class for object detection evaluation.
760
+
761
+ Args:
762
+ tp (np.ndarray): Binary array indicating whether the detection is correct (True) or not (False).
763
+ conf (np.ndarray): Array of confidence scores of the detections.
764
+ pred_cls (np.ndarray): Array of predicted classes of the detections.
765
+ target_cls (np.ndarray): Array of true classes of the detections.
766
+ plot (bool, optional): Whether to plot PR curves or not.
767
+ on_plot (callable, optional): A callback to pass plots path and data when they are rendered.
768
+ save_dir (Path, optional): Directory to save the PR curves.
769
+ names (dict[int, str], optional): Dictionary of class names to plot PR curves.
770
+ eps (float, optional): A small value to avoid division by zero.
771
+ prefix (str, optional): A prefix string for saving the plot files.
772
+
773
+ Returns:
774
+ tp (np.ndarray): True positive counts at threshold given by max F1 metric for each class.
775
+ fp (np.ndarray): False positive counts at threshold given by max F1 metric for each class.
776
+ p (np.ndarray): Precision values at threshold given by max F1 metric for each class.
777
+ r (np.ndarray): Recall values at threshold given by max F1 metric for each class.
778
+ f1 (np.ndarray): F1-score values at threshold given by max F1 metric for each class.
779
+ ap (np.ndarray): Average precision for each class at different IoU thresholds.
780
+ unique_classes (np.ndarray): An array of unique classes that have data.
781
+ p_curve (np.ndarray): Precision curves for each class.
782
+ r_curve (np.ndarray): Recall curves for each class.
783
+ f1_curve (np.ndarray): F1-score curves for each class.
784
+ x (np.ndarray): X-axis values for the curves.
785
+ prec_values (np.ndarray): Precision values at mAP@0.5 for each class.
786
+ """
787
+ # Sort by objectness
788
+ i = np.argsort(-conf)
789
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
790
+
791
+ # Find unique classes
792
+ unique_classes, nt = np.unique(target_cls, return_counts=True)
793
+ nc = unique_classes.shape[0] # number of classes, number of detections
794
+
795
+ # Create Precision-Recall curve and compute AP for each class
796
+ x, prec_values = np.linspace(0, 1, 1000), []
797
+
798
+ # Average precision, precision and recall curves
799
+ ap, p_curve, r_curve = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
800
+ for ci, c in enumerate(unique_classes):
801
+ i = pred_cls == c
802
+ n_l = nt[ci] # number of labels
803
+ n_p = i.sum() # number of predictions
804
+ if n_p == 0 or n_l == 0:
805
+ continue
806
+
807
+ # Accumulate FPs and TPs
808
+ fpc = (1 - tp[i]).cumsum(0)
809
+ tpc = tp[i].cumsum(0)
810
+
811
+ # Recall
812
+ recall = tpc / (n_l + eps) # recall curve
813
+ r_curve[ci] = np.interp(-x, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
814
+
815
+ # Precision
816
+ precision = tpc / (tpc + fpc) # precision curve
817
+ p_curve[ci] = np.interp(-x, -conf[i], precision[:, 0], left=1) # p at pr_score
818
+
819
+ # AP from recall-precision curve
820
+ for j in range(tp.shape[1]):
821
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
822
+ if j == 0:
823
+ prec_values.append(np.interp(x, mrec, mpre)) # precision at mAP@0.5
824
+
825
+ prec_values = np.array(prec_values) if prec_values else np.zeros((1, 1000)) # (nc, 1000)
826
+
827
+ # Compute F1 (harmonic mean of precision and recall)
828
+ f1_curve = 2 * p_curve * r_curve / (p_curve + r_curve + eps)
829
+ names = {i: names[k] for i, k in enumerate(unique_classes) if k in names} # dict: only classes that have data
830
+ if plot:
831
+ plot_pr_curve(x, prec_values, ap, save_dir / f"{prefix}PR_curve.png", names, on_plot=on_plot)
832
+ plot_mc_curve(x, f1_curve, save_dir / f"{prefix}F1_curve.png", names, ylabel="F1", on_plot=on_plot)
833
+ plot_mc_curve(x, p_curve, save_dir / f"{prefix}P_curve.png", names, ylabel="Precision", on_plot=on_plot)
834
+ plot_mc_curve(x, r_curve, save_dir / f"{prefix}R_curve.png", names, ylabel="Recall", on_plot=on_plot)
835
+
836
+ i = smooth(f1_curve.mean(0), 0.1).argmax() # max F1 index
837
+ p, r, f1 = p_curve[:, i], r_curve[:, i], f1_curve[:, i] # max-F1 precision, recall, F1 values
838
+ tp = (r * nt).round() # true positives
839
+ fp = (tp / (p + eps) - tp).round() # false positives
840
+ return tp, fp, p, r, f1, ap, unique_classes.astype(int), p_curve, r_curve, f1_curve, x, prec_values
841
+
842
+
843
+ class Metric(SimpleClass):
844
+ """Class for computing evaluation metrics for Ultralytics YOLO models.
845
+
846
+ Attributes:
847
+ p (list): Precision for each class. Shape: (nc,).
848
+ r (list): Recall for each class. Shape: (nc,).
849
+ f1 (list): F1 score for each class. Shape: (nc,).
850
+ all_ap (list): AP scores for all classes and all IoU thresholds. Shape: (nc, 10).
851
+ ap_class_index (list): Index of class for each AP score. Shape: (nc,).
852
+ nc (int): Number of classes.
853
+
854
+ Methods:
855
+ ap50: AP at IoU threshold of 0.5 for all classes.
856
+ ap: AP at IoU thresholds from 0.5 to 0.95 for all classes.
857
+ mp: Mean precision of all classes.
858
+ mr: Mean recall of all classes.
859
+ map50: Mean AP at IoU threshold of 0.5 for all classes.
860
+ map75: Mean AP at IoU threshold of 0.75 for all classes.
861
+ map: Mean AP at IoU thresholds from 0.5 to 0.95 for all classes.
862
+ mean_results: Mean of results, returns mp, mr, map50, map.
863
+ class_result: Class-aware result, returns p[i], r[i], ap50[i], ap[i].
864
+ maps: mAP of each class.
865
+ fitness: Model fitness as a weighted combination of metrics.
866
+ update: Update metric attributes with new evaluation results.
867
+ curves: Provides a list of curves for accessing specific metrics like precision, recall, F1, etc.
868
+ curves_results: Provide a list of results for accessing specific metrics like precision, recall, F1, etc.
869
+ """
870
+
871
+ def __init__(self) -> None:
872
+ """Initialize a Metric instance for computing evaluation metrics for the YOLOv8 model."""
873
+ self.p = [] # (nc, )
874
+ self.r = [] # (nc, )
875
+ self.f1 = [] # (nc, )
876
+ self.all_ap = [] # (nc, 10)
877
+ self.ap_class_index = [] # (nc, )
878
+ self.nc = 0
879
+
880
+ @property
881
+ def ap50(self) -> np.ndarray | list:
882
+ """Return the Average Precision (AP) at an IoU threshold of 0.5 for all classes.
883
+
884
+ Returns:
885
+ (np.ndarray | list): Array of shape (nc,) with AP50 values per class, or an empty list if not available.
886
+ """
887
+ return self.all_ap[:, 0] if len(self.all_ap) else []
888
+
889
+ @property
890
+ def ap(self) -> np.ndarray | list:
891
+ """Return the Average Precision (AP) at an IoU threshold of 0.5-0.95 for all classes.
892
+
893
+ Returns:
894
+ (np.ndarray | list): Array of shape (nc,) with AP50-95 values per class, or an empty list if not available.
895
+ """
896
+ return self.all_ap.mean(1) if len(self.all_ap) else []
897
+
898
+ @property
899
+ def mp(self) -> float:
900
+ """Return the Mean Precision of all classes.
901
+
902
+ Returns:
903
+ (float): The mean precision of all classes.
904
+ """
905
+ return self.p.mean() if len(self.p) else 0.0
906
+
907
+ @property
908
+ def mr(self) -> float:
909
+ """Return the Mean Recall of all classes.
910
+
911
+ Returns:
912
+ (float): The mean recall of all classes.
913
+ """
914
+ return self.r.mean() if len(self.r) else 0.0
915
+
916
+ @property
917
+ def map50(self) -> float:
918
+ """Return the mean Average Precision (mAP) at an IoU threshold of 0.5.
919
+
920
+ Returns:
921
+ (float): The mAP at an IoU threshold of 0.5.
922
+ """
923
+ return self.all_ap[:, 0].mean() if len(self.all_ap) else 0.0
924
+
925
+ @property
926
+ def map75(self) -> float:
927
+ """Return the mean Average Precision (mAP) at an IoU threshold of 0.75.
928
+
929
+ Returns:
930
+ (float): The mAP at an IoU threshold of 0.75.
931
+ """
932
+ return self.all_ap[:, 5].mean() if len(self.all_ap) else 0.0
933
+
934
+ @property
935
+ def map(self) -> float:
936
+ """Return the mean Average Precision (mAP) over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
937
+
938
+ Returns:
939
+ (float): The mAP over IoU thresholds of 0.5 - 0.95 in steps of 0.05.
940
+ """
941
+ return self.all_ap.mean() if len(self.all_ap) else 0.0
942
+
943
+ def mean_results(self) -> list[float]:
944
+ """Return mean of results, mp, mr, map50, map."""
945
+ return [self.mp, self.mr, self.map50, self.map]
946
+
947
+ def class_result(self, i: int) -> tuple[float, float, float, float]:
948
+ """Return class-aware result, p[i], r[i], ap50[i], ap[i]."""
949
+ return self.p[i], self.r[i], self.ap50[i], self.ap[i]
950
+
951
+ @property
952
+ def maps(self) -> np.ndarray:
953
+ """Return mAP of each class."""
954
+ maps = np.zeros(self.nc) + self.map
955
+ for i, c in enumerate(self.ap_class_index):
956
+ maps[c] = self.ap[i]
957
+ return maps
958
+
959
+ def fitness(self) -> float:
960
+ """Return model fitness as a weighted combination of metrics."""
961
+ w = [0.0, 0.0, 0.0, 1.0] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
962
+ return (np.nan_to_num(np.array(self.mean_results())) * w).sum()
963
+
964
+ def update(self, results: tuple):
965
+ """Update the evaluation metrics with a new set of results.
966
+
967
+ Args:
968
+ results (tuple): A tuple containing evaluation metrics:
969
+ - p (list): Precision for each class.
970
+ - r (list): Recall for each class.
971
+ - f1 (list): F1 score for each class.
972
+ - all_ap (list): AP scores for all classes and all IoU thresholds.
973
+ - ap_class_index (list): Index of class for each AP score.
974
+ - p_curve (list): Precision curve for each class.
975
+ - r_curve (list): Recall curve for each class.
976
+ - f1_curve (list): F1 curve for each class.
977
+ - px (list): X values for the curves.
978
+ - prec_values (list): Precision values for each class.
979
+ """
980
+ (
981
+ self.p,
982
+ self.r,
983
+ self.f1,
984
+ self.all_ap,
985
+ self.ap_class_index,
986
+ self.p_curve,
987
+ self.r_curve,
988
+ self.f1_curve,
989
+ self.px,
990
+ self.prec_values,
991
+ ) = results
992
+
993
+ @property
994
+ def curves(self) -> list:
995
+ """Return a list of curves for accessing specific metrics curves."""
996
+ return []
997
+
998
+ @property
999
+ def curves_results(self) -> list[list]:
1000
+ """Return a list of curves for accessing specific metrics curves."""
1001
+ return [
1002
+ [self.px, self.prec_values, "Recall", "Precision"],
1003
+ [self.px, self.f1_curve, "Confidence", "F1"],
1004
+ [self.px, self.p_curve, "Confidence", "Precision"],
1005
+ [self.px, self.r_curve, "Confidence", "Recall"],
1006
+ ]
1007
+
1008
+
1009
+ class DetMetrics(SimpleClass, DataExportMixin):
1010
+ """Utility class for computing detection metrics such as precision, recall, and mean average precision (mAP).
1011
+
1012
+ Attributes:
1013
+ names (dict[int, str]): A dictionary of class names.
1014
+ box (Metric): An instance of the Metric class for storing detection results.
1015
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
1016
+ task (str): The task type, set to 'detect'.
1017
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
1018
+ target classes, and target images.
1019
+ nt_per_class: Number of targets per class.
1020
+ nt_per_image: Number of targets per image.
1021
+
1022
+ Methods:
1023
+ update_stats: Update statistics by appending new values to existing stat collections.
1024
+ process: Process predicted results for object detection and update metrics.
1025
+ clear_stats: Clear the stored statistics.
1026
+ keys: Return a list of keys for accessing specific metrics.
1027
+ mean_results: Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95.
1028
+ class_result: Return the result of evaluating the performance of an object detection model on a specific class.
1029
+ maps: Return mean Average Precision (mAP) scores per class.
1030
+ fitness: Return the fitness of box object.
1031
+ ap_class_index: Return the average precision index per class.
1032
+ results_dict: Return dictionary of computed performance metrics and statistics.
1033
+ curves: Return a list of curves for accessing specific metrics curves.
1034
+ curves_results: Return a list of computed performance metrics and statistics.
1035
+ summary: Generate a summarized representation of per-class detection metrics as a list of dictionaries.
1036
+ """
1037
+
1038
+ def __init__(self, names: dict[int, str] = {}) -> None:
1039
+ """Initialize a DetMetrics instance with a save directory, plot flag, and class names.
1040
+
1041
+ Args:
1042
+ names (dict[int, str], optional): Dictionary of class names.
1043
+ """
1044
+ self.names = names
1045
+ self.box = Metric()
1046
+ self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
1047
+ self.task = "detect"
1048
+ self.stats = dict(tp=[], conf=[], pred_cls=[], target_cls=[], target_img=[])
1049
+ self.nt_per_class = None
1050
+ self.nt_per_image = None
1051
+
1052
+ def update_stats(self, stat: dict[str, Any]) -> None:
1053
+ """Update statistics by appending new values to existing stat collections.
1054
+
1055
+ Args:
1056
+ stat (dict[str, any]): Dictionary containing new statistical values to append. Keys should match existing
1057
+ keys in self.stats.
1058
+ """
1059
+ for k in self.stats.keys():
1060
+ self.stats[k].append(stat[k])
1061
+
1062
+ def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
1063
+ """Process predicted results for object detection and update metrics.
1064
+
1065
+ Args:
1066
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
1067
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
1068
+ on_plot (callable, optional): Function to call after plots are generated. Defaults to None.
1069
+
1070
+ Returns:
1071
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
1072
+ """
1073
+ stats = {k: np.concatenate(v, 0) for k, v in self.stats.items()} # to numpy
1074
+ if not stats:
1075
+ return stats
1076
+ results = ap_per_class(
1077
+ stats["tp"],
1078
+ stats["conf"],
1079
+ stats["pred_cls"],
1080
+ stats["target_cls"],
1081
+ plot=plot,
1082
+ save_dir=save_dir,
1083
+ names=self.names,
1084
+ on_plot=on_plot,
1085
+ prefix="Box",
1086
+ )[2:]
1087
+ self.box.nc = len(self.names)
1088
+ self.box.update(results)
1089
+ self.nt_per_class = np.bincount(stats["target_cls"].astype(int), minlength=len(self.names))
1090
+ self.nt_per_image = np.bincount(stats["target_img"].astype(int), minlength=len(self.names))
1091
+ return stats
1092
+
1093
+ def clear_stats(self):
1094
+ """Clear the stored statistics."""
1095
+ for v in self.stats.values():
1096
+ v.clear()
1097
+
1098
+ @property
1099
+ def keys(self) -> list[str]:
1100
+ """Return a list of keys for accessing specific metrics."""
1101
+ return ["metrics/precision(B)", "metrics/recall(B)", "metrics/mAP50(B)", "metrics/mAP50-95(B)"]
1102
+
1103
+ def mean_results(self) -> list[float]:
1104
+ """Calculate mean of detected objects & return precision, recall, mAP50, and mAP50-95."""
1105
+ return self.box.mean_results()
1106
+
1107
+ def class_result(self, i: int) -> tuple[float, float, float, float]:
1108
+ """Return the result of evaluating the performance of an object detection model on a specific class."""
1109
+ return self.box.class_result(i)
1110
+
1111
+ @property
1112
+ def maps(self) -> np.ndarray:
1113
+ """Return mean Average Precision (mAP) scores per class."""
1114
+ return self.box.maps
1115
+
1116
+ @property
1117
+ def fitness(self) -> float:
1118
+ """Return the fitness of box object."""
1119
+ return self.box.fitness()
1120
+
1121
+ @property
1122
+ def ap_class_index(self) -> list:
1123
+ """Return the average precision index per class."""
1124
+ return self.box.ap_class_index
1125
+
1126
+ @property
1127
+ def results_dict(self) -> dict[str, float]:
1128
+ """Return dictionary of computed performance metrics and statistics."""
1129
+ keys = [*self.keys, "fitness"]
1130
+ values = ((float(x) if hasattr(x, "item") else x) for x in ([*self.mean_results(), self.fitness]))
1131
+ return dict(zip(keys, values))
1132
+
1133
+ @property
1134
+ def curves(self) -> list[str]:
1135
+ """Return a list of curves for accessing specific metrics curves."""
1136
+ return ["Precision-Recall(B)", "F1-Confidence(B)", "Precision-Confidence(B)", "Recall-Confidence(B)"]
1137
+
1138
+ @property
1139
+ def curves_results(self) -> list[list]:
1140
+ """Return a list of computed performance metrics and statistics."""
1141
+ return self.box.curves_results
1142
+
1143
+ def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
1144
+ """Generate a summarized representation of per-class detection metrics as a list of dictionaries. Includes
1145
+ shared scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
1146
+
1147
+ Args:
1148
+ normalize (bool): For Detect metrics, everything is normalized by default [0-1].
1149
+ decimals (int): Number of decimal places to round the metrics values to.
1150
+
1151
+ Returns:
1152
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
1153
+ values.
1154
+
1155
+ Examples:
1156
+ >>> results = model.val(data="coco8.yaml")
1157
+ >>> detection_summary = results.summary()
1158
+ >>> print(detection_summary)
1159
+ """
1160
+ per_class = {
1161
+ "Box-P": self.box.p,
1162
+ "Box-R": self.box.r,
1163
+ "Box-F1": self.box.f1,
1164
+ }
1165
+ return [
1166
+ {
1167
+ "Class": self.names[self.ap_class_index[i]],
1168
+ "Images": self.nt_per_image[self.ap_class_index[i]],
1169
+ "Instances": self.nt_per_class[self.ap_class_index[i]],
1170
+ **{k: round(v[i], decimals) for k, v in per_class.items()},
1171
+ "mAP50": round(self.class_result(i)[2], decimals),
1172
+ "mAP50-95": round(self.class_result(i)[3], decimals),
1173
+ }
1174
+ for i in range(len(per_class["Box-P"]))
1175
+ ]
1176
+
1177
+
1178
+ class SegmentMetrics(DetMetrics):
1179
+ """Calculate and aggregate detection and segmentation metrics over a given set of classes.
1180
+
1181
+ Attributes:
1182
+ names (dict[int, str]): Dictionary of class names.
1183
+ box (Metric): An instance of the Metric class for storing detection results.
1184
+ seg (Metric): An instance of the Metric class to calculate mask segmentation metrics.
1185
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
1186
+ task (str): The task type, set to 'segment'.
1187
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
1188
+ target classes, and target images.
1189
+ nt_per_class: Number of targets per class.
1190
+ nt_per_image: Number of targets per image.
1191
+
1192
+ Methods:
1193
+ process: Process the detection and segmentation metrics over the given set of predictions.
1194
+ keys: Return a list of keys for accessing metrics.
1195
+ mean_results: Return the mean metrics for bounding box and segmentation results.
1196
+ class_result: Return classification results for a specified class index.
1197
+ maps: Return mAP scores for object detection and semantic segmentation models.
1198
+ fitness: Return the fitness score for both segmentation and bounding box models.
1199
+ curves: Return a list of curves for accessing specific metrics curves.
1200
+ curves_results: Provide a list of computed performance metrics and statistics.
1201
+ summary: Generate a summarized representation of per-class segmentation metrics as a list of dictionaries.
1202
+ """
1203
+
1204
+ def __init__(self, names: dict[int, str] = {}) -> None:
1205
+ """Initialize a SegmentMetrics instance with a save directory, plot flag, and class names.
1206
+
1207
+ Args:
1208
+ names (dict[int, str], optional): Dictionary of class names.
1209
+ """
1210
+ DetMetrics.__init__(self, names)
1211
+ self.seg = Metric()
1212
+ self.task = "segment"
1213
+ self.stats["tp_m"] = [] # add additional stats for masks
1214
+
1215
+ def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
1216
+ """Process the detection and segmentation metrics over the given set of predictions.
1217
+
1218
+ Args:
1219
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
1220
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
1221
+ on_plot (callable, optional): Function to call after plots are generated. Defaults to None.
1222
+
1223
+ Returns:
1224
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
1225
+ """
1226
+ stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats
1227
+ results_mask = ap_per_class(
1228
+ stats["tp_m"],
1229
+ stats["conf"],
1230
+ stats["pred_cls"],
1231
+ stats["target_cls"],
1232
+ plot=plot,
1233
+ on_plot=on_plot,
1234
+ save_dir=save_dir,
1235
+ names=self.names,
1236
+ prefix="Mask",
1237
+ )[2:]
1238
+ self.seg.nc = len(self.names)
1239
+ self.seg.update(results_mask)
1240
+ return stats
1241
+
1242
+ @property
1243
+ def keys(self) -> list[str]:
1244
+ """Return a list of keys for accessing metrics."""
1245
+ return [
1246
+ *DetMetrics.keys.fget(self),
1247
+ "metrics/precision(M)",
1248
+ "metrics/recall(M)",
1249
+ "metrics/mAP50(M)",
1250
+ "metrics/mAP50-95(M)",
1251
+ ]
1252
+
1253
+ def mean_results(self) -> list[float]:
1254
+ """Return the mean metrics for bounding box and segmentation results."""
1255
+ return DetMetrics.mean_results(self) + self.seg.mean_results()
1256
+
1257
+ def class_result(self, i: int) -> list[float]:
1258
+ """Return classification results for a specified class index."""
1259
+ return DetMetrics.class_result(self, i) + self.seg.class_result(i)
1260
+
1261
+ @property
1262
+ def maps(self) -> np.ndarray:
1263
+ """Return mAP scores for object detection and semantic segmentation models."""
1264
+ return DetMetrics.maps.fget(self) + self.seg.maps
1265
+
1266
+ @property
1267
+ def fitness(self) -> float:
1268
+ """Return the fitness score for both segmentation and bounding box models."""
1269
+ return self.seg.fitness() + DetMetrics.fitness.fget(self)
1270
+
1271
+ @property
1272
+ def curves(self) -> list[str]:
1273
+ """Return a list of curves for accessing specific metrics curves."""
1274
+ return [
1275
+ *DetMetrics.curves.fget(self),
1276
+ "Precision-Recall(M)",
1277
+ "F1-Confidence(M)",
1278
+ "Precision-Confidence(M)",
1279
+ "Recall-Confidence(M)",
1280
+ ]
1281
+
1282
+ @property
1283
+ def curves_results(self) -> list[list]:
1284
+ """Return a list of computed performance metrics and statistics."""
1285
+ return DetMetrics.curves_results.fget(self) + self.seg.curves_results
1286
+
1287
+ def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
1288
+ """Generate a summarized representation of per-class segmentation metrics as a list of dictionaries. Includes
1289
+ both box and mask scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for
1290
+ each class.
1291
+
1292
+ Args:
1293
+ normalize (bool): For Segment metrics, everything is normalized by default [0-1].
1294
+ decimals (int): Number of decimal places to round the metrics values to.
1295
+
1296
+ Returns:
1297
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
1298
+ values.
1299
+
1300
+ Examples:
1301
+ >>> results = model.val(data="coco8-seg.yaml")
1302
+ >>> seg_summary = results.summary(decimals=4)
1303
+ >>> print(seg_summary)
1304
+ """
1305
+ per_class = {
1306
+ "Mask-P": self.seg.p,
1307
+ "Mask-R": self.seg.r,
1308
+ "Mask-F1": self.seg.f1,
1309
+ }
1310
+ summary = DetMetrics.summary(self, normalize, decimals) # get box summary
1311
+ for i, s in enumerate(summary):
1312
+ s.update({**{k: round(v[i], decimals) for k, v in per_class.items()}})
1313
+ return summary
1314
+
1315
+
1316
+ class PoseMetrics(DetMetrics):
1317
+ """Calculate and aggregate detection and pose metrics over a given set of classes.
1318
+
1319
+ Attributes:
1320
+ names (dict[int, str]): Dictionary of class names.
1321
+ pose (Metric): An instance of the Metric class to calculate pose metrics.
1322
+ box (Metric): An instance of the Metric class for storing detection results.
1323
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
1324
+ task (str): The task type, set to 'pose'.
1325
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
1326
+ target classes, and target images.
1327
+ nt_per_class: Number of targets per class.
1328
+ nt_per_image: Number of targets per image.
1329
+
1330
+ Methods:
1331
+ process: Process the detection and pose metrics over the given set of predictions. R
1332
+ keys: Return a list of keys for accessing metrics.
1333
+ mean_results: Return the mean results of box and pose.
1334
+ class_result: Return the class-wise detection results for a specific class i.
1335
+ maps: Return the mean average precision (mAP) per class for both box and pose detections.
1336
+ fitness: Return combined fitness score for pose and box detection.
1337
+ curves: Return a list of curves for accessing specific metrics curves.
1338
+ curves_results: Provide a list of computed performance metrics and statistics.
1339
+ summary: Generate a summarized representation of per-class pose metrics as a list of dictionaries.
1340
+ """
1341
+
1342
+ def __init__(self, names: dict[int, str] = {}) -> None:
1343
+ """Initialize the PoseMetrics class with directory path, class names, and plotting options.
1344
+
1345
+ Args:
1346
+ names (dict[int, str], optional): Dictionary of class names.
1347
+ """
1348
+ super().__init__(names)
1349
+ self.pose = Metric()
1350
+ self.task = "pose"
1351
+ self.stats["tp_p"] = [] # add additional stats for pose
1352
+
1353
+ def process(self, save_dir: Path = Path("."), plot: bool = False, on_plot=None) -> dict[str, np.ndarray]:
1354
+ """Process the detection and pose metrics over the given set of predictions.
1355
+
1356
+ Args:
1357
+ save_dir (Path): Directory to save plots. Defaults to Path(".").
1358
+ plot (bool): Whether to plot precision-recall curves. Defaults to False.
1359
+ on_plot (callable, optional): Function to call after plots are generated.
1360
+
1361
+ Returns:
1362
+ (dict[str, np.ndarray]): Dictionary containing concatenated statistics arrays.
1363
+ """
1364
+ stats = DetMetrics.process(self, save_dir, plot, on_plot=on_plot) # process box stats
1365
+ results_pose = ap_per_class(
1366
+ stats["tp_p"],
1367
+ stats["conf"],
1368
+ stats["pred_cls"],
1369
+ stats["target_cls"],
1370
+ plot=plot,
1371
+ on_plot=on_plot,
1372
+ save_dir=save_dir,
1373
+ names=self.names,
1374
+ prefix="Pose",
1375
+ )[2:]
1376
+ self.pose.nc = len(self.names)
1377
+ self.pose.update(results_pose)
1378
+ return stats
1379
+
1380
+ @property
1381
+ def keys(self) -> list[str]:
1382
+ """Return a list of evaluation metric keys."""
1383
+ return [
1384
+ *DetMetrics.keys.fget(self),
1385
+ "metrics/precision(P)",
1386
+ "metrics/recall(P)",
1387
+ "metrics/mAP50(P)",
1388
+ "metrics/mAP50-95(P)",
1389
+ ]
1390
+
1391
+ def mean_results(self) -> list[float]:
1392
+ """Return the mean results of box and pose."""
1393
+ return DetMetrics.mean_results(self) + self.pose.mean_results()
1394
+
1395
+ def class_result(self, i: int) -> list[float]:
1396
+ """Return the class-wise detection results for a specific class i."""
1397
+ return DetMetrics.class_result(self, i) + self.pose.class_result(i)
1398
+
1399
+ @property
1400
+ def maps(self) -> np.ndarray:
1401
+ """Return the mean average precision (mAP) per class for both box and pose detections."""
1402
+ return DetMetrics.maps.fget(self) + self.pose.maps
1403
+
1404
+ @property
1405
+ def fitness(self) -> float:
1406
+ """Return combined fitness score for pose and box detection."""
1407
+ return self.pose.fitness() + DetMetrics.fitness.fget(self)
1408
+
1409
+ @property
1410
+ def curves(self) -> list[str]:
1411
+ """Return a list of curves for accessing specific metrics curves."""
1412
+ return [
1413
+ *DetMetrics.curves.fget(self),
1414
+ "Precision-Recall(B)",
1415
+ "F1-Confidence(B)",
1416
+ "Precision-Confidence(B)",
1417
+ "Recall-Confidence(B)",
1418
+ "Precision-Recall(P)",
1419
+ "F1-Confidence(P)",
1420
+ "Precision-Confidence(P)",
1421
+ "Recall-Confidence(P)",
1422
+ ]
1423
+
1424
+ @property
1425
+ def curves_results(self) -> list[list]:
1426
+ """Return a list of computed performance metrics and statistics."""
1427
+ return DetMetrics.curves_results.fget(self) + self.pose.curves_results
1428
+
1429
+ def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, Any]]:
1430
+ """Generate a summarized representation of per-class pose metrics as a list of dictionaries. Includes both box
1431
+ and pose scalar metrics (mAP, mAP50, mAP75) alongside precision, recall, and F1-score for each class.
1432
+
1433
+ Args:
1434
+ normalize (bool): For Pose metrics, everything is normalized by default [0-1].
1435
+ decimals (int): Number of decimal places to round the metrics values to.
1436
+
1437
+ Returns:
1438
+ (list[dict[str, Any]]): A list of dictionaries, each representing one class with corresponding metric
1439
+ values.
1440
+
1441
+ Examples:
1442
+ >>> results = model.val(data="coco8-pose.yaml")
1443
+ >>> pose_summary = results.summary(decimals=4)
1444
+ >>> print(pose_summary)
1445
+ """
1446
+ per_class = {
1447
+ "Pose-P": self.pose.p,
1448
+ "Pose-R": self.pose.r,
1449
+ "Pose-F1": self.pose.f1,
1450
+ }
1451
+ summary = DetMetrics.summary(self, normalize, decimals) # get box summary
1452
+ for i, s in enumerate(summary):
1453
+ s.update({**{k: round(v[i], decimals) for k, v in per_class.items()}})
1454
+ return summary
1455
+
1456
+
1457
+ class ClassifyMetrics(SimpleClass, DataExportMixin):
1458
+ """Class for computing classification metrics including top-1 and top-5 accuracy.
1459
+
1460
+ Attributes:
1461
+ top1 (float): The top-1 accuracy.
1462
+ top5 (float): The top-5 accuracy.
1463
+ speed (dict): A dictionary containing the time taken for each step in the pipeline.
1464
+ task (str): The task type, set to 'classify'.
1465
+
1466
+ Methods:
1467
+ process: Process target classes and predicted classes to compute metrics.
1468
+ fitness: Return mean of top-1 and top-5 accuracies as fitness score.
1469
+ results_dict: Return a dictionary with model's performance metrics and fitness score.
1470
+ keys: Return a list of keys for the results_dict property.
1471
+ curves: Return a list of curves for accessing specific metrics curves.
1472
+ curves_results: Provide a list of computed performance metrics and statistics.
1473
+ summary: Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
1474
+ """
1475
+
1476
+ def __init__(self) -> None:
1477
+ """Initialize a ClassifyMetrics instance."""
1478
+ self.top1 = 0
1479
+ self.top5 = 0
1480
+ self.speed = {"preprocess": 0.0, "inference": 0.0, "loss": 0.0, "postprocess": 0.0}
1481
+ self.task = "classify"
1482
+
1483
+ def process(self, targets: torch.Tensor, pred: torch.Tensor):
1484
+ """Process target classes and predicted classes to compute metrics.
1485
+
1486
+ Args:
1487
+ targets (torch.Tensor): Target classes.
1488
+ pred (torch.Tensor): Predicted classes.
1489
+ """
1490
+ pred, targets = torch.cat(pred), torch.cat(targets)
1491
+ correct = (targets[:, None] == pred).float()
1492
+ acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
1493
+ self.top1, self.top5 = acc.mean(0).tolist()
1494
+
1495
+ @property
1496
+ def fitness(self) -> float:
1497
+ """Return mean of top-1 and top-5 accuracies as fitness score."""
1498
+ return (self.top1 + self.top5) / 2
1499
+
1500
+ @property
1501
+ def results_dict(self) -> dict[str, float]:
1502
+ """Return a dictionary with model's performance metrics and fitness score."""
1503
+ return dict(zip([*self.keys, "fitness"], [self.top1, self.top5, self.fitness]))
1504
+
1505
+ @property
1506
+ def keys(self) -> list[str]:
1507
+ """Return a list of keys for the results_dict property."""
1508
+ return ["metrics/accuracy_top1", "metrics/accuracy_top5"]
1509
+
1510
+ @property
1511
+ def curves(self) -> list:
1512
+ """Return a list of curves for accessing specific metrics curves."""
1513
+ return []
1514
+
1515
+ @property
1516
+ def curves_results(self) -> list:
1517
+ """Return a list of curves for accessing specific metrics curves."""
1518
+ return []
1519
+
1520
+ def summary(self, normalize: bool = True, decimals: int = 5) -> list[dict[str, float]]:
1521
+ """Generate a single-row summary of classification metrics (Top-1 and Top-5 accuracy).
1522
+
1523
+ Args:
1524
+ normalize (bool): For Classify metrics, everything is normalized by default [0-1].
1525
+ decimals (int): Number of decimal places to round the metrics values to.
1526
+
1527
+ Returns:
1528
+ (list[dict[str, float]]): A list with one dictionary containing Top-1 and Top-5 classification accuracy.
1529
+
1530
+ Examples:
1531
+ >>> results = model.val(data="imagenet10")
1532
+ >>> classify_summary = results.summary(decimals=4)
1533
+ >>> print(classify_summary)
1534
+ """
1535
+ return [{"top1_acc": round(self.top1, decimals), "top5_acc": round(self.top5, decimals)}]
1536
+
1537
+
1538
+ class OBBMetrics(DetMetrics):
1539
+ """Metrics for evaluating oriented bounding box (OBB) detection.
1540
+
1541
+ Attributes:
1542
+ names (dict[int, str]): Dictionary of class names.
1543
+ box (Metric): An instance of the Metric class for storing detection results.
1544
+ speed (dict[str, float]): A dictionary for storing execution times of different parts of the detection process.
1545
+ task (str): The task type, set to 'obb'.
1546
+ stats (dict[str, list]): A dictionary containing lists for true positives, confidence scores, predicted classes,
1547
+ target classes, and target images.
1548
+ nt_per_class: Number of targets per class.
1549
+ nt_per_image: Number of targets per image.
1550
+
1551
+ References:
1552
+ https://arxiv.org/pdf/2106.06072.pdf
1553
+ """
1554
+
1555
+ def __init__(self, names: dict[int, str] = {}) -> None:
1556
+ """Initialize an OBBMetrics instance with directory, plotting, and class names.
1557
+
1558
+ Args:
1559
+ names (dict[int, str], optional): Dictionary of class names.
1560
+ """
1561
+ DetMetrics.__init__(self, names)
1562
+ # TODO: probably remove task as well
1563
+ self.task = "obb"