Enhance Your Dataset to Train YOLO26 Using Albumentations
When you are building computer vision models, the quality and variety of your training data can play a big role in how well your model performs. Albumentations offers a fast, flexible, and efficient way to apply a wide range of image transformations that can improve your model's ability to adapt to real-world scenarios. It integrates with Ultralytics YOLO26 and can help you create robust datasets for object detection, instance segmentation, semantic segmentation, depth estimation, pose estimation, and oriented bounding box tasks.
Albumentations adds techniques like geometric transformations and color adjustments to your YOLO26 training data. This guide explains how Albumentations fits into the Ultralytics data augmentation pipeline and how to customize it for your projects.
Albumentations for Image Augmentation#
Albumentations is an open-source image augmentation library created in June 2018. It is designed to simplify and accelerate the image augmentation process in computer vision. Created with performance and flexibility in mind, it supports many diverse augmentation techniques, ranging from simple transformations like rotations and flips to more complex adjustments like brightness and contrast changes. Albumentations helps developers generate rich, varied datasets for tasks like image classification, object detection, and segmentation.
You can use Albumentations to easily apply augmentations to images, segmentation masks, bounding boxes, and keypoints, and make sure that all elements of your dataset are transformed together. It works with popular deep learning frameworks like PyTorch and TensorFlow, making it accessible for a wide range of projects.
Albumentations suits both small datasets and large-scale computer vision tasks. Its fast processing reduces the time spent on data preparation, and more varied training data can improve model performance in real-world applications.
Key Features of Albumentations#
Albumentations offers many useful features that simplify complex image augmentations for a wide range of computer vision applications. Here are some of the key features:
- Wide Range of Transformations: Albumentations offers over 70 different transformations, including geometric changes (e.g., rotation, flipping), color adjustments (e.g., brightness, contrast), and noise addition (e.g., Gaussian noise). Having multiple options enables the creation of highly diverse and robust training datasets.
-
High Performance Optimization: Built on OpenCV and NumPy, Albumentations uses advanced optimization techniques like SIMD (Single Instruction, Multiple Data), which processes multiple data points simultaneously to speed up processing. It handles large datasets quickly, making it one of the fastest options available for image augmentation.
-
Three Levels of Augmentation: Albumentations supports three levels of augmentation: pixel-level transformations, spatial-level transformations, and mixing-level transformations. Pixel-level transformations only affect the input images without altering masks, bounding boxes, or keypoints. Spatial-level transformations change both the image and its elements, like masks and bounding boxes. Mixing-level transformations combine multiple images into one.

- Benchmarking Results: Albumentations' published benchmarks compare its speed favorably with other augmentation libraries, especially on large datasets.
Why Should You Use Albumentations for Your Vision AI Projects?#
With respect to image augmentation, Albumentations stands out as a reliable tool for computer vision tasks. Here are a few key reasons why you should consider using it for your Vision AI projects:
-
Easy-to-Use API: Albumentations provides a single, straightforward API for applying a wide range of augmentations to images, masks, bounding boxes, and keypoints. It's designed to adapt easily to different datasets, making data preparation simpler and more efficient.
-
Rigorous Bug Testing: Bugs in the augmentation pipeline can silently corrupt input data, often going unnoticed but ultimately degrading model performance. Albumentations addresses this with a thorough test suite that helps catch bugs early in development.
-
Extensibility: Albumentations makes it easy to add new augmentations and use them alongside built-in transformations through a single interface.
How to Use Albumentations to Augment Data for YOLO26 Training#
Albumentations integrates directly into Ultralytics' training mode and applies automatically when the Albumentations package is installed.
Installation#
To use Albumentations with YOLO26, start by making sure you have the necessary packages installed. If Albumentations isn't installed, its augmentations won't be applied during training. Once it is installed, the transforms are applied on the fly to training images.
# Install the required packages
pip install albumentations ultralyticsFor detailed instructions and best practices related to the installation process, check our Ultralytics Installation guide. While installing the required packages for YOLO26, if you encounter any difficulties, consult our Common Issues guide for solutions and tips.
The custom transform examples on this page need Albumentations 1.4.22 or newer, and therefore Python 3.9 or newer.
Usage#
After installing the necessary packages, you're ready to start using Albumentations with YOLO26. When you train YOLO26 with Albumentations installed, a default set of Albumentations transforms is applied automatically.
from ultralytics import YOLO
# Load a pretrained model
model = YOLO("yolo26n.pt")
# Train the model with default augmentations
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)The following sections describe the default Albumentations transforms applied during training.
Blur#
The Blur transformation in Albumentations applies a simple blur effect to the image by averaging pixel values within a small square area, or kernel. This is done using the OpenCV cv2.blur function, which helps reduce noise in the image, though it also slightly reduces image details.
Here are the parameters and values used in this integration:
-
blur_limit: This controls the size range of the blur effect. The default range is (3, 7), meaning the kernel size for the blur can vary between 3 and 7 pixels, with only odd numbers allowed to keep the blur centered.
-
p: The probability of applying the blur. In the integration, p=0.01, so there's a 1% chance that this blur will be applied to each image. The low probability allows for occasional blur effects, introducing a bit of variation to help the model generalize without over-blurring the images.
Median Blur#
The MedianBlur transformation in Albumentations applies a median blur effect to the image, which is particularly useful for reducing noise while preserving edges. Unlike typical blurring methods, MedianBlur uses a median filter, which is especially effective at removing salt-and-pepper noise while maintaining sharpness around the edges.
Here are the parameters and values used in this integration:
-
blur_limit: This parameter controls the maximum size of the blurring kernel. In this integration, it defaults to a range of (3, 7), meaning the kernel size for the blur is randomly chosen between 3 and 7 pixels, with only odd values allowed to ensure proper alignment.
-
p: Sets the probability of applying the median blur. Here, p=0.01, so the transformation has a 1% chance of being applied to each image. This low probability ensures that the median blur is used sparingly, helping the model generalize by occasionally seeing images with reduced noise and preserved edges.
The image below shows an example of this augmentation applied to an image.
Grayscale#
The ToGray transformation in Albumentations converts an image to grayscale, reducing it to a single-channel format and optionally replicating this channel to match a specified number of output channels. Different methods can be used to adjust how grayscale brightness is calculated, ranging from simple averaging to more advanced techniques for realistic perception of contrast and brightness.
Here are the parameters and values used in this integration:
-
num_output_channels: Sets the number of channels in the output image. If this value is more than 1, the single grayscale channel will be replicated to create a multichannel grayscale image. By default, it's set to 3, giving a grayscale image with three identical channels.
-
method: Defines the grayscale conversion method. The default method, "weighted_average", applies a formula (0.299R + 0.587G + 0.114B) that closely aligns with human perception, providing a natural-looking grayscale effect. Other options, like "from_lab", "desaturation", "average", "max", and "pca", offer alternative ways to create grayscale images based on various needs for speed, brightness emphasis, or detail preservation.
-
p: Controls how often the grayscale transformation is applied. With p=0.01, there is a 1% chance of converting each image to grayscale, making it possible for a mix of color and grayscale images to help the model generalize better.
The image below shows an example of this grayscale transformation applied.
Contrast Limited Adaptive Histogram Equalization (CLAHE)#
The CLAHE transformation in Albumentations applies Contrast Limited Adaptive Histogram Equalization (CLAHE), a technique that enhances image contrast by equalizing the histogram in localized regions (tiles) instead of across the whole image. CLAHE produces a balanced enhancement effect, avoiding the overly amplified contrast that can result from standard histogram equalization, especially in areas with initially low contrast.
Here are the parameters and values used in this integration:
-
clip_limit: Controls the contrast enhancement range. Set to a default range of (1, 4), it determines the maximum contrast allowed in each tile. Higher values allow more contrast but may also introduce noise.
-
tile_grid_size: Defines the size of the grid of tiles, typically as (rows, columns). The default value is (8, 8), meaning the image is divided into an 8x8 grid. Smaller tile sizes provide more localized adjustments, while larger ones create effects closer to global equalization.
-
p: The probability of applying CLAHE. Here, p=0.01 introduces the enhancement effect only 1% of the time, ensuring that contrast adjustments are applied sparingly for occasional variation in training images.
The image below shows an example of the CLAHE transformation applied.
Using Custom Albumentations Transforms#
While the default Albumentations integration provides a solid set of augmentations, you may want to customize the transforms for your specific use case. With Ultralytics YOLO26, you can pass custom Albumentations transforms via the Python API using the augmentations parameter. The examples in this section need Albumentations 1.4.22 or newer.
How to Define Custom Transforms#
You can define your own list of Albumentations transforms and pass them to the training function. This replaces the default Albumentations transforms while keeping all other YOLO augmentations (like hsv_h, degrees, mosaic, etc.) active.
Here's an example with more advanced transforms:
import albumentations as A
from ultralytics import YOLO
# Load model
model = YOLO("yolo26n.pt")
# Define custom transforms with various augmentation techniques
custom_transforms = [
# Blur variations
A.OneOf(
[
A.MotionBlur(blur_limit=7, p=1.0),
A.MedianBlur(blur_limit=7, p=1.0),
A.GaussianBlur(blur_limit=7, p=1.0),
],
p=0.3,
),
# Noise variations
A.OneOf(
[
A.GaussNoise(std_range=(0.0124, 0.0277), p=1.0),
A.ISONoise(color_shift=(0.01, 0.05), intensity=(0.1, 0.5), p=1.0),
],
p=0.2,
),
# Color and contrast adjustments
A.CLAHE(clip_limit=4.0, tile_grid_size=(8, 8), p=0.5),
A.RandomBrightnessContrast(brightness_limit=0.3, contrast_limit=0.3, p=0.5),
A.HueSaturationValue(hue_shift_limit=20, sat_shift_limit=30, val_shift_limit=20, p=0.5),
# Simulate occlusions
A.CoarseDropout(num_holes_range=(1, 8), hole_height_range=(8, 32), hole_width_range=(8, 32), fill=0, p=0.2),
]
# Train with custom transforms
results = model.train(
data="coco8.yaml",
epochs=100,
imgsz=640,
augmentations=custom_transforms,
)Important Considerations#
When using custom Albumentations transforms, keep these points in mind:
- Configuration: Build custom transform objects through the Python API. Serialized transforms can also be passed through CLI or YAML configuration files, including when resuming training.
- Replaces Defaults: Your custom transforms will completely replace the default Albumentations transforms. Other YOLO augmentations remain active.
- Label Handling: Spatial transforms, including ones nested in
A.OneOforA.Compose, move bounding boxes, polygons, keypoints, and depth or semantic masks together with the image.A.RandomGridShufflecannot preserve polygon or keypoint topology and raises on segmentation, pose, and OBB samples. - Performance: Some transforms are computationally expensive. Monitor training speed and adjust accordingly.
- Task Compatibility: Custom Albumentations transforms work with detection, segmentation, semantic segmentation, depth, pose, and OBB training but not with classification (which uses a different augmentation pipeline).
Use Cases for Custom Transforms#
Different applications benefit from different augmentation strategies:
- Medical Imaging: Use elastic deformations, grid distortions, and specialized noise patterns
- Aerial/Satellite Imagery: Apply transforms that simulate different altitudes, weather conditions, and lighting angles
- Low-Light Scenarios: Emphasize noise addition and brightness adjustments to train robust models for challenging lighting
- Industrial Inspection: Add texture variations and simulated defects for quality control applications
For a complete list of available transforms and their parameters, visit the Albumentations documentation.
For more detailed examples and best practices on using custom Albumentations transforms with YOLO26, see the YOLO Data Augmentation guide.
Keep Learning about Albumentations#
If you are interested in learning more about Albumentations, check out the following resources for more in-depth instructions and examples:
-
Albumentations Documentation: The official documentation provides a full range of supported transformations and advanced usage techniques.
-
Ultralytics Albumentations API Reference: See the details of the class that implements this integration.
-
Albumentations GitHub Repository: The repository includes examples, benchmarks, and discussions to help you get started with customizing augmentations.
Key Takeaways#
In this guide, we explored the key aspects of Albumentations, a Python library for image augmentation. We discussed its wide range of transformations, optimized performance, and how you can use it in your next YOLO26 project.
FAQ#
Albumentations integrates with YOLO26 and applies automatically during training if you have the package installed. Here's how to get started:
# Install required packages # !pip install albumentations ultralytics from ultralytics import YOLO # Load and train model with automatic augmentations model = YOLO("yolo26n.pt") model.train(data="coco8.yaml", epochs=100)The default integration applies blur, median blur, grayscale conversion, and CLAHE, each with a low 1% probability so they add occasional variation without dominating training.
Albumentations stands out for several reasons:
- Performance: Built on OpenCV and NumPy with SIMD optimization for high speed
- Flexibility: Supports 70+ transformations across pixel-level, spatial-level, and mixing-level augmentations
- Compatibility: Works with popular frameworks like PyTorch and TensorFlow
- Reliability: Extensive test suite prevents silent data corruption
- Ease of use: Single unified API for all augmentation types
Albumentations enhances various computer vision tasks including:
- Object Detection: Improves model robustness to lighting, scale, and orientation variations
- Instance Segmentation: Enhances mask prediction accuracy through diverse transformations
- Pose Estimation: Helps models adapt to different viewpoints and lighting conditions
- Oriented Bounding Box Detection: Adds color and noise variation for aerial and rotated-object imagery
The library's diverse augmentation options make it valuable for vision tasks requiring robust model performance. In Ultralytics YOLO26, classification training uses its own torchvision-based augmentation pipeline and does not apply Albumentations transforms.
Comments19
Ask a question, share your results, or help someone else.
anushka-kore
Is there a way that we can define more custom albumentations transforms to be applied during model train? If yes, will they also change the bounding box coords accordingly if they are spatial transforms?
manuelescobar5036
The albumentations transforms are defined in the ultralytics/data/augment.py file. There you can find the following function that returns the transforms to be applied to the images, which includes the Albumentations transform.
Then, in the same file you can find the Albumentations class which defines the pipeline. In this pipeline you can add the new transforms that you want.
Bouding boxes are changed accordingly to their spatial transforms. This is done when you pass bbox_params to the Albumentations pipeline.
Glenn JocherUltralytics(edited)@anushka-kore Yes. Pass your own Albumentations transforms to training with the
augmentationsargument (Python only):import albumentations as A from ultralytics import YOLO model = YOLO("yolo26n.pt") model.train(data="coco8.yaml", augmentations=[A.Blur(p=0.01), A.CLAHE(p=0.01)])Spatial transforms (rotation, flips, perspective, etc.) are applied together with the bounding boxes, which are updated automatically through Albumentations' bbox handling in YOLO format. Non-spatial transforms like color adjustments only change the image. See the Albumentations integration guide for details.
anushka-kore
Thanks a lot for the inputs @deox1994 and @glenn-jocher! I have made it work👍🏻
anushka-kore
Hey @glenn-jocher and @deox1994, I later realised that simply defining my list of custom transform in the augment.py file is not working. This is the part I changed in the augment.py file (original ones are commented out)-
T = [ #A.Blur(p=0.01), #A.MedianBlur(p=0.01), #A.ToGray(p=0.01), #A.CLAHE(p=0.01), A.RandomBrightnessContrast(p=0.2), #A.RandomGamma(p=0.0), #A.ImageCompression(quality_range=(75, 100), p=0.0), A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5), A.Rotate(limit=30, p=0.5), A.GaussianBlur(p=0.2), A.GaussNoise(p=0.2), ]For your reference, this is the error I get, you could view the list of albumentation transforms I applied here as well- ..... Transferred 1009/1015 items from pretrained weights Freezing layer 'model.23.dfl.conv.weight' AMP: running Automatic Mixed Precision (AMP) checks... AMP: checks passed ✅ train: Scanning /home/xxx/dataset_MIP_clean/train/labels.cache... 831 images, 73 backgrounds, 0 corrupt: 100%|██████████| 831/831 [00:00<?, ?it/s] albumentations: RandomBrightnessContrast(p=0.2, brightness_by_max=True, brightness_limit=(-0.2, 0.2), contrast_limit=(-0.2, 0.2), ensure_safe_range=False), HorizontalFlip(p=0.5), VerticalFlip(p=0.5), Rotate(p=0.5, border_mode=0, crop_border=False, fill=0.0, fill_mask=0.0, interpolation=1, limit=(-30.0, 30.0), mask_interpolation=0, rotate_method='largest_box'), GaussianBlur(p=0.2, blur_limit=(0, 0), sigma_limit=(0.5, 3.0)), GaussNoise(p=0.2, mean_range=(0.0, 0.0), noise_scale_factor=1.0, per_channel=True, std_range=(0.2, 0.44)) val: Scanning /home/xxx/dataset_MIP_clean/val/labels.cache... 210 images, 13 backgrounds, 0 corrupt: 100%|██████████| 210/210 [00:00<?, ?it/s] Plotting labels to /home/xxx/yolov11_predictions/test4/labels.jpg... optimizer: 'optimizer=auto' found, ignoring 'lr0=0.01' and 'momentum=0.937' and determining best 'optimizer', 'lr0' and 'momentum' automatically... optimizer: AdamW(lr=0.000769, momentum=0.9) with parameter groups 167 weight(decay=0.0), 174 weight(decay=0.0005), 173 bias(decay=0.0) Image sizes 640 train, 640 val Using 8 dataloader workers Logging results to /home/xxx/yolov11_predictions/test4 Starting training for 200 epochs...
Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size 1/200 15.4G 5.502 51.38 2.745 17 640: 10%|▉ | 5/52 [00:02<00:22, 2.07it/s]Traceback (most recent call last): File "/home/xxx/yolo_train.py", line 149, in train_yolo(output_dir) File "/home/xxx/yolo_train.py", line 116, in train_yolo results = model.train( ^^^^^^^^^^^^ File "/home/xxx/env/lib/python3.12/site-packages/ultralytics/engine/model.py", line 791, in train self.trainer.train() File "/home/xxx/env/lib/python3.12/site-packages/ultralytics/engine/trainer.py", line 211, in train self._do_train(world_size) File "/home/xxx/env/lib/python3.12/site-packages/ultralytics/engine/trainer.py", line 366, in _do_train for i, batch in pbar: ^^^^ File "/home/xxx/env/lib/python3.12/site-packages/tqdm/std.py", line 1178, in iter for obj in iterable: ^^^^^^^^ File "/home/xxx/env/lib/python3.12/site-packages/ultralytics/data/build.py", line 59, in iter yield next(self.iterator) ^^^^^^^^^^^^^^^^^^^ File "/home/xxx/env/lib/python3.12/site-packages/torch/utils/data/dataloader.py", line 708, in next data = self._next_data() ^^^^^^^^^^^^^^^^^ File "/home/xxx/env/lib/python3.12/site-packages/torch/utils/data/dataloader.py", line 1455, in _next_data return self._process_data(data) ^^^^^^^^^^^^^^^^^^^^^^^^ File "/home/xxx/env/lib/python3.12/site-packages/torch/utils/data/dataloader.py", line 1505, in _process_data data.reraise() File "/home/xxx/env/lib/python3.12/site-packages/torch/_utils.py", line 733, in reraise raise exception RuntimeError: Caught RuntimeError in DataLoader worker process 5. Original Traceback (most recent call last): File "/home/xxx/env/lib/python3.12/site-packages/torch/utils/data/_utils/worker.py", line 349, in _worker_loop data = fetcher.fetch(index) # type: ignore[possibly-undefined] ^^^^^^^^^^^^^^^^^^^^ File "/home/xxx/env/lib/python3.12/site-packages/torch/utils/data/_utils/fetch.py", line 55, in fetch return self.collate_fn(data) ^^^^^^^^^^^^^^^^^^^^^ File "/home/xxx/env/lib/python3.12/site-packages/ultralytics/data/dataset.py", line 298, in collate_fn value = torch.cat(value, 0) ^^^^^^^^^^^^^^^^^^^ RuntimeError: Tensors must have same number of dimensions: got 1 and 2
All my transforms are correctly defined, and the spatial transforms (horizontalflip, verticalflip and rotate) exist in the spatial_transforms list. Could you please point where this is going wrong?
supriamir
Hi Glen,
I would like to optimize the hyperparameters using model.tune(). My goal is to identify the most important augmentations from Albumentations.
If I am not mistaken, the default hyperparameter optimization only includes a limited set of augmentation parameters, as described in the following link: https://docs.ultralytics.com/integrations/ray-tune/#tune-method-parameters
Could you advise how I can include and optimize additional Albumentations transforms beyond the default settings?
Glenn JocherUltralyticsYes, but not directly through the default
model.tune()search set: custom Albumentations are a Python-onlyaugmentationslist passed tomodel.train(), while the built-in tuner mutates the numericspace, so the usual workflow is to keep one fixedaugmentations=pipeline per tuning run and compare the best result across several candidate pipelines; if you want to search the pipeline itself, use a small custom Ray Tune wrapper aroundmodel.train()instead, and keep the standard YOLO augmentations fixed so you isolate the Albumentations effect—see the hyperparameter tuning guide and the Albumentations integration guide.
UltralyticsAssistantUltralytics
👋 Hello, thank you for your interest in Ultralytics 🚀! We recommend visiting the Docs for guidance—there you’ll find many Python and CLI usage examples, and answers to many common questions.
If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us investigate.
If you have a custom training ❓ Question, please share as much relevant information as possible, including dataset image examples and training logs. Also, make sure to review our Tips for Best Training Results.
You’re welcome to join the Ultralytics community where it fits you best:
- For real-time chat, join us on Discord 🎧
- For in-depth discussions, visit Discourse
- For community sharing, check out our Subreddit
Upgrade
Upgrade to the latest
ultralyticspackage and all requirements in a Python>=3.8 environment with PyTorch>=1.8 to ensure you’re on the latest version:pip install -U ultralyticsEnvironments
YOLO can be run in any of the following up-to-date verified environments (with all dependencies like CUDA/CUDNN, Python, and PyTorch preinstalled):
- Notebooks with free GPU:
- Google Cloud Deep Learning VM. See GCP Quickstart Guide
- Amazon Deep Learning AMI. See AWS Quickstart Guide
- Docker Image. See Docker Quickstart Guide
Status
If this badge is green, all Ultralytics CI tests are currently passing. These tests confirm correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.
This is an automated response 🤖. An Ultralytics engineer will assist you here soon!
Glenn JocherUltralytics欢迎来到 Ultralytics 中文文档的 Albumentations 集成讨论区!如果您对使用 Albumentations 来增强 YOLO11 训练数据有任何问题或想法,请在这里提出。
Albumentations 与 YOLO11 的集成非常简便,只需安装
albumentations包,就会在训练过程中自动应用多种图像增强技术,如模糊、中值模糊、灰度转换和 CLAHE,帮助您的模型更好地适应各种真实场景。您是否在特定项目中使用过 Albumentations?或者您对如何最佳配置这些增强技术有疑问?请随时在这里分享您的经验或提出问题,Ultralytics 团队将很乐意提供帮助!
UltralyticsAssistantUltralytics
👋 Hello, thank you for your interest in Ultralytics 🚀! We recommend visiting the Docs for guidance on integrations like Albumentations with YOLO11. You can also review many Python and CLI examples, and frequently asked questions may already be addressed there.
If this is a 🐛 Bug Report, please include a minimum reproducible example to help us investigate further.
If you have a custom training ❓ Question, please provide detailed info such as dataset image samples, training logs, and confirm you are following our Tips for Best Training Results.
Join the Ultralytics community wherever you prefer—real-time chat on Discord 🎧, in-depth discussions on Discourse, or knowledge-sharing on our Subreddit.
Upgrade
Upgrade to the latest
ultralyticspackage and all requirements in a Python>=3.8 environment with PyTorch>=1.8 to ensure your issue is not already fixed in the latest version:pip install -U ultralyticsEnvironments
YOLO may be run in any of the following verified and up-to-date environments (with all dependencies including CUDA/CUDNN, Python and PyTorch preinstalled):
- Notebooks with free GPU:
- Google Cloud Deep Learning VM. See GCP Quickstart Guide
- Amazon Deep Learning AMI. See AWS Quickstart Guide
- Docker Image. See Docker Quickstart Guide
Status
If this badge is green, all Ultralytics CI tests are currently passing. These tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.
This is an automated response. An Ultralytics engineer will review and assist you soon!
Glenn JocherUltralyticsBonjour! N'hésitez pas à poser vos questions sur l'intégration d'Albumentations avec YOLO11 dans cette discussion. Cette intégration vous permet d'améliorer automatiquement votre jeu de données pendant l'entraînement avec diverses transformations comme le flou, le flou médian, la conversion en niveaux de gris et CLAHE.
L'avantage principal est sa simplicité d'utilisation - il suffit d'installer les packages requis et les augmentations sont appliquées automatiquement pendant l'entraînement:
pip install albumentations ultralyticsSi vous rencontrez des difficultés avec cette intégration ou si vous avez des questions sur l'augmentation de données pour améliorer les performances de vos modèles YOLO11, n'hésitez pas à les partager ici!
- Notebooks with free GPU:
manuelescobar5036(edited)
Dear Ultralytics team,
I’m working on a project focused on detecting the behavior of workers in underground mines. The classes and the number of labels per class in the training set are as follows:
- Sitting → 2500
- Standing → 9000
- Operation → 700
- Lean Against → 4000
- Tumble → 400
Since the dataset is imbalanced, I would like to apply data augmentation to avoid overfitting and improve accuracy. While researching YOLO's data augmentation capabilities, a few questions came up:
- As far as I understand, YOLO currently supports two methods for performing data augmentation:
- Modifying individual hyperparameters such as hsv_h, hsv_s, hsv_v, degrees, translate, etc., in the ultralytics/cfg/default.yaml file (does not require the Albumentations Python Library).
- Using the Albumentations Python Library (previously installed).
Is this correct? If so, what are the differences between the two methods, and which one is currently recommended?
-
Considering both options from question 1, does YOLO apply data augmentation only to images from the classes with less labels, or to images from all classes? I ask because if I have an imbalanced dataset and YOLO applies data augmentation to images from all classes, the imbalance would remain, wouldn’t it?
-
If I choose to use an older YOLO model, such as yolov8n.yaml, and I have Albumentations installed, will Albumentations-based data augmentation be applied during training?
-
What other suggestions would you recommend for dealing with imbalanced classes?
safwene-bahroun
Hello @glenn-jocher , Do you can , please , answer to these questions , because the same questions and problem.
THANKS
Glenn JocherUltralytics@deox1994 Thanks for your detailed questions about data augmentation in YOLO for handling your imbalanced mining worker dataset. Let me address each point:
- Yes, you're correct about the two augmentation approaches:
- Built-in YOLO augmentations (hsv_h, translate, scale, etc.) which are always available
- Albumentations integration which activates automatically when the library is installed
The key difference is that built-in augmentations focus primarily on geometric and color transformations, while Albumentations adds more specialized transformations like blur, grayscale, and CLAHE with carefully tuned probabilities (typically 0.01 as shown in the reference code). Both work together complementarily rather than being exclusive options.
-
Both augmentation methods apply to all images regardless of class. To address your imbalance specifically, consider:
- Using a weighted loss function
- Implementing class-aware sampling during training
- Creating custom data pipeline that applies additional augmentations to underrepresented classes
-
Yes, if Albumentations is installed, it will be automatically applied when training YOLOv8 models too. The integration is part of the Ultralytics framework, not specific to YOLO11.
-
For handling imbalanced classes beyond augmentation:
- Apply weighted loss based on inverse class frequency
- Use focal loss which naturally handles class imbalance better
- Consider different evaluation metrics (precision/recall per class rather than just mAP)
- Experiment with undersampling majority classes or oversampling minority classes
You can find implementation details for these approaches in the data augment reference documentation.
- Yes, you're correct about the two augmentation approaches:
safwene-bahroun
Good morning ,@glenn-jocher, do you can help me ?
{ "total_images": 39152, "total_detections": 70910, "instances_per_class": { "Dress": 52999, "Skirt": 1259, "Handbag": 2495, "High heels": 3124, "Swimwear": 10079, "Miniskirt": 954 } } i will train this with yolo11n.pt and with albumentation the code : from ultralytics import YOLO import torch
def main(): # Load a pretrained YOLO model model = YOLO("yolo11n.pt") # Set device device = "cuda" if torch.cuda.is_available() else "cpu" print(f"Using device: {device}")
if device == "cuda": print(f"GPU name: {torch.cuda.get_device_name(0)}") # Debug: Print dataset configuration print("Training with dataset: OpenImagesV7-women.yaml") # Train the model with enhanced hyperparameters results = model.train( data="OpenImagesV7-woman.yaml", epochs=150, imgsz=640, device=device, batch=16, optimizer ="auto")
Dataset configuration
path: ../datasets/open-images-v7 train: c:\Users\GIGABYTE\datasets\open-images-v7\train val: C:/Users/GIGABYTE/datasets/open-images-v7/val
nc: 6 names: 0: Dress 1: High heels 2: Miniskirt 3: Skirt 4: Swimwear 5: Handbag
Hyperparameters for extreme imbalance
loss: cls_weight: [0.3, 0.5, 7.0, 5.0, 0.4, 0.6] # Calculated weights below box: 0.05 obj: 1.0 label_smoothing: 0.1
Strategic augmentation
augment:
For rare classes (Miniskirt, Skirt)
copy_paste: 0.7 # High frequency for rare classes paste_classes: [2, 3] # Only Miniskirt(class2)/Skirt(class3) paste_scale: [0.3, 0.7] # Realistic resizing of pasted objects
General augmentations (applied to all)
mosaic: 1.0 # Helps context learning mixup: 0.05 # Reduced to avoid label confusion fliplr: 0.5 hsv_h: 0.015 # Mild color variation degrees: 5.0 # Small rotation for fashion items
Training parameters
batch: 16 # Match GPU capacity accumulate: 4 # Simulates batch=64 epochs: 150 # Longer training for rare classes patience: 50 # Early stopping if no improveme
but i trained untill now :
Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size 104/150 2.92G 1.026 0.9478 1.206 55 640: 100%|██████████| 2447/2447 [07:51<00:00, Class Images Instances Box(P R mAP50 mAP50-95): 100%|██████████| 32/32 [00:06 all 1016 1987 0.581 0.525 0.536 0.423Can you help me please to reach all metrics above 0.8
THANKS
hillsonghimire
Even when I turned off augment=False, albumentation-related operations were still performed in yolo11. How to completely turn it off/disable?
Glenn JocherUltralytics@hillsonghimire to completely disable Albumentations augmentations in YOLO11, uninstall the Albumentations package since its presence automatically enables the integration. Run
pip uninstall albumentationsand verify it's removed from your environment. This will prevent any Albumentations transformations from being applied regardless of other settings. For more details, see the Albumentations integration guide.
DP1701
Thanks for this explanation. But if I understand correctly, not all functions of Albuminations are directly supported, or am I misunderstanding?
The explanation says: The integration includes optimized augmentations like blur, median blur, grayscale conversion, and CLAHE with carefully tuned probabilities to enhance model performance.
So only blur, median blur, grayscale conversion and CLAHE are applied and the others cannot be individually selected and adjusted?
Glenn JocherUltralytics(edited)The integration with Albumentations in YOLO11 automatically applies specific augmentations like blur, median blur, grayscale conversion, and CLAHE. While these are the default transformations used to enhance model performance, you can pass your own Albumentations transforms to
model.train()with theaugmentationsargument (Python only).