Skip to content

Register now for

# Reference for `ultralytics/engine/model.py`

Note

This file is available at https://github.com/ultralytics/ultralytics/blob/main/ultralytics/engine/model.py. If you spot a problem please help fix it by contributing a Pull Request 🛠️. Thank you 🙏!

## `` ultralytics.engine.model.Model

    Model(
        model: str | Path | Model = "yolo11n.pt",
        task: str = None,
        verbose: bool = False,
    )

Bases: `Module`

A base class for implementing YOLO models, unifying APIs across different model types.

This class provides a common interface for various operations related to YOLO models, such as training, validation, prediction, exporting, and benchmarking. It handles different types of models, including those loaded from local files, Ultralytics HUB, or Triton Server.

Attributes:

Name | Type | Description
--- | --- | ---
`callbacks` | `dict` | A dictionary of callback functions for various events during model operations.
`predictor` | `BasePredictor` | The predictor object used for making predictions.
`model` | `Module` | The underlying PyTorch model.
`trainer` | `BaseTrainer` | The trainer object used for training the model.
`ckpt` | `dict` | The checkpoint data if the model is loaded from a *.pt file.
`cfg` | `str` | The configuration of the model if loaded from a *.yaml file.
`ckpt_path` | `str` | The path to the checkpoint file.
`overrides` | `dict` | A dictionary of overrides for model configuration.
`metrics` | `dict` | The latest training/validation metrics.
`session` | `HUBTrainingSession` | The Ultralytics HUB session, if applicable.
`task` | `str` | The type of task the model is intended for.
`model_name` | `str` | The name of the model.

Methods:

Name | Description
--- | ---
`__call__` | Alias for the predict method, enabling the model instance to be callable.
`_new` | Initialize a new model based on a configuration file.
`_load` | Load a model from a checkpoint file.
`_check_is_pytorch_model` | Ensure that the model is a PyTorch model.
`reset_weights` | Reset the model's weights to their initial state.
`load` | Load model weights from a specified file.
`save` | Save the current state of the model to a file.
`info` | Log or return information about the model.
`fuse` | Fuse Conv2d and BatchNorm2d layers for optimized inference.
`predict` | Perform object detection predictions.
`track` | Perform object tracking.
`val` | Validate the model on a dataset.
`benchmark` | Benchmark the model on various export formats.
`export` | Export the model to different formats.
`train` | Train the model on a dataset.
`tune` | Perform hyperparameter tuning.
`_apply` | Apply a function to the model's tensors.
`add_callback` | Add a callback function for an event.
`clear_callback` | Clear all callbacks for an event.
`reset_callbacks` | Reset all callbacks to their default functions.

Examples:

    >>> from ultralytics import YOLO
    >>> model = YOLO("yolo11n.pt")
    >>> results = model.predict("image.jpg")
    >>> model.train(data="coco8.yaml", epochs=3)
    >>> metrics = model.val()
    >>> model.export(format="onnx")

This constructor sets up the model based on the provided model path or name. It handles various types of model sources, including local files, Ultralytics HUB models, and Triton Server models. The method initializes several important attributes of the model and prepares it for operations like training, prediction, or export.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `str | Path | Model` | Path or name of the model to load or create. Can be a local file path, a model name from Ultralytics HUB, a Triton Server model, or an already initialized Model instance. | `'yolo11n.pt'`
`task` | `str` | The specific task for the model. If None, it will be inferred from the config. | `None`
`verbose` | `bool` | If True, enables verbose output during the model's initialization and subsequent operations. | `False`

Raises:

Type | Description
--- | ---
`FileNotFoundError` | If the specified model file does not exist or is inaccessible.
`ValueError` | If the model file or configuration is invalid or unsupported.
`ImportError` | If required dependencies for specific model types (like HUB SDK) are not installed.

Examples:

    >>> model = Model("yolo11n.pt")
    >>> model = Model("path/to/model.yaml", task="detect")
    >>> model = Model("hub_model", verbose=True)

Source code in `ultralytics/engine/model.py`

     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
    def __init__(
        self,
        model: str | Path | Model = "yolo11n.pt",
        task: str = None,
        verbose: bool = False,
    ) -> None:
        """
        Initialize a new instance of the YOLO model class.

        This constructor sets up the model based on the provided model path or name. It handles various types of
        model sources, including local files, Ultralytics HUB models, and Triton Server models. The method
        initializes several important attributes of the model and prepares it for operations like training,
        prediction, or export.

        Args:
            model (str | Path | Model): Path or name of the model to load or create. Can be a local file path, a
                model name from Ultralytics HUB, a Triton Server model, or an already initialized Model instance.
            task (str, optional): The specific task for the model. If None, it will be inferred from the config.
            verbose (bool): If True, enables verbose output during the model's initialization and subsequent
                operations.

        Raises:
            FileNotFoundError: If the specified model file does not exist or is inaccessible.
            ValueError: If the model file or configuration is invalid or unsupported.
            ImportError: If required dependencies for specific model types (like HUB SDK) are not installed.

        Examples:
            >>> model = Model("yolo11n.pt")
            >>> model = Model("path/to/model.yaml", task="detect")
            >>> model = Model("hub_model", verbose=True)
        """
        if isinstance(model, Model):
            self.__dict__ = model.__dict__  # accepts an already initialized Model
            return
        super().__init__()
        self.callbacks = callbacks.get_default_callbacks()
        self.predictor = None  # reuse predictor
        self.model = None  # model object
        self.trainer = None  # trainer object
        self.ckpt = {}  # if loaded from *.pt
        self.cfg = None  # if loaded from *.yaml
        self.ckpt_path = None
        self.overrides = {}  # overrides for trainer object
        self.metrics = None  # validation/training metrics
        self.session = None  # HUB session
        self.task = task  # task type
        self.model_name = None  # model name
        model = str(model).strip()

        # Check if Ultralytics HUB model from https://hub.ultralytics.com
        if self.is_hub_model(model):
            from ultralytics.hub import HUBTrainingSession

            # Fetch model from HUB
            checks.check_requirements("hub-sdk>=0.0.12")
            session = HUBTrainingSession.create_session(model)
            model = session.model_file
            if session.train_args:  # training sent from HUB
                self.session = session

        # Check if Triton Server model
        elif self.is_triton_model(model):
            self.model_name = self.model = model
            self.overrides["task"] = task or "detect"  # set `task=detect` if not explicitly set
            return

        # Load or create new YOLO model
        __import__("os").environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"  # to avoid deterministic warnings
        if str(model).endswith((".yaml", ".yml")):
            self._new(model, task=task, verbose=verbose)
        else:
            self._load(model, task=task)

        # Delete super().training for accessing self.model.training
        del self.training

### `` device `property`

    device: device

Get the device on which the model's parameters are allocated.

This property determines the device (CPU or GPU) where the model's parameters are currently stored. It is applicable only to models that are instances of torch.nn.Module.

Returns:

Type | Description
--- | ---
`device` | The device (CPU/GPU) of the model.

Raises:

Type | Description
--- | ---
`AttributeError` | If the model is not a torch.nn.Module instance.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> print(model.device)
    device(type='cuda', index=0)  # if CUDA is available
    >>> model = model.to("cpu")
    >>> print(model.device)
    device(type='cpu')

### `` names `property`

    names: dict[int, str]

Retrieve the class names associated with the loaded model.

This property returns the class names if they are defined in the model. It checks the class names for validity using the 'check_class_names' function from the ultralytics.nn.autobackend module. If the predictor is not initialized, it sets it up before retrieving the names.

Returns:

Type | Description
--- | ---
`dict[int, str]` | A dictionary of class names associated with the model, where keys are class indices and values are the corresponding class names.

Raises:

Type | Description
--- | ---
`AttributeError` | If the model or predictor does not have a 'names' attribute.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> print(model.names)
    {0: 'person', 1: 'bicycle', 2: 'car', ...}

### `` task_map `property`

    task_map: dict

Provide a mapping from model tasks to corresponding classes for different modes.

This property method returns a dictionary that maps each supported task (e.g., detect, segment, classify) to a nested dictionary. The nested dictionary contains mappings for different operational modes (model, trainer, validator, predictor) to their respective class implementations.

The mapping allows for dynamic loading of appropriate classes based on the model's task and the desired operational mode. This facilitates a flexible and extensible architecture for handling various tasks and modes within the Ultralytics framework.

Returns:

Type | Description
--- | ---
`dict[str, dict[str, Any]]` | A dictionary mapping task names to nested dictionaries. Each nested dictionary
`dict` | contains mappings for 'model', 'trainer', 'validator', and 'predictor' keys to their respective class
`dict` | implementations for that task.

Examples:

    >>> model = Model("yolo11n.pt")
    >>> task_map = model.task_map
    >>> detect_predictor = task_map["detect"]["predictor"]
    >>> segment_trainer = task_map["segment"]["trainer"]

### `` transforms `property`

    transforms

Retrieve the transformations applied to the input data of the loaded model.

This property returns the transformations if they are defined in the model. The transforms typically include preprocessing steps like resizing, normalization, and data augmentation that are applied to input data before it is fed into the model.

Returns:

Type | Description
--- | ---
`object | None` | The transform object of the model if available, otherwise None.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> transforms = model.transforms
    >>> if transforms:
    ...     print(f"Model transforms: {transforms}")
    ... else:
    ...     print("No transforms defined for this model.")

### `` __call__

    __call__(
        source: str | Path | int | Image | list | tuple | ndarray | Tensor = None,
        stream: bool = False,
        **kwargs: Any
    ) -> list

Alias for the predict method, enabling the model instance to be callable for predictions.

This method simplifies the process of making predictions by allowing the model instance to be called directly with the required arguments.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`source` | `str | Path | int | Image | ndarray | Tensor | list | tuple` | The source of the image(s) to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch tensor, or a list/tuple of these. | `None`
`stream` | `bool` | If True, treat the input source as a continuous stream for predictions. | `False`
`**kwargs` | `Any` | Additional keyword arguments to configure the prediction process. | `{}`

Returns:

Type | Description
--- | ---
`list[Results]` | A list of prediction results, each encapsulated in a Results object.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> results = model("https://ultralytics.com/images/bus.jpg")
    >>> for r in results:
    ...     print(f"Detected {len(r)} objects in image")

Source code in `ultralytics/engine/model.py`

    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
    def __call__(
        self,
        source: str | Path | int | Image.Image | list | tuple | np.ndarray | torch.Tensor = None,
        stream: bool = False,
        **kwargs: Any,
    ) -> list:
        """
        Alias for the predict method, enabling the model instance to be callable for predictions.

        This method simplifies the process of making predictions by allowing the model instance to be called
        directly with the required arguments.

        Args:
            source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source of
                the image(s) to make predictions on. Can be a file path, URL, PIL image, numpy array, PyTorch
                tensor, or a list/tuple of these.
            stream (bool): If True, treat the input source as a continuous stream for predictions.
            **kwargs (Any): Additional keyword arguments to configure the prediction process.

        Returns:
            (list[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a
                Results object.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> results = model("https://ultralytics.com/images/bus.jpg")
            >>> for r in results:
            ...     print(f"Detected {len(r)} objects in image")
        """
        return self.predict(source, stream, **kwargs)

### `` __getattr__

    __getattr__(name)

Enable accessing model attributes directly through the Model class.

This method provides a way to access attributes of the underlying model directly through the Model class instance. It first checks if the requested attribute is 'model', in which case it returns the model from the module dictionary. Otherwise, it delegates the attribute lookup to the underlying model.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`name` | `str` | The name of the attribute to retrieve. | required

Returns:

Type | Description
--- | ---
`Any` | The requested attribute value.

Raises:

Type | Description
--- | ---
`AttributeError` | If the requested attribute does not exist in the model.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> print(model.stride)  # Access model.stride attribute
    >>> print(model.names)  # Access model.names attribute

Source code in `ultralytics/engine/model.py`

    1142
    1143
    1144
    1145
    1146
    1147
    1148
    1149
    1150
    1151
    1152
    1153
    1154
    1155
    1156
    1157
    1158
    1159
    1160
    1161
    1162
    1163
    1164
    def __getattr__(self, name):
        """
        Enable accessing model attributes directly through the Model class.

        This method provides a way to access attributes of the underlying model directly through the Model class
        instance. It first checks if the requested attribute is 'model', in which case it returns the model from
        the module dictionary. Otherwise, it delegates the attribute lookup to the underlying model.

        Args:
            name (str): The name of the attribute to retrieve.

        Returns:
            (Any): The requested attribute value.

        Raises:
            AttributeError: If the requested attribute does not exist in the model.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> print(model.stride)  # Access model.stride attribute
            >>> print(model.names)  # Access model.names attribute
        """
        return self._modules["model"] if name == "model" else getattr(self.model, name)

### `` add_callback

    add_callback(event: str, func) -> None

Add a callback function for a specified event.

This method allows registering custom callback functions that are triggered on specific events during model operations such as training or inference. Callbacks provide a way to extend and customize the behavior of the model at various stages of its lifecycle.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`event` | `str` | The name of the event to attach the callback to. Must be a valid event name recognized by the Ultralytics framework. | required
`func` | `Callable` | The callback function to be registered. This function will be called when the specified event occurs. | required

Raises:

Type | Description
--- | ---
`ValueError` | If the event name is not recognized or is invalid.

Examples:

    >>> def on_train_start(trainer):
    ...     print("Training is starting!")
    >>> model = YOLO("yolo11n.pt")
    >>> model.add_callback("on_train_start", on_train_start)
    >>> model.train(data="coco8.yaml", epochs=1)

Source code in `ultralytics/engine/model.py`

    962
    963
    964
    965
    966
    967
    968
    969
    970
    971
    972
    973
    974
    975
    976
    977
    978
    979
    980
    981
    982
    983
    984
    985
    986
    def add_callback(self, event: str, func) -> None:
        """
        Add a callback function for a specified event.

        This method allows registering custom callback functions that are triggered on specific events during
        model operations such as training or inference. Callbacks provide a way to extend and customize the
        behavior of the model at various stages of its lifecycle.

        Args:
            event (str): The name of the event to attach the callback to. Must be a valid event name recognized
                by the Ultralytics framework.
            func (Callable): The callback function to be registered. This function will be called when the
                specified event occurs.

        Raises:
            ValueError: If the event name is not recognized or is invalid.

        Examples:
            >>> def on_train_start(trainer):
            ...     print("Training is starting!")
            >>> model = YOLO("yolo11n.pt")
            >>> model.add_callback("on_train_start", on_train_start)
            >>> model.train(data="coco8.yaml", epochs=1)
        """
        self.callbacks[event].append(func)

### `` benchmark

    benchmark(data=None, format='', verbose=False, **kwargs: Any)

Benchmark the model across various export formats to evaluate performance.

This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc. It uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is configured using a combination of default configuration values, model-specific arguments, method-specific defaults, and any additional user-provided keyword arguments.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`data` | `str` | Path to the dataset for benchmarking. | `None`
`verbose` | `bool` | Whether to print detailed benchmark information. | `False`
`format` | `str` | Export format name for specific benchmarking. | `''`
`**kwargs` | `Any` | Arbitrary keyword arguments to customize the benchmarking process. Common options include: - imgsz (int | list[int]): Image size for benchmarking. - half (bool): Whether to use half-precision (FP16) mode. - int8 (bool): Whether to use int8 precision mode. - device (str): Device to run the benchmark on (e.g., 'cpu', 'cuda'). | `{}`

Returns:

Type | Description
--- | ---
`dict` | A dictionary containing the results of the benchmarking process, including metrics for different export formats.

Raises:

Type | Description
--- | ---
`AssertionError` | If the model is not a PyTorch model.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> results = model.benchmark(data="coco8.yaml", imgsz=640, half=True)
    >>> print(results)

Source code in `ultralytics/engine/model.py`

    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
    def benchmark(self, data=None, format="", verbose=False, **kwargs: Any):
        """
        Benchmark the model across various export formats to evaluate performance.

        This method assesses the model's performance in different export formats, such as ONNX, TorchScript, etc.
        It uses the 'benchmark' function from the ultralytics.utils.benchmarks module. The benchmarking is
        configured using a combination of default configuration values, model-specific arguments, method-specific
        defaults, and any additional user-provided keyword arguments.

        Args:
            data (str): Path to the dataset for benchmarking.
            verbose (bool): Whether to print detailed benchmark information.
            format (str): Export format name for specific benchmarking.
            **kwargs (Any): Arbitrary keyword arguments to customize the benchmarking process. Common options include:
                - imgsz (int | list[int]): Image size for benchmarking.
                - half (bool): Whether to use half-precision (FP16) mode.
                - int8 (bool): Whether to use int8 precision mode.
                - device (str): Device to run the benchmark on (e.g., 'cpu', 'cuda').

        Returns:
            (dict): A dictionary containing the results of the benchmarking process, including metrics for
                different export formats.

        Raises:
            AssertionError: If the model is not a PyTorch model.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> results = model.benchmark(data="coco8.yaml", imgsz=640, half=True)
            >>> print(results)
        """
        self._check_is_pytorch_model()
        from ultralytics.utils.benchmarks import benchmark

        from .exporter import export_formats

        custom = {"verbose": False}  # method defaults
        args = {**DEFAULT_CFG_DICT, **self.model.args, **custom, **kwargs, "mode": "benchmark"}
        fmts = export_formats()
        export_args = set(dict(zip(fmts["Argument"], fmts["Arguments"])).get(format, [])) - {"batch"}
        export_kwargs = {k: v for k, v in args.items() if k in export_args}
        return benchmark(
            model=self,
            data=data,  # if no 'data' argument passed set data=None for default datasets
            imgsz=args["imgsz"],
            device=args["device"],
            verbose=verbose,
            format=format,
            **export_kwargs,
        )

### `` clear_callback

    clear_callback(event: str) -> None

Clear all callback functions registered for a specified event.

This method removes all custom and default callback functions associated with the given event. It resets the callback list for the specified event to an empty list, effectively removing all registered callbacks for that event.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`event` | `str` | The name of the event for which to clear the callbacks. This should be a valid event name recognized by the Ultralytics callback system. | required

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> model.add_callback("on_train_start", lambda: print("Training started"))
    >>> model.clear_callback("on_train_start")
    >>> # All callbacks for 'on_train_start' are now removed

Notes

- This method affects both custom callbacks added by the user and default callbacks provided by the Ultralytics framework.
- After calling this method, no callbacks will be executed for the specified event until new ones are added.
- Use with caution as it removes all callbacks, including essential ones that might be required for proper functioning of certain operations.

Source code in `ultralytics/engine/model.py`

     988
     989
     990
     991
     992
     993
     994
     995
     996
     997
     998
     999
    1000
    1001
    1002
    1003
    1004
    1005
    1006
    1007
    1008
    1009
    1010
    1011
    1012
    1013
    1014
    def clear_callback(self, event: str) -> None:
        """
        Clear all callback functions registered for a specified event.

        This method removes all custom and default callback functions associated with the given event.
        It resets the callback list for the specified event to an empty list, effectively removing all
        registered callbacks for that event.

        Args:
            event (str): The name of the event for which to clear the callbacks. This should be a valid event name
                recognized by the Ultralytics callback system.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> model.add_callback("on_train_start", lambda: print("Training started"))
            >>> model.clear_callback("on_train_start")
            >>> # All callbacks for 'on_train_start' are now removed

        Notes:
            - This method affects both custom callbacks added by the user and default callbacks
              provided by the Ultralytics framework.
            - After calling this method, no callbacks will be executed for the specified event
              until new ones are added.
            - Use with caution as it removes all callbacks, including essential ones that might
              be required for proper functioning of certain operations.
        """
        self.callbacks[event] = []

### `` embed

    embed(
        source: str | Path | int | list | tuple | ndarray | Tensor = None,
        stream: bool = False,
        **kwargs: Any
    ) -> list

Generate image embeddings based on the provided source.

This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image source. It allows customization of the embedding process through various keyword arguments.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`source` | `str | Path | int | list | tuple | ndarray | Tensor` | The source of the image for generating embeddings. Can be a file path, URL, PIL image, numpy array, etc. | `None`
`stream` | `bool` | If True, predictions are streamed. | `False`
`**kwargs` | `Any` | Additional keyword arguments for configuring the embedding process. | `{}`

Returns:

Type | Description
--- | ---
`list[Tensor]` | A list containing the image embeddings.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> image = "https://ultralytics.com/images/bus.jpg"
    >>> embeddings = model.embed(image)
    >>> print(embeddings[0].shape)

Source code in `ultralytics/engine/model.py`

    467
    468
    469
    470
    471
    472
    473
    474
    475
    476
    477
    478
    479
    480
    481
    482
    483
    484
    485
    486
    487
    488
    489
    490
    491
    492
    493
    494
    495
    496
    def embed(
        self,
        source: str | Path | int | list | tuple | np.ndarray | torch.Tensor = None,
        stream: bool = False,
        **kwargs: Any,
    ) -> list:
        """
        Generate image embeddings based on the provided source.

        This method is a wrapper around the 'predict()' method, focusing on generating embeddings from an image
        source. It allows customization of the embedding process through various keyword arguments.

        Args:
            source (str | Path | int | list | tuple | np.ndarray | torch.Tensor): The source of the image for
                generating embeddings. Can be a file path, URL, PIL image, numpy array, etc.
            stream (bool): If True, predictions are streamed.
            **kwargs (Any): Additional keyword arguments for configuring the embedding process.

        Returns:
            (list[torch.Tensor]): A list containing the image embeddings.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> image = "https://ultralytics.com/images/bus.jpg"
            >>> embeddings = model.embed(image)
            >>> print(embeddings[0].shape)
        """
        if not kwargs.get("embed"):
            kwargs["embed"] = [len(self.model.model) - 2]  # embed second-to-last layer if no indices passed
        return self.predict(source, stream, **kwargs)

### `` eval

    eval()

Sets the model to evaluation mode.

This method changes the model's mode to evaluation, which affects layers like dropout and batch normalization that behave differently during training and evaluation. In evaluation mode, these layers use running statistics rather than computing batch statistics, and dropout layers are disabled.

Returns:

Type | Description
--- | ---
`Model` | The model instance with evaluation mode set.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> model.eval()
    >>> # Model is now in evaluation mode for inference

Source code in `ultralytics/engine/model.py`

    1123
    1124
    1125
    1126
    1127
    1128
    1129
    1130
    1131
    1132
    1133
    1134
    1135
    1136
    1137
    1138
    1139
    1140
    def eval(self):
        """
        Sets the model to evaluation mode.

        This method changes the model's mode to evaluation, which affects layers like dropout and batch normalization
        that behave differently during training and evaluation. In evaluation mode, these layers use running statistics
        rather than computing batch statistics, and dropout layers are disabled.

        Returns:
            (Model): The model instance with evaluation mode set.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> model.eval()
            >>> # Model is now in evaluation mode for inference
        """
        self.model.eval()
        return self

### `` export

    export(**kwargs: Any) -> str

Export the model to a different format suitable for deployment.

This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method defaults, and any additional arguments provided.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`**kwargs` | `Any` | Arbitrary keyword arguments to customize the export process. These are combined with the model's overrides and method defaults. Common arguments include: format (str): Export format (e.g., 'onnx', 'engine', 'coreml'). half (bool): Export model in half-precision. int8 (bool): Export model in int8 precision. device (str): Device to run the export on. workspace (int): Maximum memory workspace size for TensorRT engines. nms (bool): Add Non-Maximum Suppression (NMS) module to model. simplify (bool): Simplify ONNX model. | `{}`

Returns:

Type | Description
--- | ---
`str` | The path to the exported model file.

Raises:

Type | Description
--- | ---
`AssertionError` | If the model is not a PyTorch model.
`ValueError` | If an unsupported export format is specified.
`RuntimeError` | If the export process fails due to errors.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> model.export(format="onnx", dynamic=True, simplify=True)
    'path/to/exported/model.onnx'

Source code in `ultralytics/engine/model.py`

    690
    691
    692
    693
    694
    695
    696
    697
    698
    699
    700
    701
    702
    703
    704
    705
    706
    707
    708
    709
    710
    711
    712
    713
    714
    715
    716
    717
    718
    719
    720
    721
    722
    723
    724
    725
    726
    727
    728
    729
    730
    731
    732
    733
    734
    735
    736
    def export(
        self,
        **kwargs: Any,
    ) -> str:
        """
        Export the model to a different format suitable for deployment.

        This method facilitates the export of the model to various formats (e.g., ONNX, TorchScript) for deployment
        purposes. It uses the 'Exporter' class for the export process, combining model-specific overrides, method
        defaults, and any additional arguments provided.

        Args:
            **kwargs (Any): Arbitrary keyword arguments to customize the export process. These are combined with
                the model's overrides and method defaults. Common arguments include:
                format (str): Export format (e.g., 'onnx', 'engine', 'coreml').
                half (bool): Export model in half-precision.
                int8 (bool): Export model in int8 precision.
                device (str): Device to run the export on.
                workspace (int): Maximum memory workspace size for TensorRT engines.
                nms (bool): Add Non-Maximum Suppression (NMS) module to model.
                simplify (bool): Simplify ONNX model.

        Returns:
            (str): The path to the exported model file.

        Raises:
            AssertionError: If the model is not a PyTorch model.
            ValueError: If an unsupported export format is specified.
            RuntimeError: If the export process fails due to errors.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> model.export(format="onnx", dynamic=True, simplify=True)
            'path/to/exported/model.onnx'
        """
        self._check_is_pytorch_model()
        from .exporter import Exporter

        custom = {
            "imgsz": self.model.args["imgsz"],
            "batch": 1,
            "data": None,
            "device": None,  # reset to avoid multi-GPU errors
            "verbose": False,
        }  # method defaults
        args = {**self.overrides, **custom, **kwargs, "mode": "export"}  # highest priority args on the right
        return Exporter(overrides=args, _callbacks=self.callbacks)(model=self.model)

### `` fuse

    fuse() -> None

Fuse Conv2d and BatchNorm2d layers in the model for optimized inference.

This method iterates through the model's modules and fuses consecutive Conv2d and BatchNorm2d layers into a single layer. This fusion can significantly improve inference speed by reducing the number of operations and memory accesses required during forward passes.

The fusion process typically involves folding the BatchNorm2d parameters (mean, variance, weight, and bias) into the preceding Conv2d layer's weights and biases. This results in a single Conv2d layer that performs both convolution and normalization in one step.

Examples:

    >>> model = Model("yolo11n.pt")
    >>> model.fuse()
    >>> # Model is now fused and ready for optimized inference

Source code in `ultralytics/engine/model.py`

    447
    448
    449
    450
    451
    452
    453
    454
    455
    456
    457
    458
    459
    460
    461
    462
    463
    464
    465
    def fuse(self) -> None:
        """
        Fuse Conv2d and BatchNorm2d layers in the model for optimized inference.

        This method iterates through the model's modules and fuses consecutive Conv2d and BatchNorm2d layers
        into a single layer. This fusion can significantly improve inference speed by reducing the number of
        operations and memory accesses required during forward passes.

        The fusion process typically involves folding the BatchNorm2d parameters (mean, variance, weight, and
        bias) into the preceding Conv2d layer's weights and biases. This results in a single Conv2d layer that
        performs both convolution and normalization in one step.

        Examples:
            >>> model = Model("yolo11n.pt")
            >>> model.fuse()
            >>> # Model is now fused and ready for optimized inference
        """
        self._check_is_pytorch_model()
        self.model.fuse()

### `` info

    info(detailed: bool = False, verbose: bool = True)

Display model information.

This method provides an overview or detailed information about the model, depending on the arguments passed. It can control the verbosity of the output and return the information as a list.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`detailed` | `bool` | If True, shows detailed information about the model layers and parameters. | `False`
`verbose` | `bool` | If True, prints the information. If False, returns the information as a list. | `True`

Returns:

Type | Description
--- | ---
`list[str]` | A list of strings containing various types of information about the model, including model summary, layer details, and parameter counts. Empty if verbose is True.

Examples:

    >>> model = Model("yolo11n.pt")
    >>> model.info()  # Prints model summary
    >>> info_list = model.info(detailed=True, verbose=False)  # Returns detailed info as a list

Source code in `ultralytics/engine/model.py`

    424
    425
    426
    427
    428
    429
    430
    431
    432
    433
    434
    435
    436
    437
    438
    439
    440
    441
    442
    443
    444
    445
    def info(self, detailed: bool = False, verbose: bool = True):
        """
        Display model information.

        This method provides an overview or detailed information about the model, depending on the arguments
        passed. It can control the verbosity of the output and return the information as a list.

        Args:
            detailed (bool): If True, shows detailed information about the model layers and parameters.
            verbose (bool): If True, prints the information. If False, returns the information as a list.

        Returns:
            (list[str]): A list of strings containing various types of information about the model, including
                model summary, layer details, and parameter counts. Empty if verbose is True.

        Examples:
            >>> model = Model("yolo11n.pt")
            >>> model.info()  # Prints model summary
            >>> info_list = model.info(detailed=True, verbose=False)  # Returns detailed info as a list
        """
        self._check_is_pytorch_model()
        return self.model.info(detailed=detailed, verbose=verbose)

### `` is_hub_model `staticmethod`

    is_hub_model(model: str) -> bool

Check if the provided model is an Ultralytics HUB model.

This static method determines whether the given model string represents a valid Ultralytics HUB model identifier.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `str` | The model string to check. | required

Returns:

Type | Description
--- | ---
`bool` | True if the model is a valid Ultralytics HUB model, False otherwise.

Examples:

    >>> Model.is_hub_model("https://hub.ultralytics.com/models/MODEL")
    True
    >>> Model.is_hub_model("yolo11n.pt")
    False

Source code in `ultralytics/engine/model.py`

    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    @staticmethod
    def is_hub_model(model: str) -> bool:
        """
        Check if the provided model is an Ultralytics HUB model.

        This static method determines whether the given model string represents a valid Ultralytics HUB model
        identifier.

        Args:
            model (str): The model string to check.

        Returns:
            (bool): True if the model is a valid Ultralytics HUB model, False otherwise.

        Examples:
            >>> Model.is_hub_model("https://hub.ultralytics.com/models/MODEL")
            True
            >>> Model.is_hub_model("yolo11n.pt")
            False
        """
        from ultralytics.hub import HUB_WEB_ROOT

        return model.startswith(f"{HUB_WEB_ROOT}/models/")

### `` is_triton_model `staticmethod`

    is_triton_model(model: str) -> bool

Check if the given model string is a Triton Server URL.

This static method determines whether the provided model string represents a valid Triton Server URL by parsing its components using urllib.parse.urlsplit().

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`model` | `str` | The model string to be checked. | required

Returns:

Type | Description
--- | ---
`bool` | True if the model string is a valid Triton Server URL, False otherwise.

Examples:

    >>> Model.is_triton_model("http://localhost:8000/v2/models/yolo11n")
    True
    >>> Model.is_triton_model("yolo11n.pt")
    False

Source code in `ultralytics/engine/model.py`

    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    @staticmethod
    def is_triton_model(model: str) -> bool:
        """
        Check if the given model string is a Triton Server URL.

        This static method determines whether the provided model string represents a valid Triton Server URL by
        parsing its components using urllib.parse.urlsplit().

        Args:
            model (str): The model string to be checked.

        Returns:
            (bool): True if the model string is a valid Triton Server URL, False otherwise.

        Examples:
            >>> Model.is_triton_model("http://localhost:8000/v2/models/yolo11n")
            True
            >>> Model.is_triton_model("yolo11n.pt")
            False
        """
        from urllib.parse import urlsplit

        url = urlsplit(model)
        return url.netloc and url.path and url.scheme in {"http", "grpc"}

### `` load

    load(weights: str | Path = 'yolo11n.pt') -> Model

Load parameters from the specified weights file into the model.

This method supports loading weights from a file or directly from a weights object. It matches parameters by name and shape and transfers them to the model.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`weights` | `str | Path` | Path to the weights file or a weights object. | `'yolo11n.pt'`

Returns:

Type | Description
--- | ---
`Model` | The instance of the class with loaded weights.

Raises:

Type | Description
--- | ---
`AssertionError` | If the model is not a PyTorch model.

Examples:

    >>> model = Model()
    >>> model.load("yolo11n.pt")
    >>> model.load(Path("path/to/weights.pt"))

Source code in `ultralytics/engine/model.py`

    364
    365
    366
    367
    368
    369
    370
    371
    372
    373
    374
    375
    376
    377
    378
    379
    380
    381
    382
    383
    384
    385
    386
    387
    388
    389
    390
    def load(self, weights: str | Path = "yolo11n.pt") -> Model:
        """
        Load parameters from the specified weights file into the model.

        This method supports loading weights from a file or directly from a weights object. It matches parameters by
        name and shape and transfers them to the model.

        Args:
            weights (str | Path): Path to the weights file or a weights object.

        Returns:
            (Model): The instance of the class with loaded weights.

        Raises:
            AssertionError: If the model is not a PyTorch model.

        Examples:
            >>> model = Model()
            >>> model.load("yolo11n.pt")
            >>> model.load(Path("path/to/weights.pt"))
        """
        self._check_is_pytorch_model()
        if isinstance(weights, (str, Path)):
            self.overrides["pretrained"] = weights  # remember the weights for DDP training
            weights, self.ckpt = load_checkpoint(weights)
        self.model.load(weights)
        return self

### `` predict

    predict(
        source: str | Path | int | Image | list | tuple | ndarray | Tensor = None,
        stream: bool = False,
        predictor=None,
        **kwargs: Any
    ) -> list[Results]

Perform predictions on the given image source using the YOLO model.

This method facilitates the prediction process, allowing various configurations through keyword arguments. It supports predictions with custom predictors or the default predictor method. The method handles different types of image sources and can operate in a streaming mode.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`source` | `str | Path | int | Image | ndarray | Tensor | list | tuple` | The source of the image(s) to make predictions on. Accepts various types including file paths, URLs, PIL images, numpy arrays, and torch tensors. | `None`
`stream` | `bool` | If True, treats the input source as a continuous stream for predictions. | `False`
`predictor` | `BasePredictor` | An instance of a custom predictor class for making predictions. If None, the method uses a default predictor. | `None`
`**kwargs` | `Any` | Additional keyword arguments for configuring the prediction process. | `{}`

Returns:

Type | Description
--- | ---
`list[Results]` | A list of prediction results, each encapsulated in a Results object.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> results = model.predict(source="path/to/image.jpg", conf=0.25)
    >>> for r in results:
    ...     print(r.boxes.data)  # print detection bounding boxes

Notes

- If 'source' is not provided, it defaults to the ASSETS constant with a warning.
- The method sets up a new predictor if not already present and updates its arguments with each call.
- For SAM-type models, 'prompts' can be passed as a keyword argument.

Source code in `ultralytics/engine/model.py`

    498
    499
    500
    501
    502
    503
    504
    505
    506
    507
    508
    509
    510
    511
    512
    513
    514
    515
    516
    517
    518
    519
    520
    521
    522
    523
    524
    525
    526
    527
    528
    529
    530
    531
    532
    533
    534
    535
    536
    537
    538
    539
    540
    541
    542
    543
    544
    545
    546
    547
    548
    549
    550
    551
    552
    553
    554
    555
    556
    557
    def predict(
        self,
        source: str | Path | int | Image.Image | list | tuple | np.ndarray | torch.Tensor = None,
        stream: bool = False,
        predictor=None,
        **kwargs: Any,
    ) -> list[Results]:
        """
        Perform predictions on the given image source using the YOLO model.

        This method facilitates the prediction process, allowing various configurations through keyword arguments.
        It supports predictions with custom predictors or the default predictor method. The method handles different
        types of image sources and can operate in a streaming mode.

        Args:
            source (str | Path | int | PIL.Image | np.ndarray | torch.Tensor | list | tuple): The source
                of the image(s) to make predictions on. Accepts various types including file paths, URLs, PIL
                images, numpy arrays, and torch tensors.
            stream (bool): If True, treats the input source as a continuous stream for predictions.
            predictor (BasePredictor, optional): An instance of a custom predictor class for making predictions.
                If None, the method uses a default predictor.
            **kwargs (Any): Additional keyword arguments for configuring the prediction process.

        Returns:
            (list[ultralytics.engine.results.Results]): A list of prediction results, each encapsulated in a
                Results object.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> results = model.predict(source="path/to/image.jpg", conf=0.25)
            >>> for r in results:
            ...     print(r.boxes.data)  # print detection bounding boxes

        Notes:
            - If 'source' is not provided, it defaults to the ASSETS constant with a warning.
            - The method sets up a new predictor if not already present and updates its arguments with each call.
            - For SAM-type models, 'prompts' can be passed as a keyword argument.
        """
        if source is None:
            source = "https://ultralytics.com/images/boats.jpg" if self.task == "obb" else ASSETS
            LOGGER.warning(f"'source' is missing. Using 'source={source}'.")

        is_cli = (ARGV[0].endswith("yolo") or ARGV[0].endswith("ultralytics")) and any(
            x in ARGV for x in ("predict", "track", "mode=predict", "mode=track")
        )

        custom = {"conf": 0.25, "batch": 1, "save": is_cli, "mode": "predict", "rect": True}  # method defaults
        args = {**self.overrides, **custom, **kwargs}  # highest priority args on the right
        prompts = args.pop("prompts", None)  # for SAM-type models

        if not self.predictor:
            self.predictor = (predictor or self._smart_load("predictor"))(overrides=args, _callbacks=self.callbacks)
            self.predictor.setup_model(model=self.model, verbose=is_cli)
        else:  # only update args if predictor is already setup
            self.predictor.args = get_cfg(self.predictor.args, args)
            if "project" in args or "name" in args:
                self.predictor.save_dir = get_save_dir(self.predictor.args)
        if prompts and hasattr(self.predictor, "set_prompts"):  # for SAM-type models
            self.predictor.set_prompts(prompts)
        return self.predictor.predict_cli(source=source) if is_cli else self.predictor(source=source, stream=stream)

### `` reset_callbacks

    reset_callbacks() -> None

Reset all callbacks to their default functions.

This method reinstates the default callback functions for all events, removing any custom callbacks that were previously added. It iterates through all default callback events and replaces the current callbacks with the default ones.

The default callbacks are defined in the 'callbacks.default_callbacks' dictionary, which contains predefined functions for various events in the model's lifecycle, such as on_train_start, on_epoch_end, etc.

This method is useful when you want to revert to the original set of callbacks after making custom modifications, ensuring consistent behavior across different runs or experiments.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> model.add_callback("on_train_start", custom_function)
    >>> model.reset_callbacks()
    # All callbacks are now reset to their default functions

Source code in `ultralytics/engine/model.py`

    1016
    1017
    1018
    1019
    1020
    1021
    1022
    1023
    1024
    1025
    1026
    1027
    1028
    1029
    1030
    1031
    1032
    1033
    1034
    1035
    1036
    1037
    def reset_callbacks(self) -> None:
        """
        Reset all callbacks to their default functions.

        This method reinstates the default callback functions for all events, removing any custom callbacks that were
        previously added. It iterates through all default callback events and replaces the current callbacks with the
        default ones.

        The default callbacks are defined in the 'callbacks.default_callbacks' dictionary, which contains predefined
        functions for various events in the model's lifecycle, such as on_train_start, on_epoch_end, etc.

        This method is useful when you want to revert to the original set of callbacks after making custom
        modifications, ensuring consistent behavior across different runs or experiments.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> model.add_callback("on_train_start", custom_function)
            >>> model.reset_callbacks()
            # All callbacks are now reset to their default functions
        """
        for event in callbacks.default_callbacks.keys():
            self.callbacks[event] = [callbacks.default_callbacks[event][0]]

### `` reset_weights

    reset_weights() -> Model

Reset the model's weights to their initial state.

This method iterates through all modules in the model and resets their parameters if they have a 'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True, enabling them to be updated during training.

Returns:

Type | Description
--- | ---
`Model` | The instance of the class with reset weights.

Raises:

Type | Description
--- | ---
`AssertionError` | If the model is not a PyTorch model.

Examples:

    >>> model = Model("yolo11n.pt")
    >>> model.reset_weights()

Source code in `ultralytics/engine/model.py`

    338
    339
    340
    341
    342
    343
    344
    345
    346
    347
    348
    349
    350
    351
    352
    353
    354
    355
    356
    357
    358
    359
    360
    361
    362
    def reset_weights(self) -> Model:
        """
        Reset the model's weights to their initial state.

        This method iterates through all modules in the model and resets their parameters if they have a
        'reset_parameters' method. It also ensures that all parameters have 'requires_grad' set to True,
        enabling them to be updated during training.

        Returns:
            (Model): The instance of the class with reset weights.

        Raises:
            AssertionError: If the model is not a PyTorch model.

        Examples:
            >>> model = Model("yolo11n.pt")
            >>> model.reset_weights()
        """
        self._check_is_pytorch_model()
        for m in self.model.modules():
            if hasattr(m, "reset_parameters"):
                m.reset_parameters()
        for p in self.model.parameters():
            p.requires_grad = True
        return self

### `` save

    save(filename: str | Path = 'saved_model.pt') -> None

Save the current model state to a file.

This method exports the model's checkpoint (ckpt) to the specified filename. It includes metadata such as the date, Ultralytics version, license information, and a link to the documentation.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`filename` | `str | Path` | The name of the file to save the model to. | `'saved_model.pt'`

Raises:

Type | Description
--- | ---
`AssertionError` | If the model is not a PyTorch model.

Examples:

    >>> model = Model("yolo11n.pt")
    >>> model.save("my_model.pt")

Source code in `ultralytics/engine/model.py`

    392
    393
    394
    395
    396
    397
    398
    399
    400
    401
    402
    403
    404
    405
    406
    407
    408
    409
    410
    411
    412
    413
    414
    415
    416
    417
    418
    419
    420
    421
    422
    def save(self, filename: str | Path = "saved_model.pt") -> None:
        """
        Save the current model state to a file.

        This method exports the model's checkpoint (ckpt) to the specified filename. It includes metadata such as
        the date, Ultralytics version, license information, and a link to the documentation.

        Args:
            filename (str | Path): The name of the file to save the model to.

        Raises:
            AssertionError: If the model is not a PyTorch model.

        Examples:
            >>> model = Model("yolo11n.pt")
            >>> model.save("my_model.pt")
        """
        self._check_is_pytorch_model()
        from copy import deepcopy
        from datetime import datetime

        from ultralytics import __version__

        updates = {
            "model": deepcopy(self.model).half() if isinstance(self.model, torch.nn.Module) else self.model,
            "date": datetime.now().isoformat(),
            "version": __version__,
            "license": "AGPL-3.0 License (https://ultralytics.com/license)",
            "docs": "https://docs.ultralytics.com",
        }
        torch.save({**self.ckpt, **updates}, filename)

### `` track

    track(
        source: str | Path | int | list | tuple | ndarray | Tensor = None,
        stream: bool = False,
        persist: bool = False,
        **kwargs: Any
    ) -> list[Results]

Conduct object tracking on the specified input source using the registered trackers.

This method performs object tracking using the model's predictors and optionally registered trackers. It handles various input sources such as file paths or video streams, and supports customization through keyword arguments. The method registers trackers if not already present and can persist them between calls.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`source` | `str | Path | int | list | tuple | ndarray | Tensor` | Input source for object tracking. Can be a file path, URL, or video stream. | `None`
`stream` | `bool` | If True, treats the input source as a continuous video stream. | `False`
`persist` | `bool` | If True, persists trackers between different calls to this method. | `False`
`**kwargs` | `Any` | Additional keyword arguments for configuring the tracking process. | `{}`

Returns:

Type | Description
--- | ---
`list[Results]` | A list of tracking results, each a Results object.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> results = model.track(source="path/to/video.mp4", show=True)
    >>> for r in results:
    ...     print(r.boxes.id)  # print tracking IDs

Notes

- This method sets a default confidence threshold of 0.1 for ByteTrack-based tracking.
- The tracking mode is explicitly set in the keyword arguments.
- Batch size is set to 1 for tracking in videos.

Source code in `ultralytics/engine/model.py`

    559
    560
    561
    562
    563
    564
    565
    566
    567
    568
    569
    570
    571
    572
    573
    574
    575
    576
    577
    578
    579
    580
    581
    582
    583
    584
    585
    586
    587
    588
    589
    590
    591
    592
    593
    594
    595
    596
    597
    598
    599
    600
    601
    def track(
        self,
        source: str | Path | int | list | tuple | np.ndarray | torch.Tensor = None,
        stream: bool = False,
        persist: bool = False,
        **kwargs: Any,
    ) -> list[Results]:
        """
        Conduct object tracking on the specified input source using the registered trackers.

        This method performs object tracking using the model's predictors and optionally registered trackers. It handles
        various input sources such as file paths or video streams, and supports customization through keyword arguments.
        The method registers trackers if not already present and can persist them between calls.

        Args:
            source (str | Path | int | list | tuple | np.ndarray | torch.Tensor, optional): Input source for object
                tracking. Can be a file path, URL, or video stream.
            stream (bool): If True, treats the input source as a continuous video stream.
            persist (bool): If True, persists trackers between different calls to this method.
            **kwargs (Any): Additional keyword arguments for configuring the tracking process.

        Returns:
            (list[ultralytics.engine.results.Results]): A list of tracking results, each a Results object.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> results = model.track(source="path/to/video.mp4", show=True)
            >>> for r in results:
            ...     print(r.boxes.id)  # print tracking IDs

        Notes:
            - This method sets a default confidence threshold of 0.1 for ByteTrack-based tracking.
            - The tracking mode is explicitly set in the keyword arguments.
            - Batch size is set to 1 for tracking in videos.
        """
        if not hasattr(self.predictor, "trackers"):
            from ultralytics.trackers import register_tracker

            register_tracker(self, persist)
        kwargs["conf"] = kwargs.get("conf") or 0.1  # ByteTrack-based method needs low confidence predictions as input
        kwargs["batch"] = kwargs.get("batch") or 1  # batch-size 1 for tracking in videos
        kwargs["mode"] = "track"
        return self.predict(source=source, stream=stream, **kwargs)

### `` train

    train(trainer=None, **kwargs: Any)

Train the model using the specified dataset and training configuration.

This method facilitates model training with a range of customizable settings. It supports training with a custom trainer or the default training approach. The method handles scenarios such as resuming training from a checkpoint, integrating with Ultralytics HUB, and updating model and configuration after training.

When using Ultralytics HUB, if the session has a loaded model, the method prioritizes HUB training arguments and warns if local arguments are provided. It checks for pip updates and combines default configurations, method-specific defaults, and user-provided arguments to configure the training process.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`trainer` | `BaseTrainer` | Custom trainer instance for model training. If None, uses default. | `None`
`**kwargs` | `Any` | Arbitrary keyword arguments for training configuration. Common options include: data (str): Path to dataset configuration file. epochs (int): Number of training epochs. batch (int): Batch size for training. imgsz (int): Input image size. device (str): Device to run training on (e.g., 'cuda', 'cpu'). workers (int): Number of worker threads for data loading. optimizer (str): Optimizer to use for training. lr0 (float): Initial learning rate. patience (int): Epochs to wait for no observable improvement for early stopping of training. | `{}`

Returns:

Type | Description
--- | ---
`dict | None` | Training metrics if available and training is successful; otherwise, None.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> results = model.train(data="coco8.yaml", epochs=3)

Source code in `ultralytics/engine/model.py`

    738
    739
    740
    741
    742
    743
    744
    745
    746
    747
    748
    749
    750
    751
    752
    753
    754
    755
    756
    757
    758
    759
    760
    761
    762
    763
    764
    765
    766
    767
    768
    769
    770
    771
    772
    773
    774
    775
    776
    777
    778
    779
    780
    781
    782
    783
    784
    785
    786
    787
    788
    789
    790
    791
    792
    793
    794
    795
    796
    797
    798
    799
    800
    801
    802
    803
    804
    805
    806
    807
    def train(
        self,
        trainer=None,
        **kwargs: Any,
    ):
        """
        Train the model using the specified dataset and training configuration.

        This method facilitates model training with a range of customizable settings. It supports training with a
        custom trainer or the default training approach. The method handles scenarios such as resuming training
        from a checkpoint, integrating with Ultralytics HUB, and updating model and configuration after training.

        When using Ultralytics HUB, if the session has a loaded model, the method prioritizes HUB training
        arguments and warns if local arguments are provided. It checks for pip updates and combines default
        configurations, method-specific defaults, and user-provided arguments to configure the training process.

        Args:
            trainer (BaseTrainer, optional): Custom trainer instance for model training. If None, uses default.
            **kwargs (Any): Arbitrary keyword arguments for training configuration. Common options include:
                data (str): Path to dataset configuration file.
                epochs (int): Number of training epochs.
                batch (int): Batch size for training.
                imgsz (int): Input image size.
                device (str): Device to run training on (e.g., 'cuda', 'cpu').
                workers (int): Number of worker threads for data loading.
                optimizer (str): Optimizer to use for training.
                lr0 (float): Initial learning rate.
                patience (int): Epochs to wait for no observable improvement for early stopping of training.

        Returns:
            (dict | None): Training metrics if available and training is successful; otherwise, None.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> results = model.train(data="coco8.yaml", epochs=3)
        """
        self._check_is_pytorch_model()
        if hasattr(self.session, "model") and self.session.model.id:  # Ultralytics HUB session with loaded model
            if any(kwargs):
                LOGGER.warning("using HUB training arguments, ignoring local training arguments.")
            kwargs = self.session.train_args  # overwrite kwargs

        checks.check_pip_update_available()

        if isinstance(kwargs.get("pretrained", None), (str, Path)):
            self.load(kwargs["pretrained"])  # load pretrained weights if provided
        overrides = YAML.load(checks.check_yaml(kwargs["cfg"])) if kwargs.get("cfg") else self.overrides
        custom = {
            # NOTE: handle the case when 'cfg' includes 'data'.
            "data": overrides.get("data") or DEFAULT_CFG_DICT["data"] or TASK2DATA[self.task],
            "model": self.overrides["model"],
            "task": self.task,
        }  # method defaults
        args = {**overrides, **custom, **kwargs, "mode": "train", "session": self.session}  # prioritizes rightmost args
        if args.get("resume"):
            args["resume"] = self.ckpt_path

        self.trainer = (trainer or self._smart_load("trainer"))(overrides=args, _callbacks=self.callbacks)
        if not args.get("resume"):  # manually set model only if not resuming
            self.trainer.model = self.trainer.get_model(weights=self.model if self.ckpt else None, cfg=self.model.yaml)
            self.model = self.trainer.model

        self.trainer.train()
        # Update model and cfg after training
        if RANK in {-1, 0}:
            ckpt = self.trainer.best if self.trainer.best.exists() else self.trainer.last
            self.model, self.ckpt = load_checkpoint(ckpt)
            self.overrides = self.model.args
            self.metrics = getattr(self.trainer.validator, "metrics", None)  # TODO: no metrics returned by DDP
        return self.metrics

### `` tune

    tune(use_ray=False, iterations=10, *args: Any, **kwargs: Any)

Conduct hyperparameter tuning for the model, with an option to use Ray Tune.

This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method. When Ray Tune is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module. Otherwise, it uses the internal 'Tuner' class for tuning. The method combines default, overridden, and custom arguments to configure the tuning process.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`use_ray` | `bool` | Whether to use Ray Tune for hyperparameter tuning. If False, uses internal tuning method. | `False`
`iterations` | `int` | Number of tuning iterations to perform. | `10`
`*args` | `Any` | Additional positional arguments to pass to the tuner. | `()`
`**kwargs` | `Any` | Additional keyword arguments for tuning configuration. These are combined with model overrides and defaults to configure the tuning process. | `{}`

Returns:

Type | Description
--- | ---
`dict` | Results of the hyperparameter search, including best parameters and performance metrics.

Raises:

Type | Description
--- | ---
`TypeError` | If the model is not a PyTorch model.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> results = model.tune(data="coco8.yaml", iterations=5)
    >>> print(results)

#### Use Ray Tune for more advanced hyperparameter search

    >>> results = model.tune(use_ray=True, iterations=20, data="coco8.yaml")

Source code in `ultralytics/engine/model.py`

    809
    810
    811
    812
    813
    814
    815
    816
    817
    818
    819
    820
    821
    822
    823
    824
    825
    826
    827
    828
    829
    830
    831
    832
    833
    834
    835
    836
    837
    838
    839
    840
    841
    842
    843
    844
    845
    846
    847
    848
    849
    850
    851
    852
    853
    854
    855
    def tune(
        self,
        use_ray=False,
        iterations=10,
        *args: Any,
        **kwargs: Any,
    ):
        """
        Conduct hyperparameter tuning for the model, with an option to use Ray Tune.

        This method supports two modes of hyperparameter tuning: using Ray Tune or a custom tuning method.
        When Ray Tune is enabled, it leverages the 'run_ray_tune' function from the ultralytics.utils.tuner module.
        Otherwise, it uses the internal 'Tuner' class for tuning. The method combines default, overridden, and
        custom arguments to configure the tuning process.

        Args:
            use_ray (bool): Whether to use Ray Tune for hyperparameter tuning. If False, uses internal tuning method.
            iterations (int): Number of tuning iterations to perform.
            *args (Any): Additional positional arguments to pass to the tuner.
            **kwargs (Any): Additional keyword arguments for tuning configuration. These are combined with model
                overrides and defaults to configure the tuning process.

        Returns:
            (dict): Results of the hyperparameter search, including best parameters and performance metrics.

        Raises:
            TypeError: If the model is not a PyTorch model.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> results = model.tune(data="coco8.yaml", iterations=5)
            >>> print(results)

            # Use Ray Tune for more advanced hyperparameter search
            >>> results = model.tune(use_ray=True, iterations=20, data="coco8.yaml")
        """
        self._check_is_pytorch_model()
        if use_ray:
            from ultralytics.utils.tuner import run_ray_tune

            return run_ray_tune(self, max_samples=iterations, *args, **kwargs)
        else:
            from .tuner import Tuner

            custom = {}  # method defaults
            args = {**self.overrides, **custom, **kwargs, "mode": "train"}  # highest priority args on the right
            return Tuner(args=args, _callbacks=self.callbacks)(model=self, iterations=iterations)

### `` val

    val(validator=None, **kwargs: Any)

Validate the model using a specified dataset and validation configuration.

This method facilitates the model validation process, allowing for customization through various settings. It supports validation with a custom validator or the default validation approach. The method combines default configurations, method-specific defaults, and user-provided arguments to configure the validation process.

Parameters:

Name | Type | Description | Default
--- | --- | --- | ---
`validator` | `BaseValidator` | An instance of a custom validator class for validating the model. | `None`
`**kwargs` | `Any` | Arbitrary keyword arguments for customizing the validation process. | `{}`

Returns:

Type | Description
--- | ---
`DetMetrics` | Validation metrics obtained from the validation process.

Raises:

Type | Description
--- | ---
`AssertionError` | If the model is not a PyTorch model.

Examples:

    >>> model = YOLO("yolo11n.pt")
    >>> results = model.val(data="coco8.yaml", imgsz=640)
    >>> print(results.box.map)  # Print mAP50-95

Source code in `ultralytics/engine/model.py`

    603
    604
    605
    606
    607
    608
    609
    610
    611
    612
    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
    def val(
        self,
        validator=None,
        **kwargs: Any,
    ):
        """
        Validate the model using a specified dataset and validation configuration.

        This method facilitates the model validation process, allowing for customization through various settings. It
        supports validation with a custom validator or the default validation approach. The method combines default
        configurations, method-specific defaults, and user-provided arguments to configure the validation process.

        Args:
            validator (ultralytics.engine.validator.BaseValidator, optional): An instance of a custom validator class
                for validating the model.
            **kwargs (Any): Arbitrary keyword arguments for customizing the validation process.

        Returns:
            (ultralytics.utils.metrics.DetMetrics): Validation metrics obtained from the validation process.

        Raises:
            AssertionError: If the model is not a PyTorch model.

        Examples:
            >>> model = YOLO("yolo11n.pt")
            >>> results = model.val(data="coco8.yaml", imgsz=640)
            >>> print(results.box.map)  # Print mAP50-95
        """
        custom = {"rect": True}  # method defaults
        args = {**self.overrides, **custom, **kwargs, "mode": "val"}  # highest priority args on the right

        validator = (validator or self._smart_load("validator"))(args=args, _callbacks=self.callbacks)
        validator(model=self.model)
        self.metrics = validator.metrics
        return validator.metrics

📅 Created 1 year ago ✏️ Updated 1 year ago