Bắt đầu

Hướng dẫn tinh chỉnh hyperparameter cho Ultralytics YOLO

Tinh chỉnh hyperparameter trong Ultralytics YOLO là quy trình tìm kiếm tự động, lặp đi lặp lại nhằm tối ưu các thiết lập — chẳng hạn learning rate, trọng số loss và cường độ augmentation — để tối đa hóa các metric hiệu suất của model machine learning, như accuracy, precision và recall. Thay vì kiểm tra thủ công các giá trị này, Ultralytics YOLO khám phá không gian hyperparameter bằng thuật toán di truyền, đột biến và đánh giá các cấu hình tiềm năng qua nhiều lượt huấn luyện ngắn.



Xem: Cách tinh chỉnh hyperparameter để cải thiện hiệu suất model 🚀

Siêu tham số là gì?#

Siêu tham số là các thiết lập cấu trúc ở cấp cao cho thuật toán. Chúng được thiết lập trước giai đoạn huấn luyện và giữ nguyên trong suốt giai đoạn đó. Sau đây là một số siêu tham số thường được tinh chỉnh trong Ultralytics YOLO:

  • Learning Rate lr0: Xác định độ lớn bước đi ở mỗi vòng lặp khi tiến tới cực tiểu của hàm loss.
  • Batch Size batch: Số lượng ảnh được xử lý đồng thời trong một lượt lan truyền tiến.
  • Số lượng Epoch epochs: Một epoch là một lượt lan truyền tiến và lan truyền ngược hoàn chỉnh qua toàn bộ mẫu huấn luyện.
  • Thông số kiến trúc: Chẳng hạn như số lượng channel, số lớp, loại hàm kích hoạt, v.v. Các thông số này nằm trong cấu hình YAML của model, thay vì trong các đối số huấn luyện.

Trong bốn yếu tố này, chỉ learning rate nằm trong không gian tìm kiếm mặc định: batch, epochs và kiến trúc được giữ nguyên. Tuner cũng đột biến lịch trình, hệ số loss và các augmentation được liệt kê bên dưới.

Hyperparameter optimization search space visualization

Tiến hóa di truyền và đột biến#

Ultralytics YOLO sử dụng thuật toán di truyền, một nhóm thuật toán tiến hóa, để tối ưu hyperparameter. Thuật toán di truyền lấy cảm hứng từ cơ chế chọn lọc tự nhiên và di truyền học.

  • Chọn lọc: Mỗi vòng lặp chọn một trong tối đa chín cấu hình có độ thích nghi cao nhất, với xác suất được cân theo độ thích nghi. Sau 30 kết quả, 20% kết quả tốt nhất (tối đa 30) cũng được dùng để ước lượng hiệp phương sai của tham số; ảnh hưởng của ước lượng này tăng dần khi tích lũy thêm bằng chứng từ các cấu hình ưu tú.
  • Đột biến: Mỗi vòng lặp đột biến khoảng một nửa số tham số bằng các bước Gaussian được chuẩn hóa theo phạm vi tìm kiếm. Khi hiệp phương sai được kích hoạt, một tỷ lệ có trọng số theo độ tin cậy, tối đa 40%, sử dụng các bước tương quan; phép phản xạ đưa các bước này về trong giới hạn mà không tích lũy các giá trị bị cắt ngưỡng. Khi số lượt thử tăng mà không có cải thiện, kích thước bước thu hẹp tuyến tính tối đa 20% trong 25 lượt thử và được đặt lại khi tìm thấy kết quả tốt nhất mới. Vòng lặp 1 không có cấu hình cha và sử dụng các siêu tham số huấn luyện mặc định làm đường cơ sở.

Chuẩn bị tinh chỉnh siêu tham số#

Trước khi bắt đầu quá trình tinh chỉnh, điều quan trọng là:

  1. Xác định metric: Tuner tích hợp (use_ray=False) xếp hạng các lần thử theo điểm fitness của tác vụ, trong khi use_ray=True dùng metric của tác vụ. Hãy quyết định các metric phụ cần kiểm tra, chẳng hạn AP50 hoặc điểm F1.
  2. Thiết lập ngân sách tinh chỉnh: Xác định lượng tài nguyên tính toán bạn sẵn sàng phân bổ. Tinh chỉnh hyperparameter có thể tiêu tốn nhiều tài nguyên tính toán.

Cách vòng lặp tinh chỉnh hoạt động#

Ở mỗi vòng lặp, bộ tinh chỉnh tích hợp sẵn lặp lại quy trình sau:

  1. Khởi tạo siêu tham số — bắt đầu từ một đường cơ sở hợp lý, có thể là các siêu tham số mặc định do Ultralytics YOLO thiết lập hoặc các giá trị dựa trên kiến thức chuyên môn hay những thử nghiệm trước đó của bạn.
  2. Đột biến siêu tham số — lớp Tuner tự động tạo một bộ siêu tham số mới từ bộ hiện có bằng phương thức _mutate.
  3. Huấn luyện model — huấn luyện bằng các siêu tham số đã đột biến, sau đó đánh giá hiệu suất huấn luyện bằng các chỉ số bạn đã chọn.
  4. Đánh giá model — quy trình đánh giá tạo ra điểm thích nghi của vòng lặp, rồi so sánh điểm đó với các vòng lặp trước để xác định liệu các siêu tham số hiện tại có cải thiện hay không.
  5. Ghi nhật ký kết quả — lưu lại cả các chỉ số hiệu suất và siêu tham số tương ứng để tham khảo sau này. Ultralytics YOLO tự động lưu các kết quả này ở định dạng NDJSON.
  6. Lặp lại — tiếp tục cho đến khi đạt số vòng lặp đã đặt; mỗi vòng lặp đều tận dụng kiến thức thu được từ các lượt chạy trước. Bộ tinh chỉnh tích hợp sẵn chạy toàn bộ iterations; Ray Tune báo cáo các chỉ số sau mỗi epoch fit, cho phép ASHA dừng các lượt thử kém sau thời gian chờ tối thiểu.

Số vòng lặp và kích thước quần thể#

Với bộ tinh chỉnh tích hợp sẵn (use_ray=False), iterations kiểm soát tổng số lượt thử tuần tự và mặc định là 300. Mỗi lượt thử huấn luyện một model với một cấu hình siêu tham số — ví dụ, iterations=40 cùng epochs=50 lên lịch 40 lượt huấn luyện độc lập, mỗi lượt 50 epoch; không phải một lượt huấn luyện 50 epoch với một quần thể riêng gồm 40 ứng viên.

Thuật toán di truyền tích hợp sẵn không có tham số kích thước quần thể tường minh. Khi đã có các lượt thử trước đó, thuật toán chọn từ tối đa chín cấu hình có độ thích nghi cao nhất và đột biến một ứng viên ở mỗi vòng lặp.

Để chạy các lượt thử song song hoặc sử dụng chiến lược tìm kiếm nâng cao hơn, hãy đặt use_ray=True để dùng Ray Tune; Ray Tune cũng có mặc định 300 lượt thử và nhận iterations làm num_samples. Xem hướng dẫn tích hợp Ray Tune để biết thêm chi tiết.

Không gian tìm kiếm mặc định#

Bảng sau liệt kê các tham số trong không gian tìm kiếm mặc định để tinh chỉnh siêu tham số trong YOLO26. Mỗi tham số có một khoảng giá trị cụ thể được xác định bằng tuple (min, max).

Tham sốKiểuKhoảng giá trịMô tả
lr0float(1e-5, 1e-2)Learning rate ban đầu khi bắt đầu huấn luyện. Giá trị thấp hơn giúp quá trình huấn luyện ổn định hơn nhưng hội tụ chậm hơn
lrffloat(0.01, 1.0)Hệ số learning rate cuối cùng tính theo tỷ lệ của lr0. Kiểm soát mức giảm của learning rate trong quá trình huấn luyện
momentumfloat(0.7, 0.98)Hệ số momentum của SGD. Giá trị cao hơn giúp duy trì hướng gradient nhất quán và có thể tăng tốc độ hội tụ
weight_decayfloat(0.0, 0.001)Hệ số regularization L2 để ngăn overfitting. Giá trị lớn hơn áp dụng regularization mạnh hơn
warmup_epochsfloat(0.0, 5.0)Số epoch warmup learning rate tuyến tính. Giúp ngăn tình trạng huấn luyện không ổn định ở giai đoạn đầu
warmup_momentumfloat(0.0, 0.95)Momentum ban đầu trong giai đoạn warmup. Tăng dần đến giá trị momentum cuối cùng
boxfloat(1.0, 20.0)Trọng số loss bounding box trong hàm loss tổng. Cân bằng giữa hồi quy box và phân loại
clsfloat(0.1, 4.0)Trọng số loss phân loại trong hàm loss tổng. Giá trị cao hơn nhấn mạnh việc dự đoán lớp chính xác
cls_pwfloat(0.0, 1.0)Số mũ trọng số lớp để xử lý mất cân bằng lớp. Giá trị cao hơn tăng trọng số cho các lớp hiếm
dflfloat(0.4, 12.0)Trọng số của thành phần hồi quy khoảng cách box. YOLO26 không dùng DFL áp dụng hệ số này cho loss L1 trên khoảng cách box đã chuẩn hóa; giá trị cao hơn nhấn mạnh khả năng định vị chính xác
hsv_hfloat(0.0, 0.1)Phạm vi augmentation hue ngẫu nhiên trong không gian màu HSV. Giúp model tổng quát hóa với các biến thể màu sắc
hsv_sfloat(0.0, 0.9)Phạm vi augmentation saturation ngẫu nhiên trong không gian HSV. Mô phỏng các điều kiện chiếu sáng khác nhau
hsv_vfloat(0.0, 0.9)Phạm vi augmentation value (độ sáng) ngẫu nhiên. Giúp model xử lý các mức phơi sáng khác nhau
degreesfloat(0.0, 45.0)Mức augmentation xoay tối đa tính bằng độ. Giúp model bất biến với hướng của đối tượng
translatefloat(0.0, 0.9)Mức augmentation dịch chuyển tối đa theo tỷ lệ kích thước ảnh. Tăng độ bền vững trước sự thay đổi vị trí đối tượng
scalefloat(0.0, 0.95)Phạm vi augmentation scale ngẫu nhiên. Giúp model phát hiện đối tượng ở nhiều kích thước khác nhau
shearfloat(0.0, 10.0)Mức augmentation shear tối đa tính bằng độ. Tạo biến dạng giống phối cảnh trên ảnh huấn luyện
perspectivefloat(0.0, 0.001)Phạm vi augmentation phối cảnh ngẫu nhiên. Mô phỏng các góc nhìn khác nhau
flipudfloat(0.0, 1.0)Xác suất lật ảnh theo chiều dọc trong quá trình huấn luyện. Hữu ích với ảnh chụp từ trên cao hoặc ảnh hàng không
fliplrfloat(0.0, 1.0)Xác suất lật ảnh theo chiều ngang. Giúp model bất biến với hướng của đối tượng
bgrfloat(0.0, 1.0)Xác suất sử dụng augmentation BGR, hoán đổi các kênh màu. Có thể giúp model bất biến với màu sắc
mosaicfloat(0.0, 1.0)Xác suất sử dụng augmentation mosaic, kết hợp 4 ảnh. Đặc biệt hữu ích cho phát hiện vật thể nhỏ
mixupfloat(0.0, 1.0)Xác suất sử dụng augmentation mixup, trộn hai ảnh. Có thể cải thiện độ bền vững của model
cutmixfloat(0.0, 1.0)Xác suất sử dụng augmentation cutmix. Kết hợp các vùng ảnh đồng thời duy trì đặc trưng cục bộ
copy_pastefloat(0.0, 1.0)Ở chế độ flip, đây là tỷ lệ đối tượng đủ điều kiện được sao chép; ở chế độ mixup, giá trị này cũng là xác suất áp dụng augmentation
close_mosaicint(0.0, 10.0)Tắt mosaic trong N epoch cuối để ổn định quá trình huấn luyện trước khi kết thúc. Giá trị được đột biến dưới dạng số thực, sau đó làm tròn thành số epoch nguyên

Ví dụ về không gian tìm kiếm tùy chỉnh#

Ví dụ dưới đây xác định không gian tìm kiếm và gọi model.tune(), chạy class Tuner, để tinh chỉnh YOLO26n trên COCO8 trong 30 epoch bằng optimizer AdamW. Tắt việc vẽ biểu đồ, lưu checkpoint và validation ngoài epoch cuối để tinh chỉnh nhanh hơn.

Cảnh báo

Ví dụ này chỉ nhằm mục đích minh họa. Các siêu tham số thu được từ những lượt tinh chỉnh ngắn hoặc quy mô nhỏ hiếm khi tối ưu cho huấn luyện thực tế. Trên thực tế, nên tinh chỉnh trong các điều kiện tương tự như huấn luyện đầy đủ — bao gồm dataset, số epoch và augmentation tương đương — để đảm bảo kết quả đáng tin cậy và có thể chuyển giao. Tinh chỉnh nhanh có thể khiến tham số thiên về hội tụ nhanh hơn hoặc cải thiện validation trong ngắn hạn nhưng không tổng quát hóa được.

Ví dụ
from ultralytics import YOLO

# Khởi tạo YOLO model
model = YOLO("yolo26n.pt")

# Định nghĩa không gian tìm kiếm
search_space = {
    "lr0": (1e-5, 1e-2),
    "degrees": (0.0, 45.0),
}

# Tinh chỉnh siêu tham số trên COCO8 trong 30 epoch
model.tune(
    data="coco8.yaml",
    epochs=30,
    iterations=300,
    optimizer="AdamW",
    space=search_space,
    plots=False,
    save=False,
    val=False,
)

Tiếp tục phiên tinh chỉnh siêu tham số bị gián đoạn#

Bạn có thể tiếp tục phiên tinh chỉnh siêu tham số bị gián đoạn bằng cách truyền resume=True. Bạn có thể tùy chọn truyền thư mục name được dùng trong runs/{task} để tiếp tục. Nếu không có name, quá trình sẽ tiếp tục thư mục có tên chính xác là tune — tên mặc định, không phải phiên chạy gần đây nhất — vì vậy hãy truyền name cho mọi lượt chạy mà bạn đã bắt đầu với tên tùy chỉnh. Bạn cũng cần cung cấp tất cả các đối số huấn luyện trước đó, bao gồm data, epochs, iterations và space.

Sử dụng `resume=True` với `model.tune()`
from ultralytics import YOLO

# Định nghĩa YOLO model
model = YOLO("yolo26n.pt")

# Định nghĩa không gian tìm kiếm
search_space = {
    "lr0": (1e-5, 1e-2),
    "degrees": (0.0, 45.0),
}

# Tiếp tục lượt chạy trước
results = model.tune(data="coco8.yaml", epochs=50, iterations=300, space=search_space, resume=True)

# Tiếp tục lượt tinh chỉnh với tên 'tune_exp'
results = model.tune(data="coco8.yaml", epochs=50, iterations=300, space=search_space, name="tune_exp", resume=True)

Kết quả#

Sau khi hoàn tất thành công quá trình tinh chỉnh siêu tham số, bạn sẽ nhận được một số tệp và thư mục chứa kết quả tinh chỉnh. Mô tả về từng mục như sau:

Cấu trúc tệp#

Sau đây là cấu trúc thư mục kết quả. Các thư mục sweep như multitrain/ và multitrain-2/ chứa từng vòng lặp tinh chỉnh riêng lẻ, tức là mỗi model được huấn luyện trên một dataset bằng một bộ siêu tham số, trong thư mục con mang tên dataset tương ứng. Để tiết kiệm dung lượng, bộ tinh chỉnh xóa các thư mục chạy theo từng dataset của những vòng lặp không còn là kết quả tốt nhất hiện tại. Thư mục tune/ chứa kết quả tinh chỉnh từ tất cả các lượt huấn luyện model riêng lẻ:

runs/
└── detect/
    ├── multitrain/
    │   └── coco8/
    ├── multitrain-2/
    ├── ...
    └── tune/
        ├── best_hyperparameters.yaml
        ├── tune_fitness.png
        ├── tune_results.ndjson
        ├── tune_scatter_plots.png
        └── weights/
            ├── last.pt
            └── best.pt

Mô tả tệp#

best_hyperparameters.yaml#

Tệp YAML này chứa các siêu tham số có hiệu suất tốt nhất được tìm thấy trong quá trình tinh chỉnh. Bạn có thể dùng tệp này để khởi tạo các lượt huấn luyện sau với những thiết lập đã tối ưu.

  • Định dạng: YAML

  • Cách dùng: Kết quả siêu tham số

  • Ví dụ:

    # 558/900 iterations complete ✅ (45536.81s)
    # Results saved to /usr/src/ultralytics/runs/detect/tune
    # Best fitness=0.64297 observed at iteration 498
    # Best fitness metrics are {'metrics/precision(B)': 0.87247, 'metrics/recall(B)': 0.71387, 'metrics/mAP50(B)': 0.79106, 'metrics/mAP50-95(B)': 0.62651, 'val/box_loss': 2.79884, 'val/cls_loss': 2.72386, 'val/l1_loss': 0.68503, 'fitness': 0.64297}
    # Best fitness model is /usr/src/ultralytics/runs/detect/tune/weights
    # Best fitness hyperparameters are printed below.
    
    lr0: 0.00269
    lrf: 0.00288
    momentum: 0.73375
    weight_decay: 0.00015
    warmup_epochs: 1.22935
    warmup_momentum: 0.1525
    box: 18.27875
    cls: 1.32899
    dfl: 0.56016
    hsv_h: 0.01148
    hsv_s: 0.53554
    hsv_v: 0.13636
    degrees: 0.0
    translate: 0.12431
    scale: 0.07643
    shear: 0.0
    perspective: 0.0
    flipud: 0.0
    fliplr: 0.08631
    mosaic: 0.42551
    mixup: 0.0
    copy_paste: 0.0

tune_fitness.png#

Đây là biểu đồ thể hiện độ thích nghi theo số vòng lặp. Biểu đồ giúp bạn hình dung hiệu suất của thuật toán di truyền theo thời gian.

  • Định dạng: PNG
  • Cách dùng: Trực quan hóa hiệu suất

Hyperparameter Tuning Fitness vs Iteration

Biểu đồ bao gồm:

  • Một dấu điểm cho mỗi vòng lặp trên mỗi dataset, vì vậy lượt chạy với một dataset hiển thị một điểm ở mỗi vòng lặp, còn lượt chạy với nhiều dataset hiển thị một điểm cho mỗi dataset ở mỗi vòng lặp.
  • Đường "trung bình làm mượt" dạng chấm được tính bằng phép làm mượt Gaussian (sigma=3) trên các giá trị độ thích nghi cấp cao nhất của từng vòng lặp.

tune_results.ndjson#

Tệp NDJSON chứa kết quả chi tiết của từng vòng lặp tinh chỉnh. Mỗi dòng là một đối tượng JSON gồm độ thích nghi tổng hợp, các siêu tham số đã tinh chỉnh và các chỉ số theo từng dataset. Quá trình tinh chỉnh trên một hoặc nhiều dataset đều sử dụng cùng định dạng tệp.

  • Định dạng: NDJSON
  • Cách dùng: Theo dõi kết quả từng vòng lặp.
  • Ví dụ:

Sau đây là ví dụ được định dạng đẹp để dễ đọc; trong tệp .ndjson thực tế, mỗi đối tượng được lưu trên một dòng.

{
    "iteration": 1,
    "fitness": 0.48628,
    "hyperparameters": {
        "lr0": 0.01,
        "lrf": 0.01,
        "momentum": 0.937,
        "weight_decay": 0.0005
    },
    "datasets": {
        "coco8": {
            "metrics/precision(B)": 0.65666,
            "metrics/recall(B)": 0.85,
            "metrics/mAP50(B)": 0.85086,
            "metrics/mAP50-95(B)": 0.64104,
            "val/box_loss": 1.57958,
            "val/cls_loss": 1.04986,
            "val/l1_loss": 1.32641,
            "fitness": 0.64104
        },
        "coco8-grayscale": {
            "metrics/precision(B)": 0.6582,
            "metrics/recall(B)": 0.51667,
            "metrics/mAP50(B)": 0.59106,
            "metrics/mAP50-95(B)": 0.33152,
            "val/box_loss": 1.95424,
            "val/cls_loss": 1.64059,
            "val/l1_loss": 1.70226,
            "fitness": 0.33152
        }
    },
    "save_dirs": {
        "coco8": "runs/detect/multitrain/coco8",
        "coco8-grayscale": "runs/detect/multitrain/coco8-grayscale"
    }
}

fitness cấp cao nhất là trung bình cộng của các giá trị fitness theo từng dataset. Khi tinh chỉnh trên một dataset, dict datasets có một mục, trong đó fitness bằng fitness cấp cao nhất. Mỗi vòng lặp hoàn tất sẽ ghi lại một đối tượng JSON. Các đường dẫn save_dirs thực tế là đường dẫn tuyệt đối; chúng được rút gọn ở trên để dễ đọc.

tune_scatter_plots.png#

Tệp này chứa các biểu đồ phân tán được tạo từ tune_results.ndjson, giúp bạn hình dung mối quan hệ giữa các siêu tham số và chỉ số hiệu suất khác nhau. Quá trình đột biến sử dụng phạm vi được cấu hình cho từng siêu tham số, vì vậy các giá trị có thể tiến hóa từ những giá trị mặc định bằng không như degrees và shear.

  • Định dạng: PNG
  • Cách dùng: Phân tích dữ liệu khám phá

Hyperparameter tuning results scatter plot analysis

weights/#

Thư mục này chứa các model PyTorch đã lưu từ vòng lặp có độ thích nghi tốt nhất của lượt tinh chỉnh. Cả hai tệp đều thuộc cùng vòng lặp đó:

  • last.pt: Trọng số từ epoch cuối cùng của lượt huấn luyện đó.
  • best.pt: Trọng số từ epoch có độ phù hợp cao nhất trong lượt huấn luyện đó.

Dựa vào các kết quả này, bạn có thể đưa ra quyết định sáng suốt hơn cho các lần huấn luyện và phân tích model sau này.

Kết luận#

Tinh chỉnh siêu tham số trong Ultralytics YOLO vừa dễ khởi chạy vừa mạnh mẽ bên trong, nhờ lựa chọn có trọng số theo độ thích nghi và đột biến được chuẩn hóa theo phạm vi trong thuật toán di truyền. Làm theo vòng lặp được trình bày trong hướng dẫn này giúp bạn tinh chỉnh model một cách có hệ thống để đạt hiệu suất tốt hơn, sau đó tái sử dụng best_hyperparameters.yaml thu được để khởi tạo các lần huấn luyện tiếp theo. Để mở rộng quy mô tinh chỉnh trên các lượt thử nghiệm song song và dùng những thuật toán tìm kiếm nâng cao hơn, hãy xem tiếp hướng dẫn tích hợp Ray Tune, hoặc chạy các tác vụ được quản lý với siêu tham số có thể cấu hình và theo dõi chỉ số theo thời gian thực trên Ultralytics Platform thông qua huấn luyện trên đám mây.

Với các thiết lập không được cung cấp qua bất kỳ đối số nào, chẳng hạn như learning rate riêng cho từng layer hoặc chỉ số độ thích nghi tùy chỉnh, hãy tạo lớp con từ trainer. Để hiểu sâu hơn, hãy khám phá mã nguồn của lớp Tuner. Nếu có câu hỏi hoặc yêu cầu tính năng, hãy liên hệ qua GitHub hoặc Discord.

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

  • Đặt giá trị ban đầu bằng tham số lr0 — các giá trị thường dùng nằm trong khoảng từ 0.001 đến 0.01 — rồi để quá trình tinh chỉnh tạo đột biến từ giá trị đó nhằm tìm ra mức tối ưu. Bạn có thể tự động hóa việc này bằng phương thức model.tune(). Ví dụ:

    Ví dụ
    from ultralytics import YOLO
    
    # Khởi tạo YOLO model
    model = YOLO("yolo26n.pt")
    
    # Tinh chỉnh siêu tham số trên COCO8 trong 30 epoch
    model.tune(data="coco8.yaml", epochs=30, iterations=300, optimizer="AdamW", plots=False, save=False, val=False)

    Để biết thêm chi tiết, hãy xem trang cấu hình Ultralytics YOLO.

  • Thuật toán di truyền cung cấp cho Ultralytics YOLO26 một cách thức hiệu quả để khám phá không gian hyperparameter mà không cần thử sai thủ công. Các lợi ích chính bao gồm:

    • Tìm kiếm hiệu quả: Lựa chọn có trọng số theo độ thích nghi giữ lại các cấu hình tốt, trong khi đột biến được chuẩn hóa theo phạm vi khám phá các ứng viên mới.
    • Tránh cực tiểu cục bộ: Các đột biến ngẫu nhiên giúp quá trình tìm kiếm thoát khỏi cực tiểu cục bộ, nơi một phương pháp tìm kiếm tham lam thuần túy có thể mắc kẹt.
    • Metric hiệu năng: Các metric này được điều chỉnh dựa trên điểm fitness riêng cho từng tác vụ (mAP50-95 đối với phát hiện).

    Để xem cách thuật toán di truyền tối ưu hóa siêu tham số, hãy tham khảo hướng dẫn tiến hóa siêu tham số.

  • Thời gian cần thiết để tinh chỉnh siêu tham số với Ultralytics YOLO phụ thuộc phần lớn vào một số yếu tố như kích thước dataset, độ phức tạp của kiến trúc model, số vòng lặp và tài nguyên tính toán sẵn có. Ví dụ, việc tinh chỉnh YOLO26n trên dataset như COCO8 trong 30 epoch có thể mất từ vài giờ đến vài ngày, tùy thuộc vào phần cứng.

    Để quản lý hiệu quả thời gian tinh chỉnh, hãy xác định trước ngân sách tinh chỉnh rõ ràng như trình bày trong Chuẩn bị tinh chỉnh siêu tham số. Việc này giúp cân bằng phân bổ tài nguyên và mục tiêu tối ưu hóa.

  • Khi đánh giá hiệu suất model trong quá trình tinh chỉnh siêu tham số cho YOLO, bạn có thể dùng một số chỉ số chính:

    • AP50: Độ chính xác trung bình tại ngưỡng IoU 0.50.
    • Điểm F1: Trung bình điều hòa giữa precision và recall.
    • Precision và Recall: Các chỉ số riêng lẻ thể hiện độ chính xác của model khi xác định true positive so với false positive và false negative.

    Các metric này giúp bạn hiểu những khía cạnh khác nhau trong hiệu suất của model.

  • Có, Ultralytics YOLO26 tích hợp với Ray Tune để tối ưu hyperparameter nâng cao. Ray Tune cung cấp các thuật toán tìm kiếm như tối ưu hóa Bayesian và Hyperband, cùng khả năng thực thi song song để tăng tốc quá trình tinh chỉnh.

    Để dùng Ray Tune với YOLO26, hãy đặt tham số use_ray=True trong lời gọi phương thức model.tune().

Bình luận152

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

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

    I tuned my defect detection dataset ,which are composed of 8000+ images, this is my tune code: model.tune( data="../data/data20260420_line_scan_merged_6ch.yaml", epochs=300, iterations=300, #space=search_space, #optimizer="AdamW", optimizer="MuSGD", lr0=0.01, momentum=0.9, shear=1, degrees=1, perspective=0.0001, mixup=0.1, cutmix=0.1, batch=20 )

    I got the best mAP 0.586 at iteration 5 after tuned 30+ iterations, then I retrain the dataset with the following code: model.train( data="../data/data20260420_line_scan_merged_6ch.yaml", epochs=300, batch=20, imgsz=640, device=0, workers=16, optimizer="MuSGD", lr0=0.00721, lrf=0.01267, momentum=0.81816, weight_decay=0.00077, warmup_epochs=3.31429, warmup_momentum=0.95, box=7.11682, cls=0.48318, dfl=0.9397, hsv_h=0.00364, hsv_s=0.9, hsv_v=0.29751, degrees=0.99922, translate=0.07662, scale=0.51303, shear=0.76723, perspective=0.0, flipud=0.00019, fliplr=0.57639, bgr=0.00634, mosaic=0.62424, mixup=0.11307, cutmix=0.13007, copy_paste=0.00583, close_mosaic=10 #cfg="best_hyperparameters_map0.586.yaml" )

    I copied the hyperparameters from best_hyperparameters_map0.586.yaml, but I got the best mAP 0.568, what cause the discrepancy?Can sb help me out? Thanks.

    1. Glenn JocherUltralytics

      A small gap like 0.586 -> 0.568 is usually expected because tune() saves the best single stochastic run, while your later train() is a fresh run with different randomness and augmentation order; please first validate the tuning checkpoint runs/detect/tune/weights/best.pt, then retrain with the exact same args plus seed=0 and deterministic=True, and make sure you are comparing the same metric (fitness/mAP50-95) described in the Hyperparameter Tuning guide. If the gap still looks too large, please share the text output from validating that checkpoint and the matching row from tune_results.ndjson here in Discussions so the team can compare them directly.

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

      Thank you for your timely reply, I validated the tuning checkpoint, here is the text output from validating that checkpoint: (yolo26) ps@ps:~/Desktop/GB/ultralytics$ python val.py Ultralytics 8.4.26 🚀 Python-3.11.15 torch-2.5.1 CUDA:0 (NVIDIA GeForce RTX 4090 D, 24208MiB) YOLO26x summary (fused): 190 layers, 55,645,380 parameters, 0 gradients, 193.9 GFLOPs val: Fast image access ✅ (ping: 0.0±0.0 ms, read: 10744.4±1424.6 MB/s, size: 734.1 KB) val: Scanning /home/ps/Desktop/GB/ultralytics/datasets/Merged_6Chanel_20260420/imagesH/val.cache... 786 images, 47 backgrounds, 0 corrupt: 100% ━━━━━━━━━━━━ 786/786 412.1Mit/s 0.0s Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 50/50 6.9it/s 7.2s all 786 1363 0.843 0.69 0.765 0.585 black 45 47 0.914 0.677 0.828 0.648 crack 120 145 0.681 0.517 0.55 0.334 edge 184 195 0.916 0.899 0.94 0.833 line 116 147 0.809 0.646 0.736 0.544 pit 73 89 0.775 0.543 0.642 0.447 raw 279 318 0.861 0.745 0.81 0.644 white 95 106 0.9 0.623 0.712 0.46 yellow 299 316 0.884 0.873 0.9 0.773 Speed: 0.9ms preprocess, 7.3ms inference, 0.0ms loss, 0.0ms postprocess per image Results saved to /home/ps/Desktop/GB/ultralytics/runs/detect/val81

      I checked my retrain args, it show that seed=0 and deterministic=True already set: python train.py New https://pypi.org/project/ultralytics/8.4.53 available 😃 Update with 'pip install -U ultralytics' Ultralytics 8.4.26 🚀 Python-3.11.15 torch-2.5.1 CUDA:0 (NVIDIA GeForce RTX 4090 D, 24208MiB) engine/trainer: agnostic_nms=False, amp=True, angle=1.0, augment=False, auto_augment=randaugment, batch=20, bgr=0.00634, box=7.11682, cache=False, cfg=None, classes=None, close_mosaic=10, cls=0.48318, compile=False, conf=None, copy_paste=0.00583, copy_paste_mode=flip, cos_lr=False, cutmix=0.13007, data=../data/data20260420_line_scan_merged_6ch.yaml, degrees=0.99922, deterministic=True, device=0, dfl=0.9397, dnn=False, dropout=0.0, dynamic=False, embed=None, end2end=None, epochs=500, erasing=0.4, exist_ok=False, fliplr=0.57639, flipud=0.00019, format=torchscript, fraction=1.0, freeze=None, half=False, hsv_h=0.00364, hsv_s=0.9, hsv_v=0.29751, imgsz=640, int8=False, iou=0.7, keras=False, kobj=1.0, line_width=None, lr0=0.00721, lrf=0.01267, mask_ratio=4, max_det=300, mixup=0.11307, mode=train, model=yolo26x.pt, momentum=0.81816, mosaic=0.62424, multi_scale=0.0, name=train137, nbs=64, nms=False, opset=None, optimize=False, optimizer=MuSGD, overlap_mask=True, patience=100, perspective=0.0, plots=True, pose=12.0, pretrained=True, profile=False, project=None, rect=False, resume=False, retina_masks=False, rle=1.0, save=True, save_conf=False, save_crop=False, save_dir=/home/ps/Desktop/GB/ultralytics/runs/detect/train137, save_frames=False, save_json=False, save_period=-1, save_txt=False, scale=0.51303, seed=0, shear=0.76723, show=False, show_boxes=True, show_conf=True, show_labels=True, simplify=True, single_cls=False, source=None, split=val, stream_buffer=False, task=detect, time=None, tracker=botsort.yaml, translate=0.07662, val=True, verbose=True, vid_stride=1, visualize=False, warmup_bias_lr=0.1, warmup_epochs=3.31429, warmup_momentum=0.95, weight_decay=0.00077, workers=16, workspace=None

      And here is the train output: Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size 260/300 20.8G 0.4503 0.4947 0.004246 50 640: 100% ━━━━━━━━━━━━ 354/354 2.7it/s 2:10 Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 20/20 4.5it/s 4.4s all 786 1363 0.841 0.682 0.751 0.564 EarlyStopping: Training stopped early as no improvement observed in last 100 epochs. Best results observed at epoch 160, best model saved as best.pt. To update EarlyStopping(patience=100) pass a new patience value, i.e. patience=300 or use patience=0 to disable EarlyStopping.

      260 epochs completed in 9.792 hours. Optimizer stripped from /home/ps/Desktop/GB/ultralytics/runs/detect/train138/weights/last.pt, 118.4MB Optimizer stripped from /home/ps/Desktop/GB/ultralytics/runs/detect/train138/weights/best.pt, 118.4MB

      Validating /home/ps/Desktop/GB/ultralytics/runs/detect/train138/weights/best.pt... Ultralytics 8.4.26 🚀 Python-3.11.15 torch-2.5.1 CUDA:0 (NVIDIA GeForce RTX 4090 D, 24208MiB) YOLO26x summary (fused): 190 layers, 55,645,380 parameters, 0 gradients, 193.9 GFLOPs Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 20/20 4.9it/s 4.1s all 786 1363 0.826 0.685 0.758 0.568 black 45 47 0.882 0.634 0.773 0.579 crack 120 145 0.675 0.559 0.577 0.314 edge 184 195 0.925 0.885 0.949 0.824 line 116 147 0.785 0.667 0.714 0.52 pit 73 89 0.84 0.528 0.662 0.447 raw 279 318 0.812 0.72 0.804 0.638 white 95 106 0.802 0.611 0.674 0.434 yellow 299 316 0.888 0.877 0.911 0.787 Speed: 0.1ms preprocess, 4.4ms inference, 0.0ms loss, 0.0ms postprocess per image Results saved to /home/ps/Desktop/GB/ultralytics/runs/detect/train138

      And I don't know where to find tune_results.ndjson mentioned in your reply. I guess you mean the matching row from tune_results.csv then here is: fitness lr0 lrf momentum weight_decay warmup_epochs warmup_momentum box cls dfl hsv_h hsv_s hsv_v degrees translate scale shear perspective flipud fliplr bgr mosaic mixup cutmix copy_paste close_mosaic 0.58582 0.00721 0.01267 0.81816 0.00077 3.31429 0.95 7.11682 0.48318 0.9397 0.00364 0.9 0.29751 0.99922 0.07662 0.51303 0.76723 0 0.00019 0.57639 0.00634 0.62424 0.11307 0.13007 0.00583 10

    3. Glenn JocherUltralytics

      The main issue I see is that your retrain is not matching the tuned trial: the runtime log shows epochs=500 rather than 300, so the schedule driven by lr0 and lrf is different and that alone can explain 0.585 -> 0.568; the current Hyperparameter Tuning guide writes tune_results.ndjson under runs/detect/tune/, but in your older 8.4.26 install the equivalent may be tune_results.csv, so please rerun with the exact runtime args from the best trial, especially epochs=300 and the same patience, and if it still prints epochs=500 then another override is being applied.

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

      Sorry, after hyperparameter tuning, I retrained first with epochs=500, observed mAP=0.57, then I changed epochs=300, observed mAP=0.568. In the previous reply, I mistakenly copied the retrain args from the epochs=500 run. But the train output is correctly copied from the epochs=300 run, you can tell this out from the EarlyStopping output: Epoch GPU_mem box_loss cls_loss dfl_loss Instances Size 260/300 20.8G 0.4503 0.4947 0.004246 50 640: 100% ━━━━━━━━━━━━ 354/354 2.7it/s 2:10 Class Images Instances Box(P R mAP50 mAP50-95): 100% ━━━━━━━━━━━━ 20/20 4.5it/s 4.4s all 786 1363 0.841 0.682 0.751 0.564 EarlyStopping: Training stopped early as no improvement observed in last 100 epochs. Best results observed at epoch 160, best model saved as best.pt. To update EarlyStopping(patience=100) pass a new patience value, i.e. patience=300 or use patience=0 to disable EarlyStopping.

      And the retrain args of the epochs=300 run, it shows that seed=0 and deterministic=True already set: python train.py New https://pypi.org/project/ultralytics/8.4.53 available 😃 Update with 'pip install -U ultralytics' Ultralytics 8.4.26 🚀 Python-3.11.15 torch-2.5.1 CUDA:0 (NVIDIA GeForce RTX 4090 D, 24208MiB) engine/trainer: agnostic_nms=False, amp=True, angle=1.0, augment=False, auto_augment=randaugment, batch=20, bgr=0.00634, box=7.11682, cache=False, cfg=None, classes=None, close_mosaic=10, cls=0.48318, compile=False, conf=None, copy_paste=0.00583, copy_paste_mode=flip, cos_lr=False, cutmix=0.13007, data=../data/data20260420_line_scan_merged_6ch.yaml, degrees=0.99922, deterministic=True, device=0, dfl=0.9397, dnn=False, dropout=0.0, dynamic=False, embed=None, end2end=None, epochs=300, erasing=0.4, exist_ok=False, fliplr=0.57639, flipud=0.00019, format=torchscript, fraction=1.0, freeze=None, half=False, hsv_h=0.00364, hsv_s=0.9, hsv_v=0.29751, imgsz=640, int8=False, iou=0.7, keras=False, kobj=1.0, line_width=None, lr0=0.00721, lrf=0.01267, mask_ratio=4, max_det=300, mixup=0.11307, mode=train, model=yolo26x.pt, momentum=0.81816, mosaic=0.62424, multi_scale=0.0, name=train138, nbs=64, nms=False, opset=None, optimize=False, optimizer=MuSGD, overlap_mask=True, patience=100, perspective=0.0, plots=True, pose=12.0, pretrained=True, profile=False, project=None, rect=False, resume=False, retina_masks=False, rle=1.0, save=True, save_conf=False, save_crop=False, save_dir=/home/ps/Desktop/GB/ultralytics/runs/detect/train138, save_frames=False, save_json=False, save_period=-1, save_txt=False, scale=0.51303, seed=0, shear=0.76723, show=False, show_boxes=True, show_conf=True, show_labels=True, simplify=True, single_cls=False, source=None, split=val, stream_buffer=False, task=detect, time=None, tracker=botsort.yaml, translate=0.07662, val=True, verbose=True, vid_stride=1, visualize=False, warmup_bias_lr=0.1, warmup_epochs=3.31429, warmup_momentum=0.95, weight_decay=0.00077, workers=16, workspace=None

    5. Murat Raimbekov

      quick check on what is likely going on, framed generally: tune saves the best of N stochastic trials, and a single retrain is one new stochastic draw with the same hyperparameters. bit-exact reproduction between the two is not guaranteed even with seed=0, deterministic=True. our init_seeds(deterministic=True) sets torch.use_deterministic_algorithms(True, warn_only=True) in ultralytics/utils/torch_utils.py, matching the pytorch reproducibility notes - cuda ops without a deterministic alternative still run non-deterministically with just a warning. over many epochs on a real dataset that variance can compound.

      a few practical takeaways before assuming the gap is a tuning bug:

      • your trial weights at runs/detect/tune/weights/best.pt already validate to 0.585, so the trial result is real and reusable - if you need exactly that performance for deployment, use that checkpoint directly.
      • the recommended way to reuse tuned hyperparameters in a fresh train run is cfg="runs/detect/tune/best_hyperparameters.yaml" (the commented-out line in your script). that file contains the exact values the trial used and matches the workflow described in the hyperparameter tuning guide.
      • to bound run-to-run variance, retrain a few times with seed=0, seed=1, seed=2 and compare the mean against the tune's reported best, not a single retrain.

      unrelated, you are on ultralytics 8.4.26 and the current release is 8.4.53; for new tuning runs it is worth updating.

  2. User

    Hi, I have a question about Hyperparameter Tuning. What value of epochs and iterations should I pass to model.tune(). Default value of epochs is 100, and iterations is 10. Are the default values OK, or should I change them ? My dataset is about 10,000 images.

    1. Glenn JocherUltralytics

      For a 10k-image dataset, the defaults are fine for a quick sanity check, but for useful tuning you should set epochs close to your real training length because epochs is per trial, while iterations is how many different trials are tested; a practical starting point is epochs=50 to 100 with iterations=30 to 100 depending on your compute budget, then retrain once with the best settings from best_hyperparameters.yaml as shown in the Hyperparameter Tuning guide.

      1
    2. User

      Thank you very much ! I will try to search the best hyperparameters !

    3. Glenn JocherUltralytics

      You're welcome — sounds good; if anything looks off during tuning, please share your model.tune() call plus the resulting best_hyperparameters.yaml or tune_results.ndjson here, and we can help compare it against the expected outputs in the Hyperparameter Tuning guide.

  3. harunemrekiran61GitHub

    You’ve shown the box range as 0.02 to 0.2, but the default value appears to be 7.5. Is there a mistake here? Could you please check?

  4. Larry-zhaiGitHub

    How can I directly apply the optimized best_hyperparameters.yaml to my training? In fact, when I use code similar to the following: from ultralytics import YOLO model = YOLO("yolov8n.pt") model.train(data="data.yaml", hyp="hyp.yaml") an error occurs: SyntaxError: 'hyp' is not a valid YOLO argument.

  5. J.Q. Pan

    Hi I have used the above code to apply the tuning but neither the diagram nor the models will be saved. I only get a single tune folder with all tuning details. I may ask if someone else has also the same problem.

  6. BrianNieuwenhuisGitHub

    When running the code below the model.tune() call does not recognize my model specification. Could someone explain to me what I am doing wrong. I am using model.overrides so that I can also tune the shear and perspective parameters that are otherwise initialized at 0.

    from ultralytics import YOLO import wandb from ultralytics import settings settings.update({"wandb": True})

    import argparse

    def main(): # parse command-line args if needed parser = argparse.ArgumentParser() parser.add_argument("--gpus", type=int, default=1) parser.add_argument("--workers", type=int, default=4) args = parser.parse_args()

    # Define a YOLO model
    model = YOLO("yolo11x.pt")
    
    # Dynamically assign GPUs based on --gpus argument
    device = list(range(args.gpus))  # e.g., [0, 1, 2, 3] if args.gpus = 4
    
    # Define search space
    search_space = {
        "lr0": (1e-5, 1e-1),
        "lrf": (0.01, 1.0),
        "momentum": (0.6, 0.98),
        "weight_decay": (0.0, 0.001),
        "warmup_epochs": (0, 5),
        "warmup_momentum": (0.0,0.95),
        "box": (0.02, 0.2),
        "cls": (0.2, 4.0),
        "hsv_h": (0.0, 0.1),
        "hsv_s": (0.0, 0.9),
        "hsv_v": (0.0, 0.9),
        "translate":(0.0, 0.9),
        "scale": (0.0, 0.9),
        "shear": (0.0, 10.0),
        "perspective": (0.0, 0.001),
        "mosaic": (0.0,1.0),
        "mixup": (0.0, 1.0),
        "copy_paste": (0.0, 1.0)
    }
    
    # Manually initialize certain hperparameters that would not be tuned otherwise
    model.overrides = {
        'shear': 1,
        'perspective': 0.001,
        'mixup': 0.01,
        'copy_paste' : 0.01,
    
    }
    
    # tune the model
    results = model.tune(project='./tune/crop1344',name="tune_default_batch16_v100", use_ray = False,
        data="data.yaml", 
        #hyp="custom_hyp.yaml", # this does not seem to work work for tune scripts!!
        batch = 16,
        imgsz = 1344,    
        device = device,
        workers = args.workers,
    
        degrees = 180, #these parameters are fixed in the model tune
        flipud = 0.5,
        fliplr = 0.5,
        bgr = 0,
        auto_augment = None,
        #erasing = 0,
        
        epochs = 100,
        iterations=10, 
        space=search_space,
        optimizer="AdamW", 
        resume=False,  #start over or resume previous checkpoint
        plots=False,  # don't make plots etc to save time until last timepoint
        save=False,
        val=False,
        verbose=False)

    if name == "main": main()

  7. yyagmurkyaaGitHub

    Hello again, I have trained new models using the parameters you provided and by organizing my datasets. However, a common issue across all of them is that the models mistakenly classify objects like myself or nearby computer screens as the traffic sign "turn right ahead" (which is one of the labeled classes in my dataset). I have checked my dataset and confirmed that there are no such unrelated objects in the background.

    Additionally, the models sometimes confuse left and right directional signs.

    Why might these errors be occurring, and how can I fix them? Thank you in advance for your help.

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

      @Fatima-khanjar to balance precision and recall in your over-predicting model, try these adjustments:

      1. Increase confidence threshold during inference (not training) to filter out low-confidence predictions
      2. Adjust IoU threshold in NMS to reduce duplicate detections
      3. Increase classification loss weight with cls=1.0 or higher to improve class discrimination
      4. Check annotation quality in your dataset, especially for small or ambiguous objects
      5. Add hard negative examples to your dataset - images with objects similar to your classes but not actually part of them

      These changes should help improve precision without significantly sacrificing your excellent recall. For implementation details, see our NMS documentation for confidence thresholding examples.

      @yyagmurkyaa for your traffic sign confusion issues:

      1. For the model detecting unrelated objects as "turn right ahead" signs:

        • Add "hard negative" examples to your training set (images with computers, people, but no traffic signs)
        • Increase cls=1.0 or higher to improve classification accuracy
        • Check if the "turn right ahead" sign has visual similarities to these false positives
      2. For left/right confusion:

        • Create specific augmentations for directional signs without flipping (as you noted)
        • Ensure balanced examples of both directional types
        • Consider using a slightly larger model like YOLO26m for better feature discrimination

      These targeted adjustments should help address the specific confusion patterns you're seeing.

    2. Fatima-khanjarGitHub

      Hello again!!

      First of all, thank you so much for your help @glenn-jocher __ you've truly helped me a lot, and I really appreciate it!

      I have a question regarding fine-tuning a pre-trained YOLO model (e.g., trained on the COCO dataset) for my custom use case. My dataset includes a combination of both new classes (not present in COCO) and some of the existing COCO classes , but with different layouts or contexts.

      What I’d like to do is the following:

      Add my new classes starting from index 80, while still leveraging the pre-trained weights for the existing COCO classes.

      Ideally, I want to preserve the learned knowledge for the COCO classes (especially the ones shared with my dataset), and only train the model further on the new classes.

      Is it possible to:

      Fine-tune the model in such a way that it uses the pre-trained weights for the common classes, and only learns new classes from scratch starting from a different index?

      Retain and benefit from the original COCO knowledge while introducing and training on new class definitions?

      Also, I’ve noticed that when I fine-tune a pre-trained model and define my own data.yaml file — completely different from coco.yaml — I redefine the class names and indexes based on my custom dataset, completely removing the COCO classes not present in my data. In this case, what really happens during fine-tuning or transfer learning under the hood? Is the model discarding unused class weights? Are shared class weights still used effectively?

      I'd greatly appreciate any clarification or guidance on how to approach this setup properly.

      Best regards,

    3. Glenn JocherUltralytics

      @Fatima-khanjar great question about fine-tuning with mixed COCO and custom classes!

      Yes, you can leverage pre-trained COCO weights while adding new classes. Here's how:

      1. When fine-tuning a YOLO model, the model's detection head is automatically resized to accommodate your new class count. The weights for existing classes are preserved where possible.

      2. For classes that overlap with COCO, the model will leverage transfer learning from those pre-trained weights, while new classes will be initialized with random weights.

      3. You don't need to explicitly start from index 80 - just define your classes in your data.yaml file, and the model will handle the mapping automatically.

      4. During fine-tuning, the model doesn't discard unused class weights but rather reshapes the classification head to match your class count. Weights for classes that exist in both datasets are transferred and further optimized for your specific data.

      For best results with mixed classes, I recommend using a smaller learning rate initially (e.g., lr0=0.001) to preserve the knowledge in the pre-trained weights while allowing the model to adapt to your new classes.

    4. Fatima-khanjarGitHub

      Hello! @glenn-jocher thank you so much for your explanation!

      I have a follow-up question regarding class index matching. Let's say the person class in the COCO dataset is indexed as 0, but in my data.yaml file, I assign person to index 5. In this case, the model will not treat the person at index 5 as the same class as COCO’s index 0, correct?

      So, to benefit from the pretrained weights of shared classes, do the class indices in my custom dataset need to match the COCO indices exactly?

      Best regards,

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

      @Fatima-khanjar you're asking a crucial question about class mapping during transfer learning!

      You no longer need to keep COCO's class indices. With cls_remap=True (the default), training copies the pretrained classification-head rows by class name, so a class such as person keeps its pretrained weights at whatever index it has in your dataset, while new classes such as traffic_sign start from fresh weights. Training prints Remapped N/M cls head rows from pretrained weights by class name when rows are copied, and cls_remap=False disables it. For example, this data.yaml works:

      names:
        0: person
        1: car
        2: traffic_sign

      Just make sure the shared classes use the same names as in COCO. See the Fine-Tuning Guide for details.

    6. Fatima-khanjarGitHub

      @glenn-jocher Hello again!!!

      Thank you so much for your clarification! I have a quick follow-up question.

      Let’s say the COCO dataset defines the following class indices in its YAML file: 0: person, 2: car, 3: cat.

      In my own dataset, I share only the person and car classes with COCO — I don’t want to include cat. If I define my shared classes using the same indices as COCO (i.e., 0: person, 2: car), but then replace the COCO class cat at index 3 with a new class (e.g., 3: animal), will I still benefit from the pretrained weights for the shared classes (person and car)?

      Or will assigning a new class at an index previously used by COCO (like 3) cause any issues?

      best regards,

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

      @Fatima-khanjar great question about reusing COCO indices for new classes!

      With cls_remap=True (the default), pretrained classification-head rows are matched by class name, not by index. Shared classes such as person and car keep their pretrained weights wherever they sit in your dataset. A new class like "animal" at index 3 does not inherit the pretrained "cat" row, because the names do not match, so it starts from fresh weights. Reusing a COCO index therefore neither helps nor hurts the shared classes.

      If a new class is close to a pretrained one, give it that class's name so its row is copied. Using a lower learning rate initially (e.g., lr0=0.001) also helps preserve the pretrained features while the model adapts to your new classes.

      1
  8. yyagmurkyaaGitHub

    Thank you for your feedback. I trained my dataset using YOLOv11s. Although I didn’t experience severe overfitting with the current parameters, I couldn’t achieve optimal performance either. Some traffic signs were misclassified or not detected at all.

    While searching for the best hyperparameters, I realized that I hadn't applied data augmentation—except for the flip parameter. I have an example parameter file, and I plan to include all relevant augmentation options except for flipping.

    I would really appreciate your help in finding the most suitable parameters for my dataset, as I’m planning to participate in a competition soon. I need to enhance my model by adjusting the parameters properly to achieve the best possible performance.

    Thank you in advance for your support.

    On Sun, Apr 20, 2025 at 1:51 PM phatima khanjar @.***> wrote:

    Hello,

    I hope this message finds you well.

    image.png (view on web) https://github.com/user-attachments/assets/be6db84b-fe0d-4356-ba77-9b4426c253ee

    I fine-tuned YOLOv11s on my custom dataset, which is relatively small (1,156 images split into 75% training, 15% validation, and 10% test). The dataset consists of 41 classes, with each class containing between 200 and 300 images. I experimented with three different sets of hyperparameters: the default values, those optimized using Ray Tune, and others obtained through a Genetic Algorithm. In all cases, I observed oscillations in the validation dfl and box losses, which may indicate signs of overfitting. I would appreciate any suggestions or insights on how to address this issue, particularly given the small size of the dataset, and how to improve model generalization.

    best regards,

    — Reply to this email directly, view it on GitHub https://github.com/orgs/ultralytics/discussions/9536#discussioncomment-12889695, or unsubscribe https://github.com/notifications/unsubscribe-auth/BPQ7ZLAQ2G7ZL434FN3WFYD22N345AVCNFSM6AAAAABFVXPSL2VHI2DSMVQWIX3LMV43URDJONRXK43TNFXW4Q3PNVWWK3TUHMYTEOBYHE3DSNI . You are receiving this because you were mentioned.Message ID: @.*** com>

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

      @yyagmurkyaa for traffic sign detection and classification with YOLO26s, I recommend focusing on these specific augmentation and training parameters:

      from ultralytics import YOLO
      
      model = YOLO("yolo26s.pt")
      model.train(
          data="your_traffic_signs.yaml",
          epochs=100,
          patience=25,
          batch=16,
          imgsz=640,  # Consider 800+ for small traffic signs
          hsv_h=0.015,  # Color augmentation helps with varying lighting conditions
          hsv_s=0.7,
          hsv_v=0.4,
          scale=0.5,  # Scale augmentation critical for varying distances
          translate=0.1,  # Helps with signs at different positions
          mosaic=1.0,  # Excellent for object detection tasks
          mixup=0.1,  # Light mixup can help with generalization
          perspective=0.0005,  # Slight perspective change for different viewing angles
          weight_decay=0.0005,  # Regularization to reduce overfitting
          optimizer="AdamW",
          lr0=0.001,
          lrf=0.01,
          cos_lr=True  # Cosine learning rate scheduler
      )

      For traffic sign detection specifically:

      1. Increase image size to better detect small signs
      2. Focus on color-preserving augmentations as colors are critical for traffic signs
      3. Use perspective transformations to simulate different viewing angles
      4. Enable strong scale/translate augmentations to handle varying distances

      Consider running model.tune() with these parameters as starting points to find the optimal configuration for your competition. You might also need to address class imbalance if some signs appear less frequently in your dataset.

    2. yyagmurkyaaGitHub

      You're very welcome! I wasn't expecting such a quick response either. I'm excited to hear that you'll be training with these parameters and look forward to seeing the results as soon as possible. Thank you again for your support!

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

      @Fatima-khanjar for a small dataset (1,156 images) with 41 classes, oscillations in validation losses often indicate overfitting. Here are specific recommendations to improve generalization:

      1. Strengthen regularization:

        • Increase weight_decay to 0.001-0.003
        • Add dropout with dropout=0.1 to reduce co-adaptation
      2. Enhance data augmentation:

        • Maximize augmentations: mosaic=1.0, mixup=0.2, copy_paste=0.1
        • Use strong geometric transforms: translate=0.2, scale=0.5
      3. Training modifications:

        • Reduce model complexity by using YOLO26n instead of YOLO26s
        • Implement gradual unfreezing (freeze layers at first)
        • Enable cos_lr=True for smoother learning rate decay
      4. Consider transfer learning modifications:

        • Start with a model pre-trained on a domain similar to yours
        • Use fewer epochs with higher patience for early stopping

      With 41 classes and limited samples per class, these techniques should help stabilize training and improve generalization. You might also benefit from training ensembles of multiple models if computational resources allow. For more details, refer to our Model Training Tips.

    4. Fatima-khanjarGitHub(đã chỉnh sửa)

      Hello,

      Thank you for your advice! Your instructions have improved my model’s performance compared to before. I have now achieved the following metrics:

      Mean Precision: 0.794 Mean Recall: 0.99 Mean F1 Score: 0.881 mAP@0.5: 0.938 mAP@0.5-0.95: 0.827

      After analyzing these results, it seems that the model is over-predicting. Do you have any suggestions on how I can better balance precision and recall?

      best regards,

  9. Fatima-khanjarGitHub

    Hello,

    I hope this message finds you well.

    image

    I fine-tuned YOLOv11s on my custom dataset, which is relatively small (1,156 images split into 75% training, 15% validation, and 10% test). The dataset consists of 41 classes, with each class containing between 200 and 300 images. I experimented with three different sets of hyperparameters: the default values, those optimized using Ray Tune, and others obtained through a Genetic Algorithm. In all cases, I observed oscillations in the validation dfl and box losses, which may indicate signs of overfitting. I would appreciate any suggestions or insights on how to address this issue, particularly given the small size of the dataset, and how to improve model generalization.

    best regards,

  10. yyagmurkyaaGitHub

    Hello, I am training a model using YOLOv11, and the dataset consists of traffic signs. There are 22 classes, and each class has 400 labeled images. I’m not sure what parameters I should use for training. What parameters should I set to prevent overfitting, and what are the correct values? Could you help me with this?

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

      @yyagmurkyaa your dataset of 22 classes with 400 images per class should provide a good foundation for traffic sign detection. To prevent overfitting with YOLO26, I'd recommend:

      1. Start with hyperparameter tuning using the model.tune() method to find optimal values:
      from ultralytics import YOLO
      
      model = YOLO("yolo26n.pt")  # Start with a smaller model for faster tuning
      model.tune(
          data="your_traffic_signs.yaml",
          epochs=30,
          iterations=100,
          weight_decay=0.0005,  # Try higher values like 0.001-0.005 to increase regularization
          patience=15,  # Early stopping
          val=True
      )
      1. Key hyperparameters to prevent overfitting:

        • Increase weight_decay (0.001-0.005)
        • Enable strong data augmentation (hsv_h, hsv_s, translate, scale, fliplr, mosaic)
        • Use early stopping with reasonable patience
        • Consider reducing model capacity (use n or s model variants)
      2. Monitor validation metrics to detect overfitting (when training accuracy continues improving but validation metrics plateau or decline)

      The automated tuning process should help identify the optimal parameter values for your specific dataset. For more details, check out our Hyperparameter Tuning Guide.

    2. yyagmurkyaaGitHub

      Thank you for your feedback. I trained my dataset using YOLOv11s. Although I didn’t experience severe overfitting with the current parameters, I couldn’t achieve optimal performance either. Some traffic signs were misclassified or not detected at all.

      While searching for the best hyperparameters, I realized that I hadn't applied data augmentation—except for the flip parameter. I have an example parameter file, and I plan to include all relevant augmentation options except for flipping.

      I would really appreciate your help in finding the most suitable parameters for my dataset, as I’m planning to participate in a competition soon. I need to enhance my model by adjusting the parameters properly to achieve the best possible performance.

      Thank you in advance for your support.