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