Reference for ultralytics/nn/tasks.py
Note
Full source code for this file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/nn/tasks.py. Help us fix any issues you see by submitting a Pull Request 🛠️. Thank you 🙏!
ultralytics.nn.tasks.BaseModel
Bases: Module
The BaseModel class serves as a base class for all the models in the Ultralytics YOLO family.
Source code in ultralytics/nn/tasks.py
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 |
|
forward(x, *args, **kwargs)
Forward pass of the model on a single scale.
Wrapper for _forward_once
method.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor | dict
|
The input image tensor or a dict including image tensor and gt labels. |
required |
Returns:
Type | Description |
---|---|
Tensor
|
The output of the network. |
Source code in ultralytics/nn/tasks.py
fuse(verbose=True)
Fuse the Conv2d()
and BatchNorm2d()
layers of the model into a single layer, in order to improve the
computation efficiency.
Returns:
Type | Description |
---|---|
Module
|
The fused model is returned. |
Source code in ultralytics/nn/tasks.py
info(detailed=False, verbose=True, imgsz=640)
Prints model information
Parameters:
Name | Type | Description | Default |
---|---|---|---|
detailed |
bool
|
if True, prints out detailed information about the model. Defaults to False |
False
|
verbose |
bool
|
if True, prints out the model information. Defaults to False |
True
|
imgsz |
int
|
the size of the image that the model will be trained on. Defaults to 640 |
640
|
Source code in ultralytics/nn/tasks.py
is_fused(thresh=10)
Check if the model has less than a certain threshold of BatchNorm layers.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
thresh |
int
|
The threshold number of BatchNorm layers. Default is 10. |
10
|
Returns:
Type | Description |
---|---|
bool
|
True if the number of BatchNorm layers in the model is less than the threshold, False otherwise. |
Source code in ultralytics/nn/tasks.py
load(weights, verbose=True)
Load the weights into the model.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weights |
dict | Module
|
The pre-trained weights to be loaded. |
required |
verbose |
bool
|
Whether to log the transfer progress. Defaults to True. |
True
|
Source code in ultralytics/nn/tasks.py
loss(batch, preds=None)
Compute loss
Parameters:
Name | Type | Description | Default |
---|---|---|---|
batch |
dict
|
Batch to compute loss on |
required |
preds |
Tensor | List[Tensor]
|
Predictions. |
None
|
Source code in ultralytics/nn/tasks.py
predict(x, profile=False, visualize=False, augment=False)
Perform a forward pass through the network.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
The input tensor to the model. |
required |
profile |
bool
|
Print the computation time of each layer if True, defaults to False. |
False
|
visualize |
bool
|
Save the feature maps of the model if True, defaults to False. |
False
|
augment |
bool
|
Augment image during prediction, defaults to False. |
False
|
Returns:
Type | Description |
---|---|
Tensor
|
The last output of the model. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.DetectionModel
Bases: BaseModel
YOLOv8 detection model.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.SegmentationModel
Bases: DetectionModel
YOLOv8 segmentation model.
Source code in ultralytics/nn/tasks.py
__init__(cfg='yolov8n-seg.yaml', ch=3, nc=None, verbose=True)
Initialize YOLOv8 segmentation model with given config and parameters.
ultralytics.nn.tasks.PoseModel
Bases: DetectionModel
YOLOv8 pose model.
Source code in ultralytics/nn/tasks.py
__init__(cfg='yolov8n-pose.yaml', ch=3, nc=None, data_kpt_shape=(None, None), verbose=True)
Initialize YOLOv8 Pose model.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.ClassificationModel
Bases: BaseModel
YOLOv8 classification model.
Source code in ultralytics/nn/tasks.py
__init__(cfg='yolov8n-cls.yaml', ch=3, nc=None, verbose=True)
Init ClassificationModel with YAML, channels, number of classes, verbose flag.
init_criterion()
reshape_outputs(model, nc)
staticmethod
Update a TorchVision classification model to class count 'n' if required.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.RTDETRDetectionModel
Bases: DetectionModel
Source code in ultralytics/nn/tasks.py
init_criterion()
Compute the classification loss between predictions and true labels.
predict(x, profile=False, visualize=False, batch=None, augment=False)
Perform a forward pass through the network.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
x |
Tensor
|
The input tensor to the model |
required |
profile |
bool
|
Print the computation time of each layer if True, defaults to False. |
False
|
visualize |
bool
|
Save the feature maps of the model if True, defaults to False |
False
|
batch |
dict
|
A dict including gt boxes and labels from dataloader. |
None
|
Returns:
Type | Description |
---|---|
Tensor
|
The last output of the model. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.Ensemble
Bases: ModuleList
Ensemble of models.
Source code in ultralytics/nn/tasks.py
__init__()
forward(x, augment=False, profile=False, visualize=False)
Function generates the YOLOv5 network's final layer.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.temporary_modules(modules=None)
Context manager for temporarily adding or modifying modules in Python's module cache (sys.modules
).
This function can be used to change the module paths during runtime. It's useful when refactoring code, where you've moved a module from one location to another, but you still want to support the old import paths for backwards compatibility.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
modules |
dict
|
A dictionary mapping old module paths to new module paths. |
None
|
Example
Note
The changes are only in effect inside the context manager and are undone once the context manager exits.
Be aware that directly manipulating sys.modules
can lead to unpredictable results, especially in larger
applications or libraries. Use this function with caution.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.torch_safe_load(weight)
This function attempts to load a PyTorch model with the torch.load() function. If a ModuleNotFoundError is raised, it catches the error, logs a warning message, and attempts to install the missing module via the check_requirements() function. After installation, the function again attempts to load the model using torch.load().
Parameters:
Name | Type | Description | Default |
---|---|---|---|
weight |
str
|
The file path of the PyTorch model. |
required |
Returns:
Type | Description |
---|---|
dict
|
The loaded PyTorch model. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.attempt_load_weights(weights, device=None, inplace=True, fuse=False)
Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.attempt_load_one_weight(weight, device=None, inplace=True, fuse=False)
Loads a single model weights.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.parse_model(d, ch, verbose=True)
Parse a YOLO model.yaml dictionary into a PyTorch model.
Source code in ultralytics/nn/tasks.py
613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 |
|
ultralytics.nn.tasks.yaml_model_load(path)
Load a YOLOv8 model from a YAML file.
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.guess_model_scale(model_path)
Takes a path to a YOLO model's YAML file as input and extracts the size character of the model's scale. The function uses regular expression matching to find the pattern of the model scale in the YAML file name, which is denoted by n, s, m, l, or x. The function returns the size character of the model scale as a string.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model_path |
str | Path
|
The path to the YOLO model's YAML file. |
required |
Returns:
Type | Description |
---|---|
str
|
The size character of the model's scale, which can be n, s, m, l, or x. |
Source code in ultralytics/nn/tasks.py
ultralytics.nn.tasks.guess_model_task(model)
Guess the task of a PyTorch model from its architecture or configuration.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
model |
Module | dict
|
PyTorch model or model configuration in YAML format. |
required |
Returns:
Type | Description |
---|---|
str
|
Task of the model ('detect', 'segment', 'classify', 'pose'). |
Raises:
Type | Description |
---|---|
SyntaxError
|
If the task of the model could not be determined. |