← All articles

AI / Machine Learning · 5 November 2026 · 12 min read

Training and Running YOLO Models with Ultralytics: A Practical Guide

Learn how to train custom YOLO object detection models using Ultralytics, prepare datasets, configure training parameters, evaluate model performance, and run inference on images, videos, and live camera feeds using Python.

  • YOLO
  • Ultralytics
  • Computer Vision
  • Object Detection
  • Deep Learning
  • Python
Training and Running YOLO Models with Ultralytics: A Practical Guide

Training and Running YOLO Models with Ultralytics: A Practical Guide

Object detection is one of the most widely used applications of computer vision. From identifying defective products on manufacturing lines to detecting vehicles, monitoring traffic, and tracking objects in videos, object detection models help machines understand visual information.

Among the available computer vision frameworks, Ultralytics YOLO provides a relatively straightforward way to train custom object detection models without implementing an entire deep learning training pipeline from scratch.

Instead of manually implementing the model architecture, loss functions, training loops, and inference logic, developers can use the Ultralytics Python API to manage most of these operations.

In this tutorial, we'll explore how to:

  • Install and configure Ultralytics.
  • Understand the YOLO dataset structure.
  • Prepare custom datasets and annotations.
  • Train a YOLO model using pretrained weights.
  • Evaluate and validate the trained model.
  • Perform inference on images, videos, and webcams.
  • Extract bounding boxes, class labels, and confidence scores.
  • Export models for deployment.

We'll primarily focus on object detection using Python.

1. Understanding Ultralytics YOLO

Ultralytics provides an ecosystem of computer vision models and tools built around YOLO.

YOLO stands for You Only Look Once. It is a family of object detection architectures designed to predict object locations and classes from images.

An object detection model typically produces three important outputs:

  1. Bounding boxes: The coordinates describing where an object is located.
  2. Class labels: The category assigned to each detected object.
  3. Confidence scores: The model's confidence in its prediction.

For example, consider an image containing a person, a bicycle, and a car.

A trained YOLO model can identify these objects and return their respective bounding boxes and confidence scores.

What makes Ultralytics useful?

One of the biggest advantages of Ultralytics is its unified API.

The same Python interface supports multiple computer vision tasks:

  • Object detection
  • Instance segmentation
  • Image classification
  • Pose estimation
  • Oriented bounding box detection
  • Semantic segmentation
  • Depth estimation

Ultralytics also provides several model lifecycle operations:

Mode Purpose
Train Train a model using a dataset
Val Evaluate model performance
Predict Run inference on new inputs
Track Track detected objects across frames
Export Convert models into deployment formats
Benchmark Compare model performance across formats

We'll primarily work with the Train, Val, Predict, and Export modes.

2. Setting Up the Environment

Before training a model, we need to install the required dependencies.

I recommend using a virtual environment to keep project dependencies isolated.

Create a project

mkdir yolo-project
cd yolo-project
 
python -m venv .venv

Activate the environment.

Windows:

.venv\Scripts\activate

Linux / macOS:

source .venv/bin/activate

Install Ultralytics

Install the package using pip:

pip install -U ultralytics

This installs the Ultralytics package and its required dependencies.

For GPU training, ensure that your PyTorch installation is compatible with your operating system, GPU, and CUDA environment. Follow the official PyTorch installation guide when a specific CUDA build is required.

Verify the installation

Create a Python file called test_yolo.py:

from ultralytics import YOLO
 
model = YOLO("yolo26n.pt")
 
print("YOLO model loaded successfully!")

Run it:

python test_yolo.py

The pretrained model weights will be downloaded automatically if they are not already available locally.

A note about model versions: This tutorial uses YOLO26 because it is the current model family featured in the Ultralytics documentation. If you are working with YOLO11, you can use the corresponding weights, such as yolo11n.pt, instead. Always check the documentation for the model family you intend to use.

3. Understanding the YOLO Dataset Structure

Before training a custom model, we need a properly organized dataset.

A dataset generally consists of two important components:

  • Images containing the objects we want to detect.
  • Annotations describing the locations and classes of those objects.

For object detection, Ultralytics supports the YOLO annotation format.

Recommended directory structure

Organize your dataset like this:

dataset/
│
├── images/
│   ├── train/
│   ├── val/
│   └── test/
│
├── labels/
│   ├── train/
│   ├── val/
│   └── test/
│
└── data.yaml

Each image should have a corresponding annotation file with the same filename.

For example:

images/train/image001.jpg
labels/train/image001.txt

The annotation file contains the bounding box information for objects in that image.

Understanding YOLO annotation format

For object detection, each annotation line follows this structure:

class_id x_center y_center width height

The bounding box coordinates are normalized between 0 and 1.

For example:

0 0.512 0.423 0.210 0.315
1 0.723 0.615 0.150 0.240

Each line represents one object.

The values mean:

  • class_id: Integer representing the object category.
  • x_center: Normalized horizontal center coordinate.
  • y_center: Normalized vertical center coordinate.
  • width: Normalized bounding box width.
  • height: Normalized bounding box height.

Why normalized coordinates?

Images can have different resolutions. Normalizing bounding box coordinates makes the annotations independent of the original image dimensions.

For example, a bounding box center at 50% of the image width will have an x-coordinate of 0.5, regardless of whether the image is 640 or 1920 pixels wide.

Creating the dataset configuration

Ultralytics uses a YAML configuration file to identify dataset locations and class names.

Create data.yaml:

path: ./dataset
 
train: images/train
val: images/val
test: images/test
 
names:
  0: person
  1: vehicle
  2: bicycle

The path field defines the dataset root directory, while train, val, and test identify the respective image directories.

The names field maps class IDs to their corresponding labels.

Make sure the class IDs in your annotation files match the class definitions in this configuration.

Important: The test split is optional for training, but keeping an independent test set is useful for final evaluation.

Dataset preparation considerations

Dataset quality has a direct impact on model performance.

Before training, consider the following:

  • Use diverse images with different lighting conditions and backgrounds.
  • Include objects at different scales and orientations.
  • Avoid incorrect or inconsistent bounding box annotations.
  • Check that every annotation references a valid class ID.
  • Avoid placing near-duplicate images across training and validation splits.
  • Include challenging examples and images without target objects where appropriate.

A larger dataset is not automatically a better dataset. Annotation quality and data diversity matter considerably.

4. Loading a Pretrained YOLO Model

Now that the dataset is ready, we can load a YOLO model.

Ultralytics supports loading models from pretrained .pt weights or model configuration files.

from ultralytics import YOLO
 
model = YOLO("yolo26n.pt")

Here, yolo26n.pt represents a pretrained nano-sized detection model.

Why use pretrained weights?

Pretrained models have already learned useful visual representations from existing training datasets.

Instead of learning everything from scratch, we can fine-tune the model using our custom dataset.

This approach is called transfer learning.

Choosing a model size

YOLO model families commonly provide different sizes, such as:

  • Nano (n)
  • Small (s)
  • Medium (m)
  • Large (l)
  • Extra Large (x)

Generally, smaller models require fewer computational resources, while larger models offer greater model capacity at the cost of increased computation.

The best model depends on the application.

For example:

Model size Potential use case
Nano Edge devices and lightweight applications
Small General-purpose applications
Medium Applications with more computational resources
Large More demanding detection tasks
Extra Large Resource-intensive experiments

Do not automatically choose the largest model. Benchmark different sizes on your target hardware and compare their accuracy and inference speed.

5. Training a Custom YOLO Model

This is where the actual training process begins.

Ultralytics provides a train() method that handles the training pipeline.

Create a file named train.py:

from ultralytics import YOLO
 
# Load pretrained weights
model = YOLO("yolo26n.pt")
 
# Train on a custom dataset
results = model.train(
    data="dataset/data.yaml",
    epochs=100,
    imgsz=640,
    batch=16,
    device=0,
    workers=4,
    project="runs/detect",
    name="custom_yolo"
)

Let's understand the important parameters.

Parameter Description
data Path to dataset YAML
epochs Number of training epochs
imgsz Input image size
batch Batch size
device Training device
workers Data loading worker processes
project Output directory
name Experiment name

Understanding training parameters

Epochs

An epoch represents one complete pass through the training dataset.

Increasing the number of epochs gives the model more opportunities to learn, but excessive training can lead to overfitting.

Image size

The imgsz parameter controls the image resolution used during training.

A common starting point is:

imgsz=640

Higher image resolutions can help with smaller objects, but they also increase computational requirements.

Batch size

Batch size determines how many images are processed in one training iteration.

For example:

batch=16

If GPU memory is insufficient, try reducing the batch size.

Device

You can explicitly specify the training device:

device=0

This selects the first CUDA GPU.

For CPU training:

device="cpu"

Ultralytics can also automatically select an available device when this argument is omitted.

What happens during training?

At a high level, the training process follows this sequence:

  1. Images and annotations are loaded.
  2. Images undergo preprocessing and augmentation.
  3. The model generates predictions.
  4. Predictions are compared against ground-truth annotations.
  5. Loss values are calculated.
  6. Backpropagation updates the model parameters.
  7. Validation is performed periodically.
  8. Model checkpoints and training metrics are saved.

You do not need to implement these operations manually when using the high-level Ultralytics API.

Where are the trained weights stored?

After training, Ultralytics creates an experiment directory.

A typical structure looks like this:

runs/
└── detect/
    └── custom_yolo/
        ├── weights/
        │   ├── best.pt
        │   └── last.pt
        │
        ├── results.csv
        ├── results.png
        ├── confusion_matrix.png
        ├── PR_curve.png
        ├── F1_curve.png
        └── args.yaml

Two files deserve particular attention:

  • best.pt: Checkpoint selected using validation performance.
  • last.pt: Checkpoint from the final training epoch.

For most inference workflows, best.pt is the appropriate starting point.

6. Validating the Trained Model

Training a model does not automatically mean that it performs well.

We need to evaluate its performance using validation data.

Ultralytics provides the val() method.

Create validate.py:

from ultralytics import YOLO
 
# Load the trained model
model = YOLO(
    "runs/detect/custom_yolo/weights/best.pt"
)
 
# Evaluate the model
metrics = model.val(
    data="dataset/data.yaml"
)
 
print(metrics)

Understanding evaluation metrics

For object detection, some important metrics include:

Precision

Precision measures how many predicted positive detections are correct.

A higher precision generally means fewer false-positive detections.

Recall

Recall measures how many actual objects the model successfully detects.

A higher recall generally means fewer missed objects.

Intersection over Union (IoU)

IoU measures the overlap between a predicted bounding box and its corresponding ground-truth box.

Mean Average Precision (mAP)

mAP summarizes object detection performance across classes.

Two commonly used metrics are:

  • mAP50: Mean average precision at an IoU threshold of 0.50.
  • mAP50-95: Mean average precision averaged across IoU thresholds from 0.50 to 0.95.

Do not evaluate a model using a single metric alone.

For example, a safety monitoring system may prioritize recall because missing an important object can be more costly than generating an occasional false positive.

Also, reserve the test split for final evaluation rather than repeatedly tuning against it.

7. Performing Inference with YOLO

Once training and validation are complete, we can use the trained model to make predictions on unseen data.

This process is called inference.

Inference is the stage where a trained model receives new input and generates predictions.

Loading the trained model

from ultralytics import YOLO
 
model = YOLO(
    "runs/detect/custom_yolo/weights/best.pt"
)

We can now use the predict() method.

Inference on an image

results = model.predict(
    source="test.jpg",
    conf=0.25,
    save=True
)

Here:

  • source specifies the input image.
  • conf defines the minimum confidence threshold.
  • save=True saves the annotated prediction image.

The model returns a list of Results objects.

Extracting detection results

One of the most useful features of Ultralytics is that it provides access to the raw prediction information.

for result in results:
 
    boxes = result.boxes
 
    for box in boxes:
 
        # Bounding box coordinates
        xyxy = box.xyxy[0]
 
        # Confidence score
        confidence = box.conf[0]
 
        # Predicted class ID
        class_id = int(box.cls[0])
 
        # Class name
        class_name = result.names[class_id]
 
        print("Class:", class_name)
        print("Confidence:", float(confidence))
        print("Bounding Box:", xyxy.tolist())

The bounding box coordinates use the following format:

[x1, y1, x2, y2]

Where:

  • x1, y1 represent the top-left corner.
  • x2, y2 represent the bottom-right corner.

This information is particularly useful when integrating YOLO with other applications.

For example, you can use bounding boxes to calculate object positions, count detected objects, trigger alerts, or store detection results in a database.

Adjusting confidence thresholds

The confidence threshold controls which predictions are retained.

results = model.predict(
    source="test.jpg",
    conf=0.5
)

A higher threshold generally removes more low-confidence predictions, potentially reducing false positives but also increasing missed detections.

The appropriate threshold should be selected using validation data and the requirements of the application.

8. Running Inference on Videos

Object detection becomes particularly interesting when working with video streams.

Ultralytics can process video files directly.

from ultralytics import YOLO
 
model = YOLO(
    "runs/detect/custom_yolo/weights/best.pt"
)
 
results = model.predict(
    source="input_video.mp4",
    conf=0.25,
    save=True
)

The framework processes the video frame by frame and generates annotated output.

Memory-efficient video inference

For longer videos, use stream=True.

results = model.predict(
    source="input_video.mp4",
    conf=0.25,
    stream=True
)
 
for result in results:
 
    print(result.boxes)

With streaming enabled, the predictor yields results one at a time instead of retaining all results in a list.

This is particularly useful when processing long videos or large collections of images.

Running inference using a webcam

You can also use a connected camera as an inference source.

results = model.predict(
    source=0,
    show=True
)

Here, source=0 represents the default camera device.

You can change the device index if multiple cameras are connected.

This can be useful for testing real-time object detection applications.

9. Exporting YOLO Models for Deployment

A trained .pt model is useful during development, but production applications may require different model formats.

Ultralytics supports exporting models into formats such as:

  • ONNX
  • TensorRT
  • OpenVINO
  • CoreML
  • TorchScript

The appropriate format depends on the deployment environment.

Exporting to ONNX

ONNX is useful when integrating models into applications that support the ONNX Runtime ecosystem.

from ultralytics import YOLO
 
model = YOLO(
    "runs/detect/custom_yolo/weights/best.pt"
)
 
model.export(
    format="onnx"
)

This generates an ONNX model that can be used with compatible inference runtimes.

Exporting to TensorRT

For supported NVIDIA GPU environments, TensorRT can be used to optimize inference.

model.export(
    format="engine",
    device=0
)

The resulting engine is intended for compatible TensorRT environments.

Remember that exporting a model does not automatically guarantee better performance. Benchmark the exported model against the original PyTorch model on the actual target hardware.

10. Common Problems and Troubleshooting

Even though Ultralytics simplifies model training, some issues are common when building custom computer vision applications.

Problem Possible solution
CUDA out-of-memory Reduce batch size or image resolution
Dataset not found Verify the dataset YAML paths
Missing annotations Check corresponding image and label filenames
Poor detection accuracy Review annotation quality and dataset diversity
Model overfitting Improve data diversity and adjust training
Slow inference Test smaller models and optimized export formats
Webcam not opening Check camera permissions and device index
Incorrect class predictions Verify class ID mappings and dataset labels

One particularly common issue is incorrect dataset organization.

Before starting a long training run, inspect a few images and their annotations. A small amount of dataset verification can save considerable GPU time.

11. Important Considerations Before Production Deployment

Training and running inference successfully is only one part of building a real-world computer vision system.

There are several additional considerations.

Model evaluation: Evaluate the model using representative real-world data, not only training images.

Inference performance: Measure latency, throughput, memory usage, and performance under realistic workloads.

Input validation: Ensure that incoming images and videos are valid and handled safely.

Monitoring: Track prediction quality and identify situations where the model consistently fails.

Versioning: Keep track of model weights, dataset versions, training configurations, and evaluation results.

Licensing: Review the Ultralytics licensing terms before commercial deployment. Ultralytics currently offers AGPL-3.0 and an Enterprise licensing option. Its published guidance identifies proprietary applications and SaaS deployments as cases requiring an Enterprise License unless the project complies with AGPL-3.0 obligations. Review the official licensing information before building a commercial product around it.

Conclusion

Ultralytics makes it considerably easier to work with YOLO models by providing a unified interface for dataset configuration, training, validation, inference, and model export.

The most important part of building a reliable object detection system, however, is not simply choosing a model or increasing the number of training epochs.

It is understanding the complete pipeline:

  1. Collect and prepare a representative dataset.
  2. Ensure that annotations are accurate.
  3. Select an appropriate pretrained model.
  4. Train and validate using suitable configurations.
  5. Analyze model performance and failure cases.
  6. Run inference on realistic inputs.
  7. Optimize and deploy the model for the target environment.

Once you understand this workflow, you can start building more sophisticated computer vision applications, whether that means defect detection, traffic monitoring, automated inspection, or real-time object tracking.

The next step is to take a small custom dataset, train a YOLO model, inspect its predictions, and gradually improve it based on actual evaluation results.


References

  1. Ultralytics Documentation – Python Usage
  2. Ultralytics Documentation – Installation and Quickstart
  3. Ultralytics Documentation – Model Training
  4. Ultralytics Documentation – Model Prediction
  5. Ultralytics Documentation – Dataset Overview
  6. Ultralytics Documentation – Configuration
  7. Ultralytics – Licensing
AS

Aditya Manoj Shinde

Author

I'm Aditya, a developer passionate about AI, Machine Learning, and software development. I love exploring new technologies, building projects, and sharing what I learn along the way.