Bắt đầu

Cải thiện Dataset của Bạn để Huấn luyện YOLO26 bằng Albumentations

Khi xây dựng model thị giác máy tính, chất lượng và tính đa dạng của dữ liệu huấn luyện có thể ảnh hưởng lớn đến hiệu năng của model. Albumentations cung cấp cách nhanh, linh hoạt và hiệu quả để áp dụng nhiều phép biến đổi ảnh, giúp cải thiện khả năng thích ứng với các tình huống thực tế của model. Albumentations tích hợp với Ultralytics YOLO26 và có thể giúp bạn tạo dataset bền vững cho các tác vụ phát hiện đối tượng, phân đoạn instance, phân đoạn ngữ nghĩa, ước lượng độ sâu, ước lượng pose và bounding box định hướng.

Albumentations bổ sung các kỹ thuật như biến đổi hình học và điều chỉnh màu sắc vào dữ liệu huấn luyện YOLO26. Hướng dẫn này giải thích cách Albumentations được tích hợp vào pipeline tăng cường dữ liệu của Ultralytics và cách tùy chỉnh pipeline cho dự án của bạn.

Albumentations để tăng cường ảnh#

Albumentations là thư viện tăng cường dữ liệu ảnh mã nguồn mở, được tạo vào tháng 6 năm 2018. Thư viện được thiết kế để đơn giản hóa và tăng tốc quá trình tăng cường dữ liệu ảnh trong thị giác máy tính. Được xây dựng chú trọng hiệu năng và tính linh hoạt, thư viện hỗ trợ nhiều kỹ thuật tăng cường đa dạng, từ các phép biến đổi đơn giản như xoay và lật đến các điều chỉnh phức tạp hơn như thay đổi độ sáng và độ tương phản. Albumentations giúp developer tạo dataset phong phú, đa dạng cho các tác vụ như phân loại ảnh, phát hiện đối tượng và phân đoạn.

Bạn có thể dễ dàng dùng Albumentations để áp dụng phép tăng cường cho ảnh, mask phân đoạn, bounding box và keypoint, đồng thời đảm bảo tất cả thành phần trong dataset được biến đổi đồng bộ. Albumentations hoạt động với các framework deep learning phổ biến như PyTorch và TensorFlow, phù hợp với nhiều dự án.

Albumentations phù hợp với cả dataset nhỏ và các tác vụ thị giác máy tính quy mô lớn. Quá trình xử lý nhanh giúp giảm thời gian chuẩn bị dữ liệu, đồng thời dữ liệu huấn luyện đa dạng hơn có thể cải thiện hiệu năng model trong các ứng dụng thực tế.

Các tính năng chính của Albumentations#

Albumentations cung cấp nhiều tính năng hữu ích giúp đơn giản hóa các phép tăng cường ảnh phức tạp cho nhiều ứng dụng computer vision. Dưới đây là một số tính năng chính:

  • Nhiều loại phép biến đổi: Albumentations cung cấp hơn 70 phép biến đổi khác nhau, bao gồm thay đổi hình học (ví dụ: xoay, lật), điều chỉnh màu sắc (ví dụ: độ sáng, độ tương phản) và thêm nhiễu (ví dụ: nhiễu Gaussian). Nhiều tùy chọn cho phép tạo dataset huấn luyện đa dạng và mạnh mẽ.

Albumentations augmentation examples

  • Tối ưu hiệu năng cao: Được xây dựng trên OpenCV và NumPy, Albumentations sử dụng các kỹ thuật tối ưu nâng cao như SIMD (Một lệnh, nhiều dữ liệu), xử lý đồng thời nhiều điểm dữ liệu để tăng tốc quá trình xử lý. Thư viện xử lý nhanh các dataset lớn, trở thành một trong những lựa chọn tăng cường ảnh nhanh nhất hiện có.

  • Ba cấp độ tăng cường dữ liệu: Albumentations hỗ trợ ba cấp độ tăng cường: biến đổi cấp pixel, biến đổi cấp không gian và biến đổi cấp trộn. Biến đổi cấp pixel chỉ ảnh hưởng đến ảnh đầu vào mà không thay đổi mask, bounding box hoặc keypoint. Biến đổi cấp không gian thay đổi cả ảnh lẫn các thành phần của ảnh, chẳng hạn như mask và bounding box. Biến đổi cấp trộn kết hợp nhiều ảnh thành một ảnh.

Ví dụ tăng cường dữ liệu cấp pixel, cấp không gian và cấp trộn của Albumentations

  • Kết quả benchmark: Các benchmark được Albumentations công bố cho thấy tốc độ của thư viện có lợi thế so với các thư viện tăng cường dữ liệu khác, đặc biệt trên dataset lớn.

Vì sao nên dùng Albumentations cho các dự án Vision AI?#

Trong lĩnh vực tăng cường ảnh, Albumentations nổi bật là công cụ đáng tin cậy cho các tác vụ computer vision. Dưới đây là một số lý do chính để cân nhắc sử dụng thư viện cho các dự án Vision AI:

  • API dễ sử dụng: Albumentations cung cấp một API đơn giản, nhất quán để áp dụng nhiều phép tăng cường lên ảnh, mask, bounding box và keypoint. API được thiết kế để dễ dàng thích ứng với các dataset khác nhau, giúp chuẩn bị dữ liệu đơn giản và hiệu quả hơn.

  • Kiểm thử lỗi nghiêm ngặt: Lỗi trong pipeline tăng cường có thể âm thầm làm sai lệch dữ liệu đầu vào, thường không được phát hiện nhưng cuối cùng làm giảm hiệu suất model. Albumentations giải quyết vấn đề này bằng bộ kiểm thử toàn diện, giúp phát hiện lỗi sớm trong quá trình phát triển.

  • Khả năng mở rộng: Albumentations giúp dễ dàng thêm phép tăng cường mới và sử dụng cùng các phép biến đổi tích hợp thông qua một interface duy nhất.

Cách dùng Albumentations để tăng cường dữ liệu khi huấn luyện YOLO26#

Albumentations tích hợp trực tiếp vào chế độ huấn luyện của Ultralytics và tự động áp dụng khi package Albumentations được cài đặt.

Cài đặt#

Để sử dụng Albumentations với YOLO26, trước tiên hãy đảm bảo bạn đã cài đặt các package cần thiết. Nếu chưa cài Albumentations, các phép tăng cường của thư viện sẽ không được áp dụng trong quá trình huấn luyện. Sau khi cài đặt, các phép biến đổi sẽ được áp dụng trực tiếp lên ảnh huấn luyện.

Cài đặt
# Install the required packages
pip install albumentations ultralytics

Để biết hướng dẫn chi tiết và các phương pháp tốt nhất về quy trình cài đặt, hãy xem hướng dẫn cài đặt Ultralytics. Nếu gặp khó khăn khi cài đặt các package cần thiết cho YOLO26, hãy tham khảo hướng dẫn khắc phục sự cố thường gặp để tìm giải pháp và mẹo hữu ích.

Các ví dụ về phép biến đổi tùy chỉnh trên trang này cần Albumentations 1.4.22 trở lên, do đó cũng cần Python 3.9 trở lên.

Cách sử dụng#

Sau khi cài đặt các package cần thiết, bạn đã sẵn sàng sử dụng Albumentations với YOLO26. Khi huấn luyện YOLO26 trong lúc Albumentations đã được cài đặt, một bộ phép biến đổi Albumentations mặc định sẽ tự động được áp dụng.

Cách sử dụng
from ultralytics import YOLO

# Tải model pretrained
model = YOLO("yolo26n.pt")

# # Huấn luyện model với các phép tăng cường mặc định
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)

Các phần sau mô tả những phép biến đổi Albumentations mặc định được áp dụng trong quá trình huấn luyện.

Làm mờ#

Phép biến đổi Blur trong Albumentations tạo hiệu ứng làm mờ đơn giản cho ảnh bằng cách lấy trung bình giá trị pixel trong một vùng hình vuông nhỏ, hay kernel. Phép biến đổi sử dụng hàm OpenCV cv2.blur, giúp giảm nhiễu trong ảnh nhưng cũng làm giảm nhẹ chi tiết ảnh.

Dưới đây là các tham số và giá trị được sử dụng trong tích hợp này:

  • blur_limit: Tham số này kiểm soát phạm vi kích thước của hiệu ứng làm mờ. Phạm vi mặc định là (3, 7), nghĩa là kích thước kernel làm mờ có thể thay đổi từ 3 đến 7 pixel; chỉ cho phép số lẻ để giữ hiệu ứng làm mờ ở vị trí trung tâm.

  • p: Xác suất áp dụng hiệu ứng làm mờ. Trong tích hợp này, p=0.01, tức là có 1% khả năng phép làm mờ được áp dụng cho mỗi ảnh. Xác suất thấp giúp thỉnh thoảng tạo hiệu ứng làm mờ, bổ sung một chút biến thiên để model khái quát hóa tốt hơn mà không làm ảnh bị mờ quá mức.

Albumentations Blur augmentation result

Làm mờ trung vị#

Phép biến đổi MedianBlur trong Albumentations áp dụng hiệu ứng làm mờ trung vị lên ảnh, đặc biệt hữu ích để giảm nhiễu mà vẫn bảo toàn các cạnh. Khác với các phương pháp làm mờ thông thường, MedianBlur sử dụng bộ lọc trung vị, đặc biệt hiệu quả trong việc loại bỏ nhiễu muối tiêu đồng thời giữ cho các cạnh sắc nét.

Dưới đây là các tham số và giá trị được sử dụng trong tích hợp này:

  • blur_limit: Tham số này kiểm soát kích thước tối đa của kernel làm mờ. Trong tích hợp này, giá trị mặc định là phạm vi (3, 7), nghĩa là kích thước kernel làm mờ được chọn ngẫu nhiên từ 3 đến 7 pixel; chỉ cho phép giá trị lẻ để đảm bảo căn chỉnh chính xác.

  • p: Thiết lập xác suất áp dụng hiệu ứng làm mờ trung vị. Ở đây, p=0.01, tức là phép biến đổi có 1% khả năng được áp dụng cho mỗi ảnh. Xác suất thấp này đảm bảo hiệu ứng chỉ được dùng thưa thớt, giúp model khái quát hóa bằng cách thỉnh thoảng xử lý ảnh đã giảm nhiễu nhưng vẫn giữ được các cạnh.

Ảnh bên dưới minh họa ví dụ áp dụng phép tăng cường này.

Albumentations MedianBlur augmentation

Ảnh xám#

Phép biến đổi ToGray trong Albumentations chuyển ảnh sang thang xám, giảm ảnh xuống định dạng một kênh và tùy chọn nhân bản kênh này để khớp với số kênh đầu ra được chỉ định. Có thể sử dụng các phương pháp khác nhau để điều chỉnh cách tính độ sáng ảnh xám, từ lấy trung bình đơn giản đến các kỹ thuật nâng cao hơn nhằm mô phỏng chân thực cảm nhận về độ tương phản và độ sáng.

Dưới đây là các tham số và giá trị được sử dụng trong tích hợp này:

  • num_output_channels: Thiết lập số kênh trong ảnh đầu ra. Nếu giá trị này lớn hơn 1, kênh ảnh xám duy nhất sẽ được nhân bản để tạo ảnh xám nhiều kênh. Mặc định, giá trị này là 3, tạo ảnh xám có ba kênh giống hệt nhau.

  • method: Xác định phương pháp chuyển đổi ảnh xám. Phương pháp mặc định, "weighted_average", áp dụng công thức (0.299R + 0.587G + 0.114B), gần với cảm nhận của con người và tạo hiệu ứng ảnh xám tự nhiên. Các tùy chọn khác như "from_lab", "desaturation", "average", "max" và "pca" cung cấp những cách thay thế để tạo ảnh xám, tùy theo nhu cầu về tốc độ, mức độ nhấn mạnh độ sáng hoặc khả năng bảo toàn chi tiết.

  • p: Kiểm soát tần suất áp dụng phép biến đổi ảnh xám. Với p=0.01, mỗi ảnh có 1% khả năng được chuyển sang thang xám, giúp tạo ra tập ảnh kết hợp cả ảnh màu và ảnh xám để model khái quát hóa tốt hơn.

Ảnh bên dưới minh họa ví dụ áp dụng phép biến đổi ảnh xám này.

Albumentations grayscale conversion

Cân bằng histogram thích ứng giới hạn tương phản (CLAHE)#

Phép biến đổi CLAHE trong Albumentations áp dụng cân bằng histogram thích ứng giới hạn tương phản (CLAHE), một kỹ thuật tăng cường độ tương phản ảnh bằng cách cân bằng histogram trong các vùng cục bộ (tile) thay vì trên toàn bộ ảnh. CLAHE tạo hiệu ứng tăng cường cân bằng, tránh khuếch đại độ tương phản quá mức như phương pháp cân bằng histogram tiêu chuẩn, đặc biệt ở những vùng ban đầu có độ tương phản thấp.

Dưới đây là các tham số và giá trị được sử dụng trong tích hợp này:

  • clip_limit: Kiểm soát phạm vi tăng cường độ tương phản. Giá trị mặc định là khoảng (1, 4), xác định mức tương phản tối đa cho phép trong mỗi ô. Giá trị cao hơn cho phép độ tương phản lớn hơn nhưng cũng có thể tạo thêm nhiễu.

  • tile_grid_size: Xác định kích thước lưới ô, thường được biểu diễn dưới dạng (hàng, cột). Giá trị mặc định là (8, 8), nghĩa là ảnh được chia thành lưới 8x8. Ô nhỏ hơn cho phép điều chỉnh cục bộ hơn, trong khi ô lớn hơn tạo hiệu ứng gần với cân bằng toàn cục.

  • p: Xác suất áp dụng CLAHE. Ở đây, p=0.01 chỉ tạo hiệu ứng tăng cường với xác suất 1%, đảm bảo điều chỉnh độ tương phản được áp dụng thưa thớt để thỉnh thoảng tạo biến thiên cho ảnh huấn luyện.

Ảnh bên dưới minh họa ví dụ áp dụng phép biến đổi CLAHE.

Albumentations CLAHE contrast enhancement

Sử dụng các transform Albumentations tùy chỉnh#

Mặc dù tích hợp Albumentations mặc định cung cấp một bộ phép tăng cường hữu ích, bạn có thể muốn tùy chỉnh phép biến đổi cho trường hợp sử dụng cụ thể. Với Ultralytics YOLO26, bạn có thể truyền phép biến đổi Albumentations tùy chỉnh qua Python API bằng tham số augmentations. Các ví dụ trong phần này yêu cầu Albumentations phiên bản 1.4.22 trở lên.

Cách định nghĩa các transform tùy chỉnh#

Bạn có thể định nghĩa danh sách transform Albumentations của riêng mình và truyền chúng vào hàm training. Thao tác này thay thế các transform Albumentations mặc định trong khi vẫn giữ các phép tăng cường dữ liệu YOLO khác (như hsv_h, degrees, mosaic, v.v.) hoạt động.

Dưới đây là ví dụ sử dụng các transform nâng cao hơn:

import albumentations as A

from ultralytics import YOLO

# Tải model
model = YOLO("yolo26n.pt")

# Định nghĩa các transform tùy chỉnh với nhiều kỹ thuật tăng cường dữ liệu
custom_transforms = [
    # Các biến thể làm mờ
    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,
    ),
    # Các biến thể nhiễu
    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,
    ),
    # Điều chỉnh màu sắc và độ tương phản
    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),
    # Mô phỏng hiện tượng che khuất
    A.CoarseDropout(num_holes_range=(1, 8), hole_height_range=(8, 32), hole_width_range=(8, 32), fill=0, p=0.2),
]

# Training với các transform tùy chỉnh
results = model.train(
    data="coco8.yaml",
    epochs=100,
    imgsz=640,
    augmentations=custom_transforms,
)

Các điểm cần lưu ý#

Khi sử dụng các transform Albumentations tùy chỉnh, hãy lưu ý những điểm sau:

  • Cấu hình: Tạo các đối tượng transform tùy chỉnh thông qua Python API. Bạn cũng có thể truyền các transform đã tuần tự hóa thông qua CLI hoặc tệp cấu hình YAML, kể cả khi tiếp tục training.
  • Thay thế mặc định: Các transform tùy chỉnh của bạn sẽ thay thế hoàn toàn các transform Albumentations mặc định. Các phép tăng cường dữ liệu YOLO khác vẫn hoạt động.
  • Xử lý nhãn: Các transform không gian, bao gồm những transform được lồng trong A.OneOf hoặc A.Compose, sẽ dịch chuyển bounding box, polygon, keypoint và mask độ sâu hoặc ngữ nghĩa cùng với ảnh. A.RandomGridShuffle không thể giữ nguyên cấu trúc liên kết của polygon hoặc keypoint và sẽ báo lỗi với các mẫu segmentation, pose và OBB.
  • Hiệu năng: Một số transform tiêu tốn nhiều tài nguyên tính toán. Hãy theo dõi tốc độ training và điều chỉnh cho phù hợp.
  • Khả năng tương thích với tác vụ: Các transform Albumentations tùy chỉnh hoạt động với tác vụ detection, segmentation, segmentation ngữ nghĩa, độ sâu, pose và training OBB, nhưng không hoạt động với classification (vốn sử dụng pipeline tăng cường dữ liệu khác).

Các trường hợp sử dụng transform tùy chỉnh#

Các ứng dụng khác nhau sẽ hưởng lợi từ những chiến lược tăng cường dữ liệu khác nhau:

  • Ảnh y tế: Sử dụng biến dạng đàn hồi, biến dạng lưới và các dạng nhiễu chuyên biệt
  • Ảnh hàng không/vệ tinh: Áp dụng các transform mô phỏng độ cao, điều kiện thời tiết và góc chiếu sáng khác nhau
  • Điều kiện thiếu sáng: Tăng cường thêm nhiễu và điều chỉnh độ sáng để training các model vững chắc trong điều kiện chiếu sáng khó khăn
  • Kiểm tra công nghiệp: Bổ sung các biến thể kết cấu và khuyết tật mô phỏng cho các ứng dụng kiểm soát chất lượng

Để xem danh sách đầy đủ các transform hiện có và tham số của chúng, hãy truy cập tài liệu Albumentations.

Để xem các ví dụ chi tiết hơn và các phương pháp thực hành tốt nhất khi dùng transform Albumentations tùy chỉnh với YOLO26, hãy tham khảo hướng dẫn tăng cường dữ liệu YOLO.

Tìm hiểu thêm về Albumentations#

Nếu muốn tìm hiểu thêm về Albumentations, hãy xem các tài nguyên sau để tham khảo hướng dẫn và ví dụ chuyên sâu hơn:

Điểm chính cần lưu ý#

Trong hướng dẫn này, chúng ta đã tìm hiểu các khía cạnh chính của Albumentations, thư viện Python dùng để tăng cường dữ liệu ảnh. Chúng ta đã đề cập đến nhiều phép biến đổi, hiệu năng được tối ưu hóa và cách bạn có thể sử dụng thư viện trong dự án YOLO26 tiếp theo.

Câu hỏi thường gặp#

  • Albumentations tích hợp với YOLO26 và tự động áp dụng trong quá trình huấn luyện nếu bạn đã cài đặt package. Sau đây là cách bắt đầu:

    # Cài đặt các package cần thiết
    # !pip install albumentations ultralytics
    from ultralytics import YOLO
    
    # Tải và training model với các phép tăng cường dữ liệu tự động
    model = YOLO("yolo26n.pt")
    model.train(data="coco8.yaml", epochs=100)

    Tích hợp mặc định áp dụng blur, median blur, chuyển ảnh sang grayscale và CLAHE, mỗi phép có xác suất thấp 1% để thỉnh thoảng tạo thêm biến thể mà không chi phối quá trình huấn luyện.

  • Albumentations nổi bật nhờ một số lý do:

    1. Hiệu năng: Được xây dựng trên OpenCV và NumPy, tối ưu hóa SIMD để đạt tốc độ cao
    2. Tính linh hoạt: Hỗ trợ hơn 70 phép biến đổi ở cấp độ pixel, không gian và trộn dữ liệu
    3. Khả năng tương thích: Hoạt động với các framework phổ biến như PyTorch và TensorFlow
    4. Độ tin cậy: Bộ kiểm thử toàn diện giúp ngăn ngừa lỗi hỏng dữ liệu không được phát hiện
    5. Dễ sử dụng: Một API thống nhất cho mọi loại phép tăng cường dữ liệu
  • Albumentations cải thiện nhiều tác vụ computer vision, bao gồm:

    • Object Detection: Tăng độ vững chắc của model trước các biến thiên về ánh sáng, tỷ lệ và hướng
    • Instance Segmentation: Nâng cao độ chính xác dự đoán mask thông qua các phép biến đổi đa dạng
    • Pose Estimation: Giúp model thích ứng với các góc nhìn và điều kiện chiếu sáng khác nhau
    • Phát hiện Oriented Bounding Box: Bổ sung biến thể màu sắc và nhiễu cho ảnh hàng không và ảnh vật thể xoay

    Các tùy chọn tăng cường dữ liệu đa dạng của thư viện này rất hữu ích cho những tác vụ thị giác cần hiệu năng model vững chắc. Trong Ultralytics YOLO26, training classification sử dụng pipeline tăng cường dữ liệu riêng dựa trên torchvision và không áp dụng các transform Albumentations.

Bình luận19

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. anushka-koreGitHub

    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?

    1. manuelescobar5036GitHub

      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. image

      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. image

      Bouding boxes are changed accordingly to their spatial transforms. This is done when you pass bbox_params to the Albumentations pipeline. image

    2. Glenn JocherUltralytics(đã chỉnh sửa)

      @anushka-kore Yes. Pass your own Albumentations transforms to training with the augmentations argument (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.

    3. anushka-koreGitHub

      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?

    4. supriamirGitHub

      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?

    5. Glenn JocherUltralytics

      Yes, but not directly through the default model.tune() search set: custom Albumentations are a Python-only augmentations list passed to model.train(), while the built-in tuner mutates the numeric space, so the usual workflow is to keep one fixed augmentations= 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 around model.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.

  2. UltralyticsAssistantGitHubUltralytics

    👋 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 ultralytics package and all requirements in a Python>=3.8 environment with PyTorch>=1.8 to ensure you’re on the latest version:

    pip install -U ultralytics

    Environments

    YOLO can be run in any of the following up-to-date verified environments (with all dependencies like CUDA/CUDNN, Python, and PyTorch preinstalled):

    Status

    Ultralytics CI

    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!

    1. Glenn JocherUltralytics

      欢迎来到 Ultralytics 中文文档的 Albumentations 集成讨论区!如果您对使用 Albumentations 来增强 YOLO11 训练数据有任何问题或想法,请在这里提出。

      Albumentations 与 YOLO11 的集成非常简便,只需安装 albumentations 包,就会在训练过程中自动应用多种图像增强技术,如模糊、中值模糊、灰度转换和 CLAHE,帮助您的模型更好地适应各种真实场景。

      您是否在特定项目中使用过 Albumentations?或者您对如何最佳配置这些增强技术有疑问?请随时在这里分享您的经验或提出问题,Ultralytics 团队将很乐意提供帮助!

  3. UltralyticsAssistantGitHubUltralytics

    👋 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 ultralytics package 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 ultralytics

    Environments

    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):

    Status

    Ultralytics CI

    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!

    1. Glenn JocherUltralytics

      Bonjour! 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 ultralytics

      Si 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!

  4. manuelescobar5036GitHub(đã chỉnh sửa)

    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:

    1. 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?

    1. 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?

    2. 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?

    3. What other suggestions would you recommend for dealing with imbalanced classes?

    1. 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:

      1. 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.

      1. 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
      2. 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.

      3. 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.

    2. safwene-bahrounGitHub

      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.423

      Can you help me please to reach all metrics above 0.8

      THANKS

  5. hillsonghimireGitHub

    Even when I turned off augment=False, albumentation-related operations were still performed in yolo11. How to completely turn it off/disable?

    1. Glenn JocherUltralytics

      @hillsonghimire to completely disable Albumentations augmentations in YOLO11, uninstall the Albumentations package since its presence automatically enables the integration. Run pip uninstall albumentations and 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.

  6. DP1701GitHub

    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?

    1. Glenn JocherUltralytics(đã chỉnh sửa)

      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 the augmentations argument (Python only).