ultralytics 8.3.88__py3-none-any.whl → 8.3.90__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 (155) hide show
  1. tests/conftest.py +2 -2
  2. tests/test_cli.py +13 -11
  3. tests/test_cuda.py +10 -1
  4. tests/test_integrations.py +1 -5
  5. tests/test_python.py +16 -16
  6. tests/test_solutions.py +9 -9
  7. ultralytics/__init__.py +1 -1
  8. ultralytics/cfg/__init__.py +3 -1
  9. ultralytics/cfg/models/11/yolo11-cls.yaml +5 -5
  10. ultralytics/cfg/models/11/yolo11-obb.yaml +5 -5
  11. ultralytics/cfg/models/11/yolo11-pose.yaml +5 -5
  12. ultralytics/cfg/models/11/yolo11-seg.yaml +5 -5
  13. ultralytics/cfg/models/11/yolo11.yaml +5 -5
  14. ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +5 -5
  15. ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +5 -5
  16. ultralytics/cfg/models/v8/yolov8-ghost.yaml +5 -5
  17. ultralytics/cfg/models/v8/yolov8-obb.yaml +5 -5
  18. ultralytics/cfg/models/v8/yolov8-p6.yaml +5 -5
  19. ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +5 -5
  20. ultralytics/cfg/models/v8/yolov8-world.yaml +5 -5
  21. ultralytics/cfg/models/v8/yolov8-worldv2.yaml +5 -5
  22. ultralytics/cfg/models/v8/yolov8.yaml +5 -5
  23. ultralytics/cfg/models/v9/yolov9c-seg.yaml +1 -1
  24. ultralytics/cfg/models/v9/yolov9c.yaml +1 -1
  25. ultralytics/cfg/models/v9/yolov9e-seg.yaml +1 -1
  26. ultralytics/cfg/models/v9/yolov9e.yaml +1 -1
  27. ultralytics/cfg/models/v9/yolov9m.yaml +1 -1
  28. ultralytics/cfg/models/v9/yolov9s.yaml +1 -1
  29. ultralytics/cfg/models/v9/yolov9t.yaml +1 -1
  30. ultralytics/data/annotator.py +9 -14
  31. ultralytics/data/base.py +125 -39
  32. ultralytics/data/build.py +63 -24
  33. ultralytics/data/converter.py +34 -33
  34. ultralytics/data/dataset.py +207 -53
  35. ultralytics/data/loaders.py +1 -0
  36. ultralytics/data/split_dota.py +39 -12
  37. ultralytics/data/utils.py +33 -47
  38. ultralytics/engine/exporter.py +19 -17
  39. ultralytics/engine/model.py +69 -90
  40. ultralytics/engine/predictor.py +106 -21
  41. ultralytics/engine/trainer.py +32 -23
  42. ultralytics/engine/tuner.py +31 -38
  43. ultralytics/engine/validator.py +75 -41
  44. ultralytics/hub/__init__.py +21 -26
  45. ultralytics/hub/auth.py +9 -12
  46. ultralytics/hub/session.py +76 -21
  47. ultralytics/hub/utils.py +19 -17
  48. ultralytics/models/fastsam/model.py +23 -17
  49. ultralytics/models/fastsam/predict.py +36 -16
  50. ultralytics/models/fastsam/utils.py +5 -5
  51. ultralytics/models/fastsam/val.py +6 -6
  52. ultralytics/models/nas/model.py +29 -24
  53. ultralytics/models/nas/predict.py +14 -11
  54. ultralytics/models/nas/val.py +11 -13
  55. ultralytics/models/rtdetr/model.py +20 -11
  56. ultralytics/models/rtdetr/predict.py +21 -21
  57. ultralytics/models/rtdetr/train.py +25 -24
  58. ultralytics/models/rtdetr/val.py +47 -14
  59. ultralytics/models/sam/__init__.py +1 -1
  60. ultralytics/models/sam/amg.py +50 -4
  61. ultralytics/models/sam/model.py +8 -14
  62. ultralytics/models/sam/modules/decoders.py +18 -21
  63. ultralytics/models/sam/modules/encoders.py +25 -46
  64. ultralytics/models/sam/modules/memory_attention.py +19 -15
  65. ultralytics/models/sam/modules/sam.py +18 -25
  66. ultralytics/models/sam/modules/tiny_encoder.py +19 -29
  67. ultralytics/models/sam/modules/transformer.py +35 -57
  68. ultralytics/models/sam/modules/utils.py +15 -15
  69. ultralytics/models/sam/predict.py +0 -3
  70. ultralytics/models/utils/loss.py +87 -36
  71. ultralytics/models/utils/ops.py +26 -31
  72. ultralytics/models/yolo/classify/predict.py +30 -12
  73. ultralytics/models/yolo/classify/train.py +83 -19
  74. ultralytics/models/yolo/classify/val.py +45 -23
  75. ultralytics/models/yolo/detect/predict.py +29 -19
  76. ultralytics/models/yolo/detect/train.py +90 -23
  77. ultralytics/models/yolo/detect/val.py +150 -29
  78. ultralytics/models/yolo/model.py +1 -2
  79. ultralytics/models/yolo/obb/predict.py +18 -13
  80. ultralytics/models/yolo/obb/train.py +12 -8
  81. ultralytics/models/yolo/obb/val.py +35 -22
  82. ultralytics/models/yolo/pose/predict.py +28 -15
  83. ultralytics/models/yolo/pose/train.py +21 -8
  84. ultralytics/models/yolo/pose/val.py +51 -31
  85. ultralytics/models/yolo/segment/predict.py +27 -16
  86. ultralytics/models/yolo/segment/train.py +11 -8
  87. ultralytics/models/yolo/segment/val.py +110 -29
  88. ultralytics/models/yolo/world/train.py +43 -16
  89. ultralytics/models/yolo/world/train_world.py +61 -36
  90. ultralytics/nn/autobackend.py +28 -14
  91. ultralytics/nn/modules/__init__.py +12 -12
  92. ultralytics/nn/modules/activation.py +12 -3
  93. ultralytics/nn/modules/block.py +587 -84
  94. ultralytics/nn/modules/conv.py +418 -54
  95. ultralytics/nn/modules/head.py +3 -4
  96. ultralytics/nn/modules/transformer.py +320 -34
  97. ultralytics/nn/modules/utils.py +17 -3
  98. ultralytics/nn/tasks.py +226 -79
  99. ultralytics/solutions/ai_gym.py +2 -2
  100. ultralytics/solutions/analytics.py +4 -4
  101. ultralytics/solutions/heatmap.py +4 -4
  102. ultralytics/solutions/instance_segmentation.py +10 -4
  103. ultralytics/solutions/object_blurrer.py +2 -2
  104. ultralytics/solutions/object_counter.py +2 -2
  105. ultralytics/solutions/object_cropper.py +2 -2
  106. ultralytics/solutions/parking_management.py +9 -9
  107. ultralytics/solutions/queue_management.py +1 -1
  108. ultralytics/solutions/region_counter.py +2 -2
  109. ultralytics/solutions/security_alarm.py +7 -7
  110. ultralytics/solutions/solutions.py +7 -4
  111. ultralytics/solutions/speed_estimation.py +2 -2
  112. ultralytics/solutions/streamlit_inference.py +6 -6
  113. ultralytics/solutions/trackzone.py +9 -2
  114. ultralytics/solutions/vision_eye.py +4 -4
  115. ultralytics/trackers/basetrack.py +1 -1
  116. ultralytics/trackers/bot_sort.py +23 -22
  117. ultralytics/trackers/byte_tracker.py +4 -4
  118. ultralytics/trackers/track.py +2 -1
  119. ultralytics/trackers/utils/gmc.py +26 -27
  120. ultralytics/trackers/utils/kalman_filter.py +31 -29
  121. ultralytics/trackers/utils/matching.py +7 -7
  122. ultralytics/utils/__init__.py +37 -35
  123. ultralytics/utils/autobatch.py +5 -5
  124. ultralytics/utils/benchmarks.py +111 -18
  125. ultralytics/utils/callbacks/base.py +3 -3
  126. ultralytics/utils/callbacks/clearml.py +11 -11
  127. ultralytics/utils/callbacks/comet.py +35 -22
  128. ultralytics/utils/callbacks/dvc.py +11 -10
  129. ultralytics/utils/callbacks/hub.py +8 -8
  130. ultralytics/utils/callbacks/mlflow.py +1 -1
  131. ultralytics/utils/callbacks/neptune.py +12 -10
  132. ultralytics/utils/callbacks/raytune.py +1 -1
  133. ultralytics/utils/callbacks/tensorboard.py +6 -6
  134. ultralytics/utils/callbacks/wb.py +16 -16
  135. ultralytics/utils/checks.py +139 -68
  136. ultralytics/utils/dist.py +15 -2
  137. ultralytics/utils/downloads.py +37 -56
  138. ultralytics/utils/files.py +12 -13
  139. ultralytics/utils/instance.py +117 -52
  140. ultralytics/utils/loss.py +28 -33
  141. ultralytics/utils/metrics.py +246 -181
  142. ultralytics/utils/ops.py +65 -61
  143. ultralytics/utils/patches.py +8 -6
  144. ultralytics/utils/plotting.py +72 -59
  145. ultralytics/utils/tal.py +88 -57
  146. ultralytics/utils/torch_utils.py +202 -64
  147. ultralytics/utils/triton.py +13 -3
  148. ultralytics/utils/tuner.py +13 -25
  149. {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/METADATA +2 -2
  150. ultralytics-8.3.90.dist-info/RECORD +250 -0
  151. ultralytics-8.3.88.dist-info/RECORD +0 -250
  152. {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/LICENSE +0 -0
  153. {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/WHEEL +0 -0
  154. {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/entry_points.txt +0 -0
  155. {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/top_level.txt +0 -0
@@ -13,21 +13,43 @@ class ClassificationValidator(BaseValidator):
13
13
  """
14
14
  A class extending the BaseValidator class for validation based on a classification model.
15
15
 
16
- Notes:
17
- - Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'.
18
-
19
- Example:
20
- ```python
21
- from ultralytics.models.yolo.classify import ClassificationValidator
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()
22
46
 
23
- args = dict(model="yolo11n-cls.pt", data="imagenet10")
24
- validator = ClassificationValidator(args=args)
25
- validator()
26
- ```
47
+ Notes:
48
+ Torchvision classification models can also be passed to the 'model' argument, i.e. model='resnet18'.
27
49
  """
28
50
 
29
51
  def __init__(self, dataloader=None, save_dir=None, pbar=None, args=None, _callbacks=None):
30
- """Initializes ClassificationValidator instance with args, dataloader, save_dir, and progress bar."""
52
+ """Initialize ClassificationValidator with dataloader, save directory, and other parameters."""
31
53
  super().__init__(dataloader, save_dir, pbar, args, _callbacks)
32
54
  self.targets = None
33
55
  self.pred = None
@@ -35,11 +57,11 @@ class ClassificationValidator(BaseValidator):
35
57
  self.metrics = ClassifyMetrics()
36
58
 
37
59
  def get_desc(self):
38
- """Returns a formatted string summarizing classification metrics."""
60
+ """Return a formatted string summarizing classification metrics."""
39
61
  return ("%22s" + "%11s" * 2) % ("classes", "top1_acc", "top5_acc")
40
62
 
41
63
  def init_metrics(self, model):
42
- """Initialize confusion matrix, class names, and top-1 and top-5 accuracy."""
64
+ """Initialize confusion matrix, class names, and tracking containers for predictions and targets."""
43
65
  self.names = model.names
44
66
  self.nc = len(model.names)
45
67
  self.confusion_matrix = ConfusionMatrix(nc=self.nc, conf=self.args.conf, task="classify")
@@ -47,20 +69,20 @@ class ClassificationValidator(BaseValidator):
47
69
  self.targets = []
48
70
 
49
71
  def preprocess(self, batch):
50
- """Preprocesses input batch and returns it."""
72
+ """Preprocess input batch by moving data to device and converting to appropriate dtype."""
51
73
  batch["img"] = batch["img"].to(self.device, non_blocking=True)
52
74
  batch["img"] = batch["img"].half() if self.args.half else batch["img"].float()
53
75
  batch["cls"] = batch["cls"].to(self.device)
54
76
  return batch
55
77
 
56
78
  def update_metrics(self, preds, batch):
57
- """Updates running metrics with model predictions and batch targets."""
79
+ """Update running metrics with model predictions and batch targets."""
58
80
  n5 = min(len(self.names), 5)
59
81
  self.pred.append(preds.argsort(1, descending=True)[:, :n5].type(torch.int32).cpu())
60
82
  self.targets.append(batch["cls"].type(torch.int32).cpu())
61
83
 
62
84
  def finalize_metrics(self, *args, **kwargs):
63
- """Finalizes metrics of the model such as confusion_matrix and speed."""
85
+ """Finalize metrics including confusion matrix and processing speed."""
64
86
  self.confusion_matrix.process_cls_preds(self.pred, self.targets)
65
87
  if self.args.plots:
66
88
  for normalize in True, False:
@@ -72,30 +94,30 @@ class ClassificationValidator(BaseValidator):
72
94
  self.metrics.save_dir = self.save_dir
73
95
 
74
96
  def postprocess(self, preds):
75
- """Preprocesses the classification predictions."""
97
+ """Extract the primary prediction from model output if it's in a list or tuple format."""
76
98
  return preds[0] if isinstance(preds, (list, tuple)) else preds
77
99
 
78
100
  def get_stats(self):
79
- """Returns a dictionary of metrics obtained by processing targets and predictions."""
101
+ """Calculate and return a dictionary of metrics by processing targets and predictions."""
80
102
  self.metrics.process(self.targets, self.pred)
81
103
  return self.metrics.results_dict
82
104
 
83
105
  def build_dataset(self, img_path):
84
- """Creates and returns a ClassificationDataset instance using given image path and preprocessing parameters."""
106
+ """Create a ClassificationDataset instance for validation."""
85
107
  return ClassificationDataset(root=img_path, args=self.args, augment=False, prefix=self.args.split)
86
108
 
87
109
  def get_dataloader(self, dataset_path, batch_size):
88
- """Builds and returns a data loader for classification tasks with given parameters."""
110
+ """Build and return a data loader for classification validation."""
89
111
  dataset = self.build_dataset(dataset_path)
90
112
  return build_dataloader(dataset, batch_size, self.args.workers, rank=-1)
91
113
 
92
114
  def print_results(self):
93
- """Prints evaluation metrics for YOLO object detection model."""
115
+ """Print evaluation metrics for the classification model."""
94
116
  pf = "%22s" + "%11.3g" * len(self.metrics.keys) # print format
95
117
  LOGGER.info(pf % ("all", self.metrics.top1, self.metrics.top5))
96
118
 
97
119
  def plot_val_samples(self, batch, ni):
98
- """Plot validation image samples."""
120
+ """Plot validation image samples with their ground truth labels."""
99
121
  plot_images(
100
122
  images=batch["img"],
101
123
  batch_idx=torch.arange(len(batch["img"])),
@@ -106,7 +128,7 @@ class ClassificationValidator(BaseValidator):
106
128
  )
107
129
 
108
130
  def plot_predictions(self, batch, preds, ni):
109
- """Plots predicted bounding boxes on input images and saves the result."""
131
+ """Plot images with their predicted class labels and save the visualization."""
110
132
  plot_images(
111
133
  batch["img"],
112
134
  batch_idx=torch.arange(len(batch["img"])),
@@ -9,15 +9,25 @@ class DetectionPredictor(BasePredictor):
9
9
  """
10
10
  A class extending the BasePredictor class for prediction based on a detection model.
11
11
 
12
- Example:
13
- ```python
14
- from ultralytics.utils import ASSETS
15
- from ultralytics.models.yolo.detect import DetectionPredictor
16
-
17
- args = dict(model="yolo11n.pt", source=ASSETS)
18
- predictor = DetectionPredictor(overrides=args)
19
- predictor.predict_cli()
20
- ```
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()
21
31
  """
22
32
 
23
33
  def postprocess(self, preds, img, orig_imgs, **kwargs):
@@ -41,15 +51,15 @@ class DetectionPredictor(BasePredictor):
41
51
 
42
52
  def construct_results(self, preds, img, orig_imgs):
43
53
  """
44
- Constructs a list of result objects from the predictions.
54
+ Construct a list of Results objects from model predictions.
45
55
 
46
56
  Args:
47
- preds (List[torch.Tensor]): List of predicted bounding boxes and scores.
48
- img (torch.Tensor): The image after preprocessing.
57
+ preds (List[torch.Tensor]): List of predicted bounding boxes and scores for each image.
58
+ img (torch.Tensor): Batch of preprocessed images used for inference.
49
59
  orig_imgs (List[np.ndarray]): List of original images before preprocessing.
50
60
 
51
61
  Returns:
52
- (list): List of result objects containing the original images, image paths, class names, and bounding boxes.
62
+ (List[Results]): List of Results objects containing detection information for each image.
53
63
  """
54
64
  return [
55
65
  self.construct_result(pred, img, orig_img, img_path)
@@ -58,16 +68,16 @@ class DetectionPredictor(BasePredictor):
58
68
 
59
69
  def construct_result(self, pred, img, orig_img, img_path):
60
70
  """
61
- Constructs the result object from the prediction.
71
+ Construct a single Results object from one image prediction.
62
72
 
63
73
  Args:
64
- pred (torch.Tensor): The predicted bounding boxes and scores.
65
- img (torch.Tensor): The image after preprocessing.
66
- orig_img (np.ndarray): The original image before preprocessing.
67
- img_path (str): The path to the original image.
74
+ pred (torch.Tensor): Predicted boxes and scores with shape (N, 6) where N is the number of detections.
75
+ img (torch.Tensor): Preprocessed image tensor used for inference.
76
+ orig_img (np.ndarray): Original image before preprocessing.
77
+ img_path (str): Path to the original image file.
68
78
 
69
79
  Returns:
70
- (Results): The result object containing the original image, image path, class names, and bounding boxes.
80
+ (Results): Results object containing the original image, image path, class names, and scaled bounding boxes.
71
81
  """
72
82
  pred[:, :4] = ops.scale_boxes(img.shape[2:], pred[:, :4], orig_img.shape)
73
83
  return Results(orig_img, path=img_path, names=self.model.names, boxes=pred[:, :6])
@@ -20,30 +20,63 @@ class DetectionTrainer(BaseTrainer):
20
20
  """
21
21
  A class extending the BaseTrainer class for training based on a detection model.
22
22
 
23
- Example:
24
- ```python
25
- from ultralytics.models.yolo.detect import DetectionTrainer
26
-
27
- args = dict(model="yolo11n.pt", data="coco8.yaml", epochs=3)
28
- trainer = DetectionTrainer(overrides=args)
29
- trainer.train()
30
- ```
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()
31
50
  """
32
51
 
33
52
  def build_dataset(self, img_path, mode="train", batch=None):
34
53
  """
35
- Build YOLO Dataset.
54
+ Build YOLO Dataset for training or validation.
36
55
 
37
56
  Args:
38
57
  img_path (str): Path to the folder containing images.
39
58
  mode (str): `train` mode or `val` mode, users are able to customize different augmentations for each mode.
40
- batch (int, optional): Size of batches, this is for `rect`. Defaults to None.
59
+ batch (int, optional): Size of batches, this is for `rect`.
60
+
61
+ Returns:
62
+ (Dataset): YOLO dataset object configured for the specified mode.
41
63
  """
42
64
  gs = max(int(de_parallel(self.model).stride.max() if self.model else 0), 32)
43
65
  return build_yolo_dataset(self.args, img_path, batch, self.data, mode=mode, rect=mode == "val", stride=gs)
44
66
 
45
67
  def get_dataloader(self, dataset_path, batch_size=16, rank=0, mode="train"):
46
- """Construct and return dataloader."""
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
+ """
47
80
  assert mode in {"train", "val"}, f"Mode must be 'train' or 'val', not {mode}."
48
81
  with torch_distributed_zero_first(rank): # init dataset *.cache only once if DDP
49
82
  dataset = self.build_dataset(dataset_path, mode, batch_size)
@@ -55,7 +88,15 @@ class DetectionTrainer(BaseTrainer):
55
88
  return build_dataloader(dataset, batch_size, workers, shuffle, rank) # return dataloader
56
89
 
57
90
  def preprocess_batch(self, batch):
58
- """Preprocesses a batch of images by scaling and converting to float."""
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
+ """
59
100
  batch["img"] = batch["img"].to(self.device, non_blocking=True).float() / 255
60
101
  if self.args.multi_scale:
61
102
  imgs = batch["img"]
@@ -74,7 +115,8 @@ class DetectionTrainer(BaseTrainer):
74
115
  return batch
75
116
 
76
117
  def set_model_attributes(self):
77
- """Nl = de_parallel(self.model).model[-1].nl # number of detection layers (to scale hyps)."""
118
+ """Set model attributes based on dataset information."""
119
+ # Nl = de_parallel(self.model).model[-1].nl # number of detection layers (to scale hyps)
78
120
  # self.args.box *= 3 / nl # scale to layers
79
121
  # self.args.cls *= self.data["nc"] / 80 * 3 / nl # scale to classes and layers
80
122
  # self.args.cls *= (self.args.imgsz / 640) ** 2 * 3 / nl # scale to image size and layers
@@ -84,14 +126,24 @@ class DetectionTrainer(BaseTrainer):
84
126
  # TODO: self.model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc
85
127
 
86
128
  def get_model(self, cfg=None, weights=None, verbose=True):
87
- """Return a YOLO detection model."""
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
+ """
88
140
  model = DetectionModel(cfg, nc=self.data["nc"], verbose=verbose and RANK == -1)
89
141
  if weights:
90
142
  model.load(weights)
91
143
  return model
92
144
 
93
145
  def get_validator(self):
94
- """Returns a DetectionValidator for YOLO model validation."""
146
+ """Return a DetectionValidator for YOLO model validation."""
95
147
  self.loss_names = "box_loss", "cls_loss", "dfl_loss"
96
148
  return yolo.detect.DetectionValidator(
97
149
  self.test_loader, save_dir=self.save_dir, args=copy(self.args), _callbacks=self.callbacks
@@ -99,9 +151,14 @@ class DetectionTrainer(BaseTrainer):
99
151
 
100
152
  def label_loss_items(self, loss_items=None, prefix="train"):
101
153
  """
102
- Returns a loss dict with labelled training loss items tensor.
154
+ Return a loss dict with labeled training loss items tensor.
103
155
 
104
- Not needed for classification but necessary for segmentation & detection
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.
105
162
  """
106
163
  keys = [f"{prefix}/{x}" for x in self.loss_names]
107
164
  if loss_items is not None:
@@ -111,7 +168,7 @@ class DetectionTrainer(BaseTrainer):
111
168
  return keys
112
169
 
113
170
  def progress_string(self):
114
- """Returns a formatted string of training progress with epoch, GPU memory, loss, instances and size."""
171
+ """Return a formatted string of training progress with epoch, GPU memory, loss, instances and size."""
115
172
  return ("\n" + "%11s" * (4 + len(self.loss_names))) % (
116
173
  "Epoch",
117
174
  "GPU_mem",
@@ -121,7 +178,13 @@ class DetectionTrainer(BaseTrainer):
121
178
  )
122
179
 
123
180
  def plot_training_samples(self, batch, ni):
124
- """Plots training samples with their annotations."""
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
+ """
125
188
  plot_images(
126
189
  images=batch["img"],
127
190
  batch_idx=batch["batch_idx"],
@@ -133,7 +196,7 @@ class DetectionTrainer(BaseTrainer):
133
196
  )
134
197
 
135
198
  def plot_metrics(self):
136
- """Plots metrics from a CSV file."""
199
+ """Plot metrics from a CSV file."""
137
200
  plot_results(file=self.csv, on_plot=self.on_plot) # save results.png
138
201
 
139
202
  def plot_training_labels(self):
@@ -143,8 +206,12 @@ class DetectionTrainer(BaseTrainer):
143
206
  plot_labels(boxes, cls.squeeze(), names=self.data["names"], save_dir=self.save_dir, on_plot=self.on_plot)
144
207
 
145
208
  def auto_batch(self):
146
- """Get batch size by calculating memory occupation of model."""
209
+ """
210
+ Get optimal batch size by calculating memory occupation of model.
211
+
212
+ Returns:
213
+ (int): Optimal batch size.
214
+ """
147
215
  train_dataset = self.build_dataset(self.trainset, mode="train", batch=16)
148
- # 4 for mosaic augmentation
149
- max_num_obj = max(len(label["cls"]) for label in train_dataset.labels) * 4
216
+ max_num_obj = max(len(label["cls"]) for label in train_dataset.labels) * 4 # 4 for mosaic augmentation
150
217
  return super().auto_batch(max_num_obj)