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.
- tests/conftest.py +2 -2
- tests/test_cli.py +13 -11
- tests/test_cuda.py +10 -1
- tests/test_integrations.py +1 -5
- tests/test_python.py +16 -16
- tests/test_solutions.py +9 -9
- ultralytics/__init__.py +1 -1
- ultralytics/cfg/__init__.py +3 -1
- ultralytics/cfg/models/11/yolo11-cls.yaml +5 -5
- ultralytics/cfg/models/11/yolo11-obb.yaml +5 -5
- ultralytics/cfg/models/11/yolo11-pose.yaml +5 -5
- ultralytics/cfg/models/11/yolo11-seg.yaml +5 -5
- ultralytics/cfg/models/11/yolo11.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8-ghost-p2.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8-ghost-p6.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8-ghost.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8-obb.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8-p6.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8-rtdetr.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8-world.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8-worldv2.yaml +5 -5
- ultralytics/cfg/models/v8/yolov8.yaml +5 -5
- ultralytics/cfg/models/v9/yolov9c-seg.yaml +1 -1
- ultralytics/cfg/models/v9/yolov9c.yaml +1 -1
- ultralytics/cfg/models/v9/yolov9e-seg.yaml +1 -1
- ultralytics/cfg/models/v9/yolov9e.yaml +1 -1
- ultralytics/cfg/models/v9/yolov9m.yaml +1 -1
- ultralytics/cfg/models/v9/yolov9s.yaml +1 -1
- ultralytics/cfg/models/v9/yolov9t.yaml +1 -1
- ultralytics/data/annotator.py +9 -14
- ultralytics/data/base.py +125 -39
- ultralytics/data/build.py +63 -24
- ultralytics/data/converter.py +34 -33
- ultralytics/data/dataset.py +207 -53
- ultralytics/data/loaders.py +1 -0
- ultralytics/data/split_dota.py +39 -12
- ultralytics/data/utils.py +33 -47
- ultralytics/engine/exporter.py +19 -17
- ultralytics/engine/model.py +69 -90
- ultralytics/engine/predictor.py +106 -21
- ultralytics/engine/trainer.py +32 -23
- ultralytics/engine/tuner.py +31 -38
- ultralytics/engine/validator.py +75 -41
- ultralytics/hub/__init__.py +21 -26
- ultralytics/hub/auth.py +9 -12
- ultralytics/hub/session.py +76 -21
- ultralytics/hub/utils.py +19 -17
- ultralytics/models/fastsam/model.py +23 -17
- ultralytics/models/fastsam/predict.py +36 -16
- ultralytics/models/fastsam/utils.py +5 -5
- ultralytics/models/fastsam/val.py +6 -6
- ultralytics/models/nas/model.py +29 -24
- ultralytics/models/nas/predict.py +14 -11
- ultralytics/models/nas/val.py +11 -13
- ultralytics/models/rtdetr/model.py +20 -11
- ultralytics/models/rtdetr/predict.py +21 -21
- ultralytics/models/rtdetr/train.py +25 -24
- ultralytics/models/rtdetr/val.py +47 -14
- ultralytics/models/sam/__init__.py +1 -1
- ultralytics/models/sam/amg.py +50 -4
- ultralytics/models/sam/model.py +8 -14
- ultralytics/models/sam/modules/decoders.py +18 -21
- ultralytics/models/sam/modules/encoders.py +25 -46
- ultralytics/models/sam/modules/memory_attention.py +19 -15
- ultralytics/models/sam/modules/sam.py +18 -25
- ultralytics/models/sam/modules/tiny_encoder.py +19 -29
- ultralytics/models/sam/modules/transformer.py +35 -57
- ultralytics/models/sam/modules/utils.py +15 -15
- ultralytics/models/sam/predict.py +0 -3
- ultralytics/models/utils/loss.py +87 -36
- ultralytics/models/utils/ops.py +26 -31
- ultralytics/models/yolo/classify/predict.py +30 -12
- ultralytics/models/yolo/classify/train.py +83 -19
- ultralytics/models/yolo/classify/val.py +45 -23
- ultralytics/models/yolo/detect/predict.py +29 -19
- ultralytics/models/yolo/detect/train.py +90 -23
- ultralytics/models/yolo/detect/val.py +150 -29
- ultralytics/models/yolo/model.py +1 -2
- ultralytics/models/yolo/obb/predict.py +18 -13
- ultralytics/models/yolo/obb/train.py +12 -8
- ultralytics/models/yolo/obb/val.py +35 -22
- ultralytics/models/yolo/pose/predict.py +28 -15
- ultralytics/models/yolo/pose/train.py +21 -8
- ultralytics/models/yolo/pose/val.py +51 -31
- ultralytics/models/yolo/segment/predict.py +27 -16
- ultralytics/models/yolo/segment/train.py +11 -8
- ultralytics/models/yolo/segment/val.py +110 -29
- ultralytics/models/yolo/world/train.py +43 -16
- ultralytics/models/yolo/world/train_world.py +61 -36
- ultralytics/nn/autobackend.py +28 -14
- ultralytics/nn/modules/__init__.py +12 -12
- ultralytics/nn/modules/activation.py +12 -3
- ultralytics/nn/modules/block.py +587 -84
- ultralytics/nn/modules/conv.py +418 -54
- ultralytics/nn/modules/head.py +3 -4
- ultralytics/nn/modules/transformer.py +320 -34
- ultralytics/nn/modules/utils.py +17 -3
- ultralytics/nn/tasks.py +226 -79
- ultralytics/solutions/ai_gym.py +2 -2
- ultralytics/solutions/analytics.py +4 -4
- ultralytics/solutions/heatmap.py +4 -4
- ultralytics/solutions/instance_segmentation.py +10 -4
- ultralytics/solutions/object_blurrer.py +2 -2
- ultralytics/solutions/object_counter.py +2 -2
- ultralytics/solutions/object_cropper.py +2 -2
- ultralytics/solutions/parking_management.py +9 -9
- ultralytics/solutions/queue_management.py +1 -1
- ultralytics/solutions/region_counter.py +2 -2
- ultralytics/solutions/security_alarm.py +7 -7
- ultralytics/solutions/solutions.py +7 -4
- ultralytics/solutions/speed_estimation.py +2 -2
- ultralytics/solutions/streamlit_inference.py +6 -6
- ultralytics/solutions/trackzone.py +9 -2
- ultralytics/solutions/vision_eye.py +4 -4
- ultralytics/trackers/basetrack.py +1 -1
- ultralytics/trackers/bot_sort.py +23 -22
- ultralytics/trackers/byte_tracker.py +4 -4
- ultralytics/trackers/track.py +2 -1
- ultralytics/trackers/utils/gmc.py +26 -27
- ultralytics/trackers/utils/kalman_filter.py +31 -29
- ultralytics/trackers/utils/matching.py +7 -7
- ultralytics/utils/__init__.py +37 -35
- ultralytics/utils/autobatch.py +5 -5
- ultralytics/utils/benchmarks.py +111 -18
- ultralytics/utils/callbacks/base.py +3 -3
- ultralytics/utils/callbacks/clearml.py +11 -11
- ultralytics/utils/callbacks/comet.py +35 -22
- ultralytics/utils/callbacks/dvc.py +11 -10
- ultralytics/utils/callbacks/hub.py +8 -8
- ultralytics/utils/callbacks/mlflow.py +1 -1
- ultralytics/utils/callbacks/neptune.py +12 -10
- ultralytics/utils/callbacks/raytune.py +1 -1
- ultralytics/utils/callbacks/tensorboard.py +6 -6
- ultralytics/utils/callbacks/wb.py +16 -16
- ultralytics/utils/checks.py +139 -68
- ultralytics/utils/dist.py +15 -2
- ultralytics/utils/downloads.py +37 -56
- ultralytics/utils/files.py +12 -13
- ultralytics/utils/instance.py +117 -52
- ultralytics/utils/loss.py +28 -33
- ultralytics/utils/metrics.py +246 -181
- ultralytics/utils/ops.py +65 -61
- ultralytics/utils/patches.py +8 -6
- ultralytics/utils/plotting.py +72 -59
- ultralytics/utils/tal.py +88 -57
- ultralytics/utils/torch_utils.py +202 -64
- ultralytics/utils/triton.py +13 -3
- ultralytics/utils/tuner.py +13 -25
- {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/METADATA +2 -2
- ultralytics-8.3.90.dist-info/RECORD +250 -0
- ultralytics-8.3.88.dist-info/RECORD +0 -250
- {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/LICENSE +0 -0
- {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/WHEEL +0 -0
- {ultralytics-8.3.88.dist-info → ultralytics-8.3.90.dist-info}/entry_points.txt +0 -0
- {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
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
20
|
-
|
21
|
-
|
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
|
-
|
24
|
-
|
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
|
-
"""
|
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
|
-
"""
|
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
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
|
13
|
-
|
14
|
-
|
15
|
-
|
16
|
-
|
17
|
-
|
18
|
-
|
19
|
-
|
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
|
-
|
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):
|
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
|
-
(
|
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
|
-
|
71
|
+
Construct a single Results object from one image prediction.
|
62
72
|
|
63
73
|
Args:
|
64
|
-
pred (torch.Tensor):
|
65
|
-
img (torch.Tensor):
|
66
|
-
orig_img (np.ndarray):
|
67
|
-
img_path (str):
|
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):
|
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
|
-
|
24
|
-
|
25
|
-
|
26
|
-
|
27
|
-
|
28
|
-
|
29
|
-
|
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`.
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
|
154
|
+
Return a loss dict with labeled training loss items tensor.
|
103
155
|
|
104
|
-
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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
|
-
"""
|
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)
|