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,215 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import torch
4
+
5
+ from ultralytics.data import ClassificationDataset, build_dataloader
6
+ from ultralytics.engine.validator import BaseValidator
7
+ from ultralytics.utils import LOGGER
8
+ from ultralytics.utils.metrics import ClassifyMetrics, ConfusionMatrix
9
+ from ultralytics.utils.plotting import plot_images
10
+
11
+
12
+ class ClassificationValidator(BaseValidator):
13
+ """
14
+ A class extending the BaseValidator class for validation based on a classification model.
15
+
16
+ This validator handles the validation process for classification models, including metrics calculation,
17
+ confusion matrix generation, and visualization of results.
18
+
19
+ Attributes:
20
+ targets (List[torch.Tensor]): Ground truth class labels.
21
+ pred (List[torch.Tensor]): Model predictions.
22
+ metrics (ClassifyMetrics): Object to calculate and store classification metrics.
23
+ names (dict): Mapping of class indices to class names.
24
+ nc (int): Number of classes.
25
+ confusion_matrix (ConfusionMatrix): Matrix to evaluate model performance across classes.
26
+
27
+ Methods:
28
+ get_desc: Return a formatted string summarizing classification metrics.
29
+ init_metrics: Initialize confusion matrix, class names, and tracking containers.
30
+ preprocess: Preprocess input batch by moving data to device.
31
+ update_metrics: Update running metrics with model predictions and batch targets.
32
+ finalize_metrics: Finalize metrics including confusion matrix and processing speed.
33
+ postprocess: Extract the primary prediction from model output.
34
+ get_stats: Calculate and return a dictionary of metrics.
35
+ build_dataset: Create a ClassificationDataset instance for validation.
36
+ get_dataloader: Build and return a data loader for classification validation.
37
+ print_results: Print evaluation metrics for the classification model.
38
+ plot_val_samples: Plot validation image samples with their ground truth labels.
39
+ plot_predictions: Plot images with their predicted class labels.
40
+
41
+ Examples:
42
+ >>> from ultralytics.models.yolo.classify import ClassificationValidator
43
+ >>> args = dict(model="yolo11n-cls.pt", data="imagenet10")
44
+ >>> validator = ClassificationValidator(args=args)
45
+ >>> validator()
46
+
47
+ Notes:
48
+ Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'.
49
+ """
50
+
51
+ def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):
52
+ """
53
+ Initialize ClassificationValidator with dataloader, save directory, and other parameters.
54
+
55
+ This validator handles the validation process for classification models, including metrics calculation,
56
+ confusion matrix generation, and visualization of results.
57
+
58
+ Args:
59
+ dataloader (torch.utils.data.DataLoader, optional): Dataloader to use for validation.
60
+ save_dir (str | Path, optional): Directory to save results.
61
+ pbar (bool, optional): Display a progress bar.
62
+ args (dict, optional): Arguments containing model and validation configuration.
63
+ _callbacks (list, optional): List of callback functions to be called during validation.
64
+
65
+ Examples:
66
+ >>> from ultralytics.models.yolo.classify import ClassificationValidator
67
+ >>> args = dict(model="yolo11n-cls.pt", data="imagenet10")
68
+ >>> validator = ClassificationValidator(args=args)
69
+ >>> validator()
70
+ """
71
+ super().__init__(dataloader, save_dir, pbar, args, _callbacks)
72
+ self.targets = None
73
+ self.pred = None
74
+ self.args.task = "classify"
75
+ self.metrics = ClassifyMetrics()
76
+
77
+ def get_desc(self):
78
+ """Return a formatted string summarizing classification metrics."""
79
+ return ("%22s" + "%11s" * 2) % ("classes", "top1_acc", "top5_acc")
80
+
81
+ def init_metrics(self, model):
82
+ """Initialize confusion matrix, class names, and tracking containers for predictions and targets."""
83
+ self.names = model.names
84
+ self.nc = len(model.names)
85
+ self.confusion_matrix = ConfusionMatrix(nc=self.nc, conf=self.args.conf, task="classify")
86
+ self.pred = []
87
+ self.targets = []
88
+
89
+ def preprocess(self, batch):
90
+ """Preprocess input batch by moving data to device and converting to appropriate dtype."""
91
+ batch["img"] = batch["img"].to(self.device, non_blocking=True)
92
+ batch["img"] = batch["img"].half() if self.args.half else batch["img"].float()
93
+ batch["cls"] = batch["cls"].to(self.device)
94
+ return batch
95
+
96
+ def update_metrics(self, preds, batch):
97
+ """
98
+ Update running metrics with model predictions and batch targets.
99
+
100
+ Args:
101
+ preds (torch.Tensor): Model predictions, typically logits or probabilities for each class.
102
+ batch (dict): Batch data containing images and class labels.
103
+
104
+ This method appends the top-N predictions (sorted by confidence in descending order) to the
105
+ prediction list for later evaluation. N is limited to the minimum of 5 and the number of classes.
106
+ """
107
+ n5 = min(len(self.names), 5)
108
+ self.pred.append(preds.argsort(1, descending=True)[:, :n5].type(torch.int32).cpu())
109
+ self.targets.append(batch["cls"].type(torch.int32).cpu())
110
+
111
+ def finalize_metrics(self, *args, **kwargs):
112
+ """
113
+ Finalize metrics including confusion matrix and processing speed.
114
+
115
+ This method processes the accumulated predictions and targets to generate the confusion matrix,
116
+ optionally plots it, and updates the metrics object with speed information.
117
+
118
+ Args:
119
+ *args (Any): Variable length argument list.
120
+ **kwargs (Any): Arbitrary keyword arguments.
121
+
122
+ Examples:
123
+ >>> validator = ClassificationValidator()
124
+ >>> validator.pred = [torch.tensor([[0, 1, 2]])] # Top-3 predictions for one sample
125
+ >>> validator.targets = [torch.tensor([0])] # Ground truth class
126
+ >>> validator.finalize_metrics()
127
+ >>> print(validator.metrics.confusion_matrix) # Access the confusion matrix
128
+ """
129
+ self.confusion_matrix.process_cls_preds(self.pred, self.targets)
130
+ if self.args.plots:
131
+ for normalize in True, False:
132
+ self.confusion_matrix.plot(
133
+ save_dir=self.save_dir, names=self.names.values(), normalize=normalize, on_plot=self.on_plot
134
+ )
135
+ self.metrics.speed = self.speed
136
+ self.metrics.confusion_matrix = self.confusion_matrix
137
+ self.metrics.save_dir = self.save_dir
138
+
139
+ def postprocess(self, preds):
140
+ """Extract the primary prediction from model output if it's in a list or tuple format."""
141
+ return preds[0] if isinstance(preds, (list, tuple)) else preds
142
+
143
+ def get_stats(self):
144
+ """Calculate and return a dictionary of metrics by processing targets and predictions."""
145
+ self.metrics.process(self.targets, self.pred)
146
+ return self.metrics.results_dict
147
+
148
+ def build_dataset(self, img_path):
149
+ """Create a ClassificationDataset instance for validation."""
150
+ return ClassificationDataset(root=img_path, args=self.args, augment=False, prefix=self.args.split)
151
+
152
+ def get_dataloader(self, dataset_path, batch_size):
153
+ """
154
+ Build and return a data loader for classification validation.
155
+
156
+ Args:
157
+ dataset_path (str | Path): Path to the dataset directory.
158
+ batch_size (int): Number of samples per batch.
159
+
160
+ Returns:
161
+ (torch.utils.data.DataLoader): DataLoader object for the classification validation dataset.
162
+ """
163
+ dataset = self.build_dataset(dataset_path)
164
+ return build_dataloader(dataset, batch_size, self.args.workers, rank=-1)
165
+
166
+ def print_results(self):
167
+ """Print evaluation metrics for the classification model."""
168
+ pf = "%22s" + "%11.3g" * len(self.metrics.keys) # print format
169
+ LOGGER.info(pf % ("all", self.metrics.top1, self.metrics.top5))
170
+
171
+ def plot_val_samples(self, batch, ni):
172
+ """
173
+ Plot validation image samples with their ground truth labels.
174
+
175
+ Args:
176
+ batch (dict): Dictionary containing batch data with 'img' (images) and 'cls' (class labels).
177
+ ni (int): Batch index used for naming the output file.
178
+
179
+ Examples:
180
+ >>> validator = ClassificationValidator()
181
+ >>> batch = {"img": torch.rand(16, 3, 224, 224), "cls": torch.randint(0, 10, (16,))}
182
+ >>> validator.plot_val_samples(batch, 0)
183
+ """
184
+ plot_images(
185
+ images=batch["img"],
186
+ batch_idx=torch.arange(len(batch["img"])),
187
+ cls=batch["cls"].view(-1), # warning: use .view(), not .squeeze() for Classify models
188
+ fname=self.save_dir / f"val_batch{ni}_labels.jpg",
189
+ names=self.names,
190
+ on_plot=self.on_plot,
191
+ )
192
+
193
+ def plot_predictions(self, batch, preds, ni):
194
+ """
195
+ Plot images with their predicted class labels and save the visualization.
196
+
197
+ Args:
198
+ batch (dict): Batch data containing images and other information.
199
+ preds (torch.Tensor): Model predictions with shape (batch_size, num_classes).
200
+ ni (int): Batch index used for naming the output file.
201
+
202
+ Examples:
203
+ >>> validator = ClassificationValidator()
204
+ >>> batch = {"img": torch.rand(16, 3, 224, 224)}
205
+ >>> preds = torch.rand(16, 10) # 16 images, 10 classes
206
+ >>> validator.plot_predictions(batch, preds, 0)
207
+ """
208
+ plot_images(
209
+ batch["img"],
210
+ batch_idx=torch.arange(len(batch["img"])),
211
+ cls=torch.argmax(preds, dim=1),
212
+ fname=self.save_dir / f"val_batch{ni}_pred.jpg",
213
+ names=self.names,
214
+ on_plot=self.on_plot,
215
+ ) # pred
@@ -0,0 +1,7 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from .predict import DetectionPredictor
4
+ from .train import DetectionTrainer
5
+ from .val import DetectionValidator
6
+
7
+ __all__ = "DetectionPredictor", "DetectionTrainer", "DetectionValidator"
@@ -0,0 +1,124 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ from ultralytics.engine.predictor import BasePredictor
4
+ from ultralytics.engine.results import Results
5
+ from ultralytics.utils import ops
6
+
7
+
8
+ class DetectionPredictor(BasePredictor):
9
+ """
10
+ A class extending the BasePredictor class for prediction based on a detection model.
11
+
12
+ This predictor specializes in object detection tasks, processing model outputs into meaningful detection results
13
+ with bounding boxes and class predictions.
14
+
15
+ Attributes:
16
+ args (namespace): Configuration arguments for the predictor.
17
+ model (nn.Module): The detection model used for inference.
18
+ batch (list): Batch of images and metadata for processing.
19
+
20
+ Methods:
21
+ postprocess: Process raw model predictions into detection results.
22
+ construct_results: Build Results objects from processed predictions.
23
+ construct_result: Create a single Result object from a prediction.
24
+
25
+ Examples:
26
+ >>> from ultralytics.utils import ASSETS
27
+ >>> from ultralytics.models.yolo.detect import DetectionPredictor
28
+ >>> args = dict(model="yolo11n.pt", source=ASSETS)
29
+ >>> predictor = DetectionPredictor(overrides=args)
30
+ >>> predictor.predict_cli()
31
+ """
32
+
33
+ def postprocess(self, preds, img, orig_imgs, **kwargs):
34
+ """
35
+ Post-process predictions and return a list of Results objects.
36
+
37
+ This method applies non-maximum suppression to raw model predictions and prepares them for visualization and
38
+ further analysis.
39
+
40
+ Args:
41
+ preds (torch.Tensor): Raw predictions from the model.
42
+ img (torch.Tensor): Processed input image tensor in model input format.
43
+ orig_imgs (torch.Tensor | list): Original input images before preprocessing.
44
+ **kwargs (Any): Additional keyword arguments.
45
+
46
+ Returns:
47
+ (list): List of Results objects containing the post-processed predictions.
48
+
49
+ Examples:
50
+ >>> predictor = DetectionPredictor(overrides=dict(model="yolo11n.pt"))
51
+ >>> results = predictor.predict("path/to/image.jpg")
52
+ >>> processed_results = predictor.postprocess(preds, img, orig_imgs)
53
+ """
54
+ save_feats = getattr(self, "_feats", None) is not None
55
+ preds = ops.non_max_suppression(
56
+ preds,
57
+ self.args.conf,
58
+ self.args.iou,
59
+ self.args.classes,
60
+ self.args.agnostic_nms,
61
+ max_det=self.args.max_det,
62
+ nc=0 if self.args.task == "detect" else len(self.model.names),
63
+ end2end=getattr(self.model, "end2end", False),
64
+ rotated=self.args.task == "obb",
65
+ return_idxs=save_feats,
66
+ )
67
+
68
+ if not isinstance(orig_imgs, list): # input images are a torch.Tensor, not a list
69
+ orig_imgs = ops.convert_torch2numpy_batch(orig_imgs)
70
+
71
+ if save_feats:
72
+ obj_feats = self.get_obj_feats(self._feats, preds[1])
73
+ preds = preds[0]
74
+
75
+ results = self.construct_results(preds, img, orig_imgs, **kwargs)
76
+
77
+ if save_feats:
78
+ for r, f in zip(results, obj_feats):
79
+ r.feats = f # add object features to results
80
+
81
+ return results
82
+
83
+ def get_obj_feats(self, feat_maps, idxs):
84
+ """Extract object features from the feature maps."""
85
+ import torch
86
+
87
+ s = min([x.shape[1] for x in feat_maps]) # find smallest vector length
88
+ obj_feats = torch.cat(
89
+ [x.permute(0, 2, 3, 1).reshape(x.shape[0], -1, s, x.shape[1] // s).mean(dim=-1) for x in feat_maps], dim=1
90
+ ) # mean reduce all vectors to same length
91
+ return [feats[idx] if len(idx) else [] for feats, idx in zip(obj_feats, idxs)] # for each img in batch
92
+
93
+ def construct_results(self, preds, img, orig_imgs):
94
+ """
95
+ Construct a list of Results objects from model predictions.
96
+
97
+ Args:
98
+ preds (List[torch.Tensor]): List of predicted bounding boxes and scores for each image.
99
+ img (torch.Tensor): Batch of preprocessed images used for inference.
100
+ orig_imgs (List[np.ndarray]): List of original images before preprocessing.
101
+
102
+ Returns:
103
+ (List[Results]): List of Results objects containing detection information for each image.
104
+ """
105
+ return [
106
+ self.construct_result(pred, img, orig_img, img_path)
107
+ for pred, orig_img, img_path in zip(preds, orig_imgs, self.batch[0])
108
+ ]
109
+
110
+ def construct_result(self, pred, img, orig_img, img_path):
111
+ """
112
+ Construct a single Results object from one image prediction.
113
+
114
+ Args:
115
+ pred (torch.Tensor): Predicted boxes and scores with shape (N, 6) where N is the number of detections.
116
+ img (torch.Tensor): Preprocessed image tensor used for inference.
117
+ orig_img (np.ndarray): Original image before preprocessing.
118
+ img_path (str): Path to the original image file.
119
+
120
+ Returns:
121
+ (Results): Results object containing the original image, image path, class names, and scaled bounding boxes.
122
+ """
123
+ pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)
124
+ return Results(orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6])
@@ -0,0 +1,217 @@
1
+ # Ultralytics 🚀 AGPL-3.0 License - https://ultralytics.com/license
2
+
3
+ import math
4
+ import random
5
+ from copy import copy
6
+
7
+ import numpy as np
8
+ import torch.nn as nn
9
+
10
+ from ultralytics.data import build_dataloader, build_yolo_dataset
11
+ from ultralytics.engine.trainer import BaseTrainer
12
+ from ultralytics.models import yolo
13
+ from ultralytics.nn.tasks import DetectionModel
14
+ from ultralytics.utils import LOGGER, RANK
15
+ from ultralytics.utils.plotting import plot_images, plot_labels, plot_results
16
+ from ultralytics.utils.torch_utils import de_parallel, torch_distributed_zero_first
17
+
18
+
19
+ class DetectionTrainer(BaseTrainer):
20
+ """
21
+ A class extending the BaseTrainer class for training based on a detection model.
22
+
23
+ This trainer specializes in object detection tasks, handling the specific requirements for training YOLO models
24
+ for object detection.
25
+
26
+ Attributes:
27
+ model (DetectionModel): The YOLO detection model being trained.
28
+ data (dict): Dictionary containing dataset information including class names and number of classes.
29
+ loss_names (Tuple[str]): Names of the loss components used in training (box_loss, cls_loss, dfl_loss).
30
+
31
+ Methods:
32
+ build_dataset: Build YOLO dataset for training or validation.
33
+ get_dataloader: Construct and return dataloader for the specified mode.
34
+ preprocess_batch: Preprocess a batch of images by scaling and converting to float.
35
+ set_model_attributes: Set model attributes based on dataset information.
36
+ get_model: Return a YOLO detection model.
37
+ get_validator: Return a validator for model evaluation.
38
+ label_loss_items: Return a loss dictionary with labeled training loss items.
39
+ progress_string: Return a formatted string of training progress.
40
+ plot_training_samples: Plot training samples with their annotations.
41
+ plot_metrics: Plot metrics from a CSV file.
42
+ plot_training_labels: Create a labeled training plot of the YOLO model.
43
+ auto_batch: Calculate optimal batch size based on model memory requirements.
44
+
45
+ Examples:
46
+ >>> from ultralytics.models.yolo.detect import DetectionTrainer
47
+ >>> args = dict(model="yolo11n.pt", data="coco8.yaml", epochs=3)
48
+ >>> trainer = DetectionTrainer(overrides=args)
49
+ >>> trainer.train()
50
+ """
51
+
52
+ def build_dataset(self, img_path, mode="train", batch=None):
53
+ """
54
+ Build YOLO Dataset for training or validation.
55
+
56
+ Args:
57
+ img_path (str): Path to the folder containing images.
58
+ mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.
59
+ batch (int, optional): Size of batches, this is for `rect`.
60
+
61
+ Returns:
62
+ (Dataset): YOLO dataset object configured for the specified mode.
63
+ """
64
+ gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)
65
+ return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, rect=mode == "val", stride=gs)
66
+
67
+ def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode="train"):
68
+ """
69
+ Construct and return dataloader for the specified mode.
70
+
71
+ Args:
72
+ dataset_path (str): Path to the dataset.
73
+ batch_size (int): Number of images per batch.
74
+ rank (int): Process rank for distributed training.
75
+ mode (str): 'train' for training dataloader, 'val' for validation dataloader.
76
+
77
+ Returns:
78
+ (DataLoader): PyTorch dataloader object.
79
+ """
80
+ assert mode in {"train", "val"}, f"Mode must be 'train' or 'val', not {mode}."
81
+ with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
82
+ dataset = self.build_dataset(dataset_path, mode, batch_size)
83
+ shuffle = mode == "train"
84
+ if getattr(dataset, "rect", False) and shuffle:
85
+ LOGGER.warning("'rect=True' is incompatible with DataLoader shuffle, setting shuffle=False")
86
+ shuffle = False
87
+ workers = self.args.workers if mode == "train" else self.args.workers * 2
88
+ return build_dataloader(dataset, batch_size, workers, shuffle, rank) # return dataloader
89
+
90
+ def preprocess_batch(self, batch):
91
+ """
92
+ Preprocess a batch of images by scaling and converting to float.
93
+
94
+ Args:
95
+ batch (dict): Dictionary containing batch data with 'img' tensor.
96
+
97
+ Returns:
98
+ (dict): Preprocessed batch with normalized images.
99
+ """
100
+ batch["img"] = batch["img"].to(self.device, non_blocking=True).float() / 255
101
+ if self.args.multi_scale:
102
+ imgs = batch["img"]
103
+ sz = (
104
+ random.randrange(int(self.args.imgsz * 0.5), int(self.args.imgsz * 1.5 + self.stride))
105
+ // self.stride
106
+ * self.stride
107
+ ) # size
108
+ sf = sz / max(imgs.shape[2:]) # scale factor
109
+ if sf != 1:
110
+ ns = [
111
+ math.ceil(x * sf / self.stride) * self.stride for x in imgs.shape[2:]
112
+ ] # new shape (stretched to gs-multiple)
113
+ imgs = nn.functional.interpolate(imgs, size=ns, mode="bilinear", align_corners=False)
114
+ batch["img"] = imgs
115
+ return batch
116
+
117
+ def set_model_attributes(self):
118
+ """Set model attributes based on dataset information."""
119
+ # Nl = de_parallel(self.model).model[-1].nl # number of detection layers (to scale hyps)
120
+ # self.args.box *= 3 / nl # scale to layers
121
+ # self.args.cls *= self.data["nc"] / 80 * 3 / nl # scale to classes and layers
122
+ # self.args.cls *= (self.args.imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
123
+ self.model.nc = self.data["nc"] # attach number of classes to model
124
+ self.model.names = self.data["names"] # attach class names to model
125
+ self.model.args = self.args # attach hyperparameters to model
126
+ # TODO: self.model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc
127
+
128
+ def get_model(self, cfg=None, weights=None, verbose=True):
129
+ """
130
+ Return a YOLO detection model.
131
+
132
+ Args:
133
+ cfg (str, optional): Path to model configuration file.
134
+ weights (str, optional): Path to model weights.
135
+ verbose (bool): Whether to display model information.
136
+
137
+ Returns:
138
+ (DetectionModel): YOLO detection model.
139
+ """
140
+ model = DetectionModel(cfg, nc=self.data["nc"], ch=self.data["channels"], verbose=verbose and RANK == -1)
141
+ if weights:
142
+ model.load(weights)
143
+ return model
144
+
145
+ def get_validator(self):
146
+ """Return a DetectionValidator for YOLO model validation."""
147
+ self.loss_names = "box_loss", "cls_loss", "dfl_loss"
148
+ return yolo.detect.DetectionValidator(
149
+ self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks
150
+ )
151
+
152
+ def label_loss_items(self, loss_items=None, prefix="train"):
153
+ """
154
+ Return a loss dict with labeled training loss items tensor.
155
+
156
+ Args:
157
+ loss_items (List[float], optional): List of loss values.
158
+ prefix (str): Prefix for keys in the returned dictionary.
159
+
160
+ Returns:
161
+ (Dict | List): Dictionary of labeled loss items if loss_items is provided, otherwise list of keys.
162
+ """
163
+ keys = [f"{prefix}/{x}" for x in self.loss_names]
164
+ if loss_items is not None:
165
+ loss_items = [round(float(x), 5) for x in loss_items] # convert tensors to 5 decimal place floats
166
+ return dict(zip(keys, loss_items))
167
+ else:
168
+ return keys
169
+
170
+ def progress_string(self):
171
+ """Return a formatted string of training progress with epoch, GPU memory, loss, instances and size."""
172
+ return ("\n" + "%11s" * (4 + len(self.loss_names))) % (
173
+ "Epoch",
174
+ "GPU_mem",
175
+ *self.loss_names,
176
+ "Instances",
177
+ "Size",
178
+ )
179
+
180
+ def plot_training_samples(self, batch, ni):
181
+ """
182
+ Plot training samples with their annotations.
183
+
184
+ Args:
185
+ batch (dict): Dictionary containing batch data.
186
+ ni (int): Number of iterations.
187
+ """
188
+ plot_images(
189
+ images=batch["img"],
190
+ batch_idx=batch["batch_idx"],
191
+ cls=batch["cls"].squeeze(-1),
192
+ bboxes=batch["bboxes"],
193
+ paths=batch["im_file"],
194
+ fname=self.save_dir / f"train_batch{ni}.jpg",
195
+ on_plot=self.on_plot,
196
+ )
197
+
198
+ def plot_metrics(self):
199
+ """Plot metrics from a CSV file."""
200
+ plot_results(file=self.csv, on_plot=self.on_plot) # save results.png
201
+
202
+ def plot_training_labels(self):
203
+ """Create a labeled training plot of the YOLO model."""
204
+ boxes = np.concatenate([lb["bboxes"] for lb in self.train_loader.dataset.labels], 0)
205
+ cls = np.concatenate([lb["cls"] for lb in self.train_loader.dataset.labels], 0)
206
+ plot_labels(boxes, cls.squeeze(), names=self.data["names"], save_dir=self.save_dir, on_plot=self.on_plot)
207
+
208
+ def auto_batch(self):
209
+ """
210
+ Get optimal batch size by calculating memory occupation of model.
211
+
212
+ Returns:
213
+ (int): Optimal batch size.
214
+ """
215
+ train_dataset = self.build_dataset(self.data["train"], mode="train", batch=16)
216
+ max_num_obj = max(len(label["cls"]) for label in train_dataset.labels) * 4 # 4 for mosaic augmentation
217
+ return super().auto_batch(max_num_obj)