Model Training with Ultralytics YOLO#
Giới thiệu#
Training a deep learning model involves feeding it data and adjusting its parameters so that it can make accurate predictions. Train mode in Ultralytics YOLO26 is engineered for effective and efficient training of object detection models, fully utilizing modern hardware capabilities. This guide aims to cover all the details you need to get started with training your own models using YOLO26's robust set of features. If you haven't installed Ultralytics yet, start with the Quickstart guide.
Xem bản xem trước YOLO27 chưa phát hành để biết các ví dụ huấn luyện được lên kế hoạch.
Watch: How to Train a YOLO model on Your Custom Dataset in Google Colab.
Why Choose Ultralytics YOLO for Training?#
Here are some compelling reasons to opt for YOLO26's Train mode:
- Efficiency: Make the most out of your hardware, whether you're on a single-GPU setup or scaling across multiple GPUs.
- Versatility: Train on custom datasets in addition to readily available ones like COCO, VOC, and ImageNet.
- User-Friendly: Simple yet powerful CLI and Python interfaces for a straightforward training experience.
- Hyperparameter Flexibility: A broad range of customizable hyperparameters to fine-tune model performance. For deeper control, you can customize the trainer itself.
- Cloud Training: Train on cloud GPUs through Ultralytics Platform with real-time metrics and automatic checkpointing.
Key Features of Train Mode#
The following are some notable features of YOLO26's Train mode:
- Automatic Dataset Download: Dataset configurations with a download source are downloaded automatically on first use, e.g.,
yolo train data=coco8.yaml. See the Datasets overview for supported formats and datasets. - Multi-GPU Support: Scale your training efforts seamlessly across multiple GPUs to expedite the process.
- Hyperparameter Configuration: The option to modify hyperparameters through YAML configuration files or CLI arguments.
- Visualization and Monitoring: Real-time tracking of training metrics and visualization of the learning process for better insights.
Ví dụ sử dụng#
Train YOLO26n on the COCO8 dataset for 100 epochs at image size 640. The training device can be specified using the device argument. If no argument is passed, GPU device=0 will be used when available; otherwise device='cpu' will be used. See the Arguments section below for a full list of training arguments.
On Windows, you may receive a RuntimeError when launching the training as a script. Add an if __name__ == "__main__": block before your training code to resolve it.
Device is determined automatically. If a GPU is available, it will be used (default CUDA device 0); otherwise training will start on CPU.
from ultralytics import YOLO
# Load a model
model = YOLO("yolo26n.yaml") # build a new model from YAML
model = YOLO("yolo26n.pt") # load a pretrained model (recommended for training)
model = YOLO("yolo26n.yaml").load("yolo26n.pt") # build from YAML and transfer weights
# Train the model
results = model.train(data="coco8.yaml", epochs=100, imgsz=640)Multi-GPU Training#
Multi-GPU training allows for more efficient utilization of available hardware resources by distributing the training load across multiple GPUs. This feature is available through both the Python API and the command-line interface. To enable multi-GPU training, specify the GPU device IDs you wish to use.
To train with 2 GPUs, CUDA devices 0 and 1 use the following commands. Expand to additional GPUs as required.
from ultralytics import YOLO
# Load a model
model = YOLO("yolo26n.pt") # load a pretrained model (recommended for training)
# Train the model with 2 GPUs
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=[0, 1])
# Train the model with the two most idle GPUs
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=[-1, -1])Multi-GPU training does not work on Windows with the official PyTorch wheels for torch>=2.4. Ultralytics launches DDP through torch.distributed.run, whose rendezvous step builds a TCPStore that has defaulted to the libuv backend since PyTorch 2.4, and the official Windows wheels are built without libuv. Training exits immediately with:
RuntimeError: use_libuv was requested but PyTorch was built without libuv support
Setting USE_LIBUV=0 does not resolve this, because the rendezvous constructs the TCPStore directly and that code path never reads the variable. Train on Linux or WSL2 to use multiple GPUs, or train on a single GPU with device=0 on Windows.
When you specify multiple devices (e.g., device=[0, 1]), Ultralytics internally spawns a new trainer instance and executes torch.distributed.run under the hood. This works seamlessly for standard CLI usage and unmodified Python scripts.
However, if your script contains custom components—such as a custom trainer, validator, dataset, or augmentation pipeline—these objects cannot be automatically serialized and transferred to the DDP subprocesses. In this case, you must launch your script directly with torch.distributed.run:
python -m torch.distributed.run --nproc_per_node 2 your_training_script.pyHuấn luyện GPU AMD sử dụng bản dựng PyTorch ROCm với cú pháp chuẩn device=0 hoặc device=cuda:0. Xem hướng dẫn tích hợp AMD để biết hướng dẫn cài đặt và trạng thái hỗ trợ MIGraphX, DirectML và Ryzen AI NPU hiện tại.
Intel GPU training uses device=xpu:0, or multiple XPU IDs with a PyTorch build that provides XCCL.
Huawei Ascend NPU Training#
Ultralytics hỗ trợ huấn luyện và xác thực trên NPU Huawei Ascend thông qua torch_npu. Cài đặt các phiên bản CANN, PyTorch và torch_npu tương thích lẫn nhau bằng cách làm theo hướng dẫn cài đặt Tiện ích mở rộng Ascend cho PyTorch, sau đó nạp môi trường CANN trước khi khởi động Ultralytics:
source /usr/local/Ascend/ascend-toolkit/set_env.shfrom ultralytics import YOLO
model = YOLO("yolo26n.pt")
# Train on one Ascend NPU
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="npu:0")
# Train across two Ascend NPUs with HCCL
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="npu:0,1")Các tính năng huấn luyện tiêu chuẩn, bao gồm AMP, xác thực, tạo checkpoint và khôi phục, sử dụng NPU đang hoạt động. AutoBatch khả dụng cho việc huấn luyện trên một NPU duy nhất, trong khi nhiều ID NPU khởi chạy huấn luyện phân tán thông qua HCCL. Xem hướng dẫn tích hợp Huawei Ascend để xuất model và triển khai sau khi huấn luyện.
Idle GPU Training#
Idle GPU Training enables automatic selection of the least utilized GPUs in multi-GPU systems, optimizing resource usage without manual GPU selection. This feature identifies available GPUs based on utilization metrics and VRAM availability.
To automatically select and use the most idle GPU(s) for training, use the -1 device parameter. This is particularly useful in shared computing environments or servers with multiple users.
from ultralytics import YOLO
# Load a model
model = YOLO("yolo26n.pt") # load a pretrained model (recommended for training)
# Train using the single most idle GPU
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=-1)
# Train using the two most idle GPUs
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device=[-1, -1])The auto-selection algorithm prioritizes GPUs with:
- Lower current utilization percentages
- Higher available memory (free VRAM)
- Lower temperature and power consumption
This feature is especially valuable in shared computing environments or when running multiple training jobs across different models. It automatically adapts to changing system conditions, ensuring optimal resource allocation without manual intervention.
Apple Silicon MPS Training#
With the support for Apple silicon chips integrated in the Ultralytics YOLO models, it's now possible to train your models on devices utilizing the powerful Metal Performance Shaders (MPS) framework. The MPS offers a high-performance way of executing computation and image processing tasks on Apple's custom silicon.
To enable training on Apple silicon chips, you should specify 'mps' as your device when initiating the training process. Below is an example of how you could do this in Python and via the command line:
from ultralytics import YOLO
# Load a model
model = YOLO("yolo26n.pt") # load a pretrained model (recommended for training)
# Train the model with MPS
results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="mps")While leveraging the computational power of the Apple silicon chips, this enables more efficient processing of the training tasks. For more detailed guidance and advanced configuration options, please refer to the PyTorch MPS documentation.
Resuming Interrupted Trainings#
Resuming training from a previously saved state is a crucial feature when working with deep learning models. This can come in handy in various scenarios, like when the training process has been unexpectedly interrupted, or when you wish to continue training a model with new data or for more epochs.
Khi tiếp tục quá trình huấn luyện, Ultralytics YOLO tải trọng số từ model đã lưu gần nhất và cũng khôi phục trạng thái bộ tối ưu hóa, bộ lập lịch learning rate, số epoch và dataset. Điều này cho phép bạn tiếp tục quá trình huấn luyện một cách liền mạch từ điểm dừng trước đó. Truyền một data= rõ ràng bên cạnh resume để tiếp tục trên một dataset khác thay vì trên checkpoint.
You can easily resume training in Ultralytics YOLO by setting the resume argument to True when calling the train method, and specifying the path to the .pt file containing the partially trained model weights.
Below is an example of how to resume an interrupted training using Python and via the command line:
from ultralytics import YOLO
# Load a model
model = YOLO("path/to/last.pt") # load a partially trained model
# Resume training
results = model.train(resume=True)By setting resume=True, the train function will continue training from where it left off, using the state stored in the 'path/to/last.pt' file. If the resume argument is omitted or set to False, the train function will start a new training session.
Remember that checkpoints are saved at the end of every epoch by default, or at fixed intervals using the save_period argument, so you must complete at least 1 epoch to resume a training run.
Thiết lập Train#
The training settings for YOLO models encompass various hyperparameters and configurations used during the training process. These settings influence the model's performance, speed, and accuracy. Key training settings include batch size, learning rate, momentum, and weight decay. Additionally, the choice of optimizer, loss function, and training dataset composition can impact the training process. Careful tuning and experimentation with these settings are crucial for optimizing performance.
Optimizer MuSGD#
In YOLO26, MuSGD is a hybrid optimizer that combines standard SGD updates with Muon-style orthogonalized updates.
It is recommended for longer YOLO26 training runs and larger datasets, where orthogonalized Muon updates can help stabilize optimization.
Only 2D linear weights and 4D convolutional filters (reshaped to 2D) receive the Muon style update together with SGD, while all other parameters, such as batch normalization weights and bias terms, remain on standard SGD.
When optimizer=auto is used, Ultralytics automatically selects MuSGD for longer training runs (typically when iterations > 10000). For shorter runs, the trainer falls back to AdamW.
Example usage:
yolo train model=yolo26n.pt data=coco8.yaml optimizer=MuSGDSee the implementation in ultralytics/optim/muon.py and the optimizer auto-selection logic in BaseTrainer.build_optimizer.
| Đối số | Kiểu | Mặc định | Mô tả |
|---|---|---|---|
model | str | None | Chỉ định file model dùng để huấn luyện. Chấp nhận đường dẫn đến model pretrained .pt hoặc file cấu hình .yaml. Đây là tham số thiết yếu để định nghĩa cấu trúc model hoặc khởi tạo trọng số. |
data | str | None | Đường dẫn đến YAML của dataset (ví dụ: coco8.yaml), chứa đường dẫn đến dữ liệu huấn luyện và validation, tên class và số lượng class. Với bài toán phân loại, tham số này nhận thư mục dataset hoặc tên dataset tích hợp sẵn (ví dụ: imagenet10). |
epochs | int | 100 | Tổng số epoch huấn luyện. Mỗi epoch biểu thị một lượt duyệt hoàn chỉnh qua toàn bộ dataset. Việc điều chỉnh giá trị này có thể ảnh hưởng đến thời lượng huấn luyện và hiệu năng model. |
time | float | None | Thời gian huấn luyện tối đa tính bằng giờ. Nếu được thiết lập, tham số này ghi đè đối số epochs, cho phép tự động dừng huấn luyện sau khoảng thời gian được chỉ định. Hữu ích trong các kịch bản huấn luyện bị giới hạn thời gian. |
patience | int | 100 | Số epoch cần chờ khi không có cải thiện trong các metric validation trước khi dừng sớm quá trình huấn luyện. Giúp ngăn overfitting bằng cách dừng huấn luyện khi hiệu năng không còn cải thiện. |
batch | int hoặc float | 16 | Batch size, với ba mode: đặt dưới dạng số nguyên (ví dụ: batch=16), mode tự động sử dụng 60% bộ nhớ GPU (batch=-1) hoặc mode tự động với phân số mức sử dụng được chỉ định (batch=0.70). |
imgsz | int | 640 | Kích thước ảnh mục tiêu cho quá trình huấn luyện. Ảnh được resize thành hình vuông với các cạnh bằng giá trị được chỉ định (nếu rect=False), bảo toàn tỷ lệ khung hình đối với model YOLO nhưng không áp dụng cho RT-DETR. Ảnh hưởng đến độ chính xác của model và độ phức tạp tính toán. |
save | bool | True | Bật việc lưu checkpoint huấn luyện và trọng số model cuối cùng. Hữu ích để tiếp tục huấn luyện hoặc triển khai model. |
save_period | int | -1 | Tần suất lưu checkpoint model, được chỉ định theo epoch. Giá trị -1 sẽ tắt tính năng này. Hữu ích để lưu các model trung gian trong những phiên huấn luyện kéo dài. |
cache | bool | False | Bật caching ảnh dataset trong bộ nhớ (True/ram), trên ổ đĩa (disk) hoặc tắt caching (False). Tăng tốc huấn luyện bằng cách giảm I/O ổ đĩa, nhưng làm tăng mức sử dụng bộ nhớ. |
device | int hoặc str hoặc list | None | Chỉ định thiết bị tính toán cho quá trình huấn luyện: một GPU (device=0), nhiều GPU (device=[0,1]), CPU (device=cpu), MPS cho Apple silicon (device=mps), Huawei Ascend NPU (device=npu:0 hoặc device=npu:0,1), tự động chọn GPU đang rảnh (device=-1) hoặc nhiều GPU đang rảnh (device=[-1,-1]). |
workers | int | 8 | Số luồng worker để tải dữ liệu (trên mỗi RANK nếu huấn luyện Multi-GPU). Ảnh hưởng đến tốc độ tiền xử lý dữ liệu và đưa dữ liệu vào model, đặc biệt hữu ích trong các thiết lập multi-GPU. |
project | str | None | Tên thư mục project nơi lưu các đầu ra huấn luyện. Cho phép lưu trữ có tổ chức các thử nghiệm khác nhau. |
name | str | None | Tên lượt chạy huấn luyện. Được dùng để tạo thư mục con trong thư mục project, nơi lưu log và đầu ra huấn luyện. |
exist_ok | bool | False | Nếu là True, cho phép ghi đè thư mục project/name hiện có. Hữu ích cho việc thử nghiệm lặp lại mà không cần xóa thủ công các đầu ra trước đó. |
save_dir | str | None | Chỉ định chính xác thư mục nơi lưu đầu ra của lượt chạy, ghi đè tổ hợp project/name. Đường dẫn được sử dụng nguyên trạng mà không tự động tăng số, vì vậy các lượt chạy liên tiếp sẽ dùng lại cùng một thư mục. |
pretrained | bool hoặc str | True | Xác định có bắt đầu huấn luyện từ trọng số pretrained hay không. Có thể là giá trị boolean hoặc đường dẫn dạng chuỗi đến trọng số cần tải. pretrained=False huấn luyện từ trọng số được khởi tạo ngẫu nhiên trong khi vẫn giữ nguyên kiến trúc model. |
cls_remap | bool | True | Khi fine-tune trên nhiều dataset, sao chép các hàng của classification head pretrained vào model mới tại những vị trí có tên class trùng khớp, để các class giao nhau giữ lại bias đã học và cả trọng số khi độ rộng của head không thay đổi. Áp dụng bất kể số lượng class khác nhau hay giống nhau nhưng có thứ tự class khác. |
optimizer | str | 'auto' | Lựa chọn optimizer cho quá trình huấn luyện. Các tùy chọn bao gồm SGD, MuSGD, Adam, Adamax, AdamW, NAdam, RAdam, RMSProp hoặc auto để chọn AdamW hoặc MuSGD dựa trên số vòng lặp huấn luyện. Ảnh hưởng đến tốc độ hội tụ và độ ổn định. |
seed | int | 0 | Thiết lập random seed cho quá trình huấn luyện, đảm bảo khả năng tái lập kết quả giữa các lượt chạy với cùng cấu hình. |
deterministic | bool | True | Buộc sử dụng các thuật toán deterministic, đảm bảo khả năng tái lập nhưng có thể ảnh hưởng đến hiệu năng và tốc độ do hạn chế các thuật toán non-deterministic. |
verbose | bool | True | Bật đầu ra chi tiết trong quá trình huấn luyện, hiển thị progress bar, metric theo từng epoch và thông tin huấn luyện bổ sung trong console. |
single_cls | bool | False | Xem tất cả class trong dataset multi-class là một class duy nhất trong quá trình huấn luyện. Hữu ích cho các task phân loại nhị phân hoặc khi tập trung vào sự hiện diện của đối tượng thay vì phân loại. |
classes | list[int] | None | Chỉ định danh sách ID class dùng để huấn luyện. Hữu ích để lọc bỏ và chỉ tập trung vào một số class nhất định trong quá trình huấn luyện. |
rect | bool | False | Bật chiến lược padding tối thiểu—các ảnh trong một batch được padding tối thiểu để đạt kích thước chung, với cạnh dài nhất bằng imgsz. Có thể cải thiện hiệu quả và tốc độ nhưng có thể ảnh hưởng đến độ chính xác của model. |
multi_scale | float | 0.0 | Thay đổi ngẫu nhiên imgsz trong mỗi batch theo +/- multi_scale (ví dụ: 0.25 -> 0.75x đến 1.25x), làm tròn theo bội số stride của model; 0.0 tắt huấn luyện multi-scale. |
cos_lr | bool | False | Sử dụng scheduler learning rate cosine, điều chỉnh learning rate theo đường cong cosine qua các epoch. Giúp quản lý learning rate để đạt hội tụ tốt hơn. |
close_mosaic | int | 10 | Tắt data augmentation mosaic trong N epoch cuối để ổn định quá trình huấn luyện trước khi hoàn tất. Đặt thành 0 để tắt tính năng này. |
resume | bool | False | Tiếp tục huấn luyện từ checkpoint được lưu gần nhất. Tự động tải trọng số model, trạng thái optimizer và số epoch, cho phép tiếp tục huấn luyện liền mạch. |
amp | bool hoặc str | True | Thiết lập độ chính xác huấn luyện: True hoặc "fp16" sử dụng FP16, "bf16" sử dụng BF16 trên các thiết bị CUDA được hỗ trợ, còn False hoặc "fp32" sử dụng FP32. |
quantize | int hoặc str | None | Được đặt thành 8 (hoặc "int8") cho quá trình huấn luyện nhận biết lượng tử hóa (QAT) INT8, quá trình này tinh chỉnh với lượng tử hóa giả trong vòng lặp để trọng số chịu được việc xuất INT8. Xem Quantization-Aware Training. |
fraction | float, int hoặc list | 1.0 | Subset dataset dưới dạng tỷ lệ/số lượng hoặc danh sách [train, val, test]. 1 có nghĩa là toàn bộ split, các số nguyên lớn hơn 1 là số lượng ảnh, và chỉ mục test tùy chọn mới chấp nhận 0/0.0 với ý nghĩa không có dữ liệu. Các danh sách gồm hai phần tử vẫn giữ toàn bộ test. |
profile | bool | False | Bật profiling tốc độ ONNX và TensorRT trong quá trình huấn luyện, hữu ích để tối ưu hóa triển khai model. |
freeze | int hoặc list | None | Đóng băng N layer đầu tiên của model hoặc các layer cụ thể theo index hoặc tên module (23.cv2, không có model. ở đầu), làm giảm số lượng tham số có thể huấn luyện. Hữu ích cho fine-tuning hoặc transfer learning. |
lr0 | float | 0.01 | Learning rate ban đầu (tức là SGD=1E-2, Adam=1E-3). Việc điều chỉnh giá trị này rất quan trọng đối với quá trình tối ưu hóa, ảnh hưởng đến tốc độ cập nhật trọng số model. |
lrf | float | 0.01 | Learning rate cuối cùng dưới dạng phần của learning rate ban đầu = (lr0 * lrf), được sử dụng kết hợp với scheduler để điều chỉnh learning rate theo thời gian. |
momentum | float | 0.937 | Hệ số momentum cho SGD hoặc beta1 cho optimizer Adam, ảnh hưởng đến việc đưa các gradient trước đó vào lần cập nhật hiện tại. |
weight_decay | float | 0.0005 | Hạng tử regularization L2, phạt các trọng số lớn để ngăn overfitting. |
warmup_epochs | float | 3.0 | Số epoch warmup learning rate, tăng dần learning rate từ giá trị thấp lên learning rate ban đầu để ổn định quá trình huấn luyện ở giai đoạn đầu. |
warmup_momentum | float | 0.8 | Momentum ban đầu cho giai đoạn warmup, dần điều chỉnh đến momentum đã thiết lập trong suốt thời gian warmup. |
warmup_bias_lr | float | 0.1 | Learning rate cho các tham số bias trong giai đoạn warmup, giúp ổn định huấn luyện model ở các epoch đầu. Tự động đặt thành 0.0 theo optimizer='auto' mặc định, vì vậy hãy chỉ định rõ optimizer để sử dụng tham số này. |
distill_model | str | None | Đường dẫn đến checkpoint model teacher (ví dụ: yolo26x.pt) để knowledge distillation. Khi được thiết lập, model student được huấn luyện với một loss distillation bổ sung dưới sự hướng dẫn của teacher đã đóng băng. |
dis | float | 6.0 | Trọng số của loss distillation được thêm vào các loss detection tiêu chuẩn. Giá trị cao hơn làm tăng ảnh hưởng của hướng dẫn feature từ teacher. |
box | float | 7.5 | Trọng số của thành phần box loss trong hàm loss, ảnh hưởng đến mức độ tập trung vào việc dự đoán chính xác tọa độ bounding box. |
cls | float | 0.5 | Trọng số của classification loss trong tổng hàm loss, ảnh hưởng đến tầm quan trọng của việc dự đoán đúng class so với các thành phần khác. |
cls_pw | float | 0.0 | Lũy thừa dùng để gán trọng số class nhằm xử lý mất cân bằng class bằng tần suất class nghịch đảo. 0.0 tắt gán trọng số class, 1.0 áp dụng đầy đủ trọng số theo tần suất nghịch đảo. Các giá trị từ 0 đến 1 cung cấp mức gán trọng số một phần. |
dfl | float | 1.5 | Trọng số của hạng tử hồi quy khoảng cách box: distribution focal loss (DFL) khi detection head sử dụng reg_max > 1, hoặc L1 loss trên khoảng cách box đã chuẩn hóa trong YOLO26 không có DFL (reg_max: 1). |
pose | float | 12.0 | Trọng số của pose loss trong các model được huấn luyện cho ước tính pose, ảnh hưởng đến mức độ tập trung vào việc dự đoán chính xác keypoint pose. |
kobj | float | 1.0 | Trọng số của keypoint objectness loss trong các model ước tính pose, cân bằng độ tin cậy phát hiện với độ chính xác pose. |
rle | float | 1.0 | Trọng số của residual log-likelihood estimation loss trong các model ước tính pose, ảnh hưởng đến độ chính xác định vị keypoint. |
angle | float | 1.0 | Trọng số của angle loss trong các model obb, ảnh hưởng đến độ chính xác dự đoán góc của bounding box định hướng. |
dlog | float | 1.0 | Trọng số của loss scale-invariant logarithmic (SILog) trong các model ước tính độ sâu, là hạng tử chính chi phối độ chính xác độ sâu. |
dgrad | float | 0.5 | Trọng số của gradient loss trong các model ước tính độ sâu, phạt lỗi tại các biên độ sâu và khuyến khích ranh giới bề mặt sắc nét hơn. |
dlam | float | 1.0 | Hệ số tập trung vào phương sai của SILog loss trong các model ước tính độ sâu. 1.0 khiến loss hoàn toàn bất biến theo tỷ lệ, trong khi 0.0 rút gọn loss thành log-RMSE thuần. |
nbs | int | 64 | Batch size danh nghĩa dùng để chuẩn hóa loss. |
overlap_mask | bool | True | Xác định có gộp các mask đối tượng thành một mask duy nhất khi huấn luyện hay giữ riêng cho từng đối tượng. Khi bị chồng lấn, mask nhỏ hơn sẽ được phủ lên trên mask lớn hơn trong quá trình gộp. |
mask_ratio | int | 4 | Tỷ lệ downsample cho mask phân đoạn, ảnh hưởng đến độ phân giải của mask được sử dụng trong quá trình huấn luyện. |
dropout | float | 0.0 | Tỷ lệ dropout dùng để regularization trong các task phân loại, ngăn overfitting bằng cách ngẫu nhiên bỏ qua các unit trong quá trình huấn luyện. |
val | bool | True | Bật validation trong quá trình huấn luyện, cho phép đánh giá định kỳ hiệu năng model trên một dataset riêng. |
nms | bool, tùy chọn | None | Chọn phần đầu suy luận được sử dụng cho việc xác thực chu kỳ, lựa chọn điểm kiểm tra và dừng sớm. None hoặc True sử dụng một-nhiều với NMS; False sử dụng phần đầu không có NMS khi khả dụng. Cả hai phần đầu đều giữ lại tổn thất huấn luyện của chúng. |
plots | bool | True | Tạo và lưu các biểu đồ về metric training và validation, cũng như các ví dụ dự đoán, cung cấp thông tin trực quan về hiệu suất model và tiến trình học. |
compile | bool hoặc str | False | Bật biên dịch graph PyTorch 2.x torch.compile với backend='inductor'. Chấp nhận True → "default", False → tắt, hoặc một mode chuỗi như "default", "reduce-overhead", "max-autotune-no-cudagraphs". Nếu không được hỗ trợ, sẽ chuyển về eager mode kèm cảnh báo. |
channels_last | bool | None | Sử dụng định dạng bộ nhớ channels_last (NHWC) cho các phép tích chập trong quá trình huấn luyện. None tự động bật tính năng này trên CUDA với PyTorch 1.11 trở lên, ngoại trừ trên Windows, nơi tính năng này cho tốc độ chậm hơn. False tắt tính năng này và True yêu cầu rõ ràng tính năng này. PyTorch 1.10 trở xuống, CPU và MPS vẫn giữ định dạng NCHW theo mặc định. |
max_det | int | 300 | Số lượng đối tượng phát hiện tối đa trên mỗi ảnh trong quá trình huấn luyện và xác thực. Đối với detect, segment, pose và OBB, giá trị mặc định là 300 sẽ tự động tăng lên bằng số lượng đối tượng được gán nhãn lớn nhất trong tập train/val chỉ khi số lượng đó vượt quá 300. Các giá trị khác được giữ nguyên; việc vượt quá giới hạn sẽ kích hoạt cảnh báo. |
The batch argument can be configured in three ways:
- Fixed Batch Size: Set an integer value (e.g.,
batch=16), specifying the number of images per batch directly. - Auto Mode (60% GPU Memory): Use
batch=-1to automatically adjust batch size for approximately 60% CUDA memory utilization. - Auto Mode with Utilization Fraction: Set a fraction value (e.g.,
batch=0.70) to adjust batch size based on the specified fraction of GPU memory usage. - OOM Auto-Retry: If a CUDA out-of-memory error occurs during the first epoch, the trainer automatically halves the batch size and retries (up to 3 times). This only applies to single-GPU training; multi-GPU (DDP) training will raise the error immediately.
- Không tìm thấy cấu hình phù hợp: Nếu không có batch size ứng viên nào tạo ra profile có thể sử dụng, AutoBatch sẽ raise một
RuntimeErrorrõ ràng thay vì âm thầm chuyển về một giá trị mặc định không liên quan.
Augmentation Settings and Hyperparameters#
Augmentation techniques are essential for improving the robustness and performance of YOLO models by introducing variability into the training data, helping the model generalize better to unseen data. The following table outlines the purpose and effect of each augmentation argument:
| Đối số | Kiểu | Mặc định | Các Task được hỗ trợ | Phạm vi | Mô tả |
|---|---|---|---|---|---|
hsv_h | float | 0.015 | detect, segment, semantic, depth, classify, pose, obb | 0.0 - 1.0 | Điều chỉnh hue của ảnh theo một phần của color wheel, tạo ra sự biến thiên màu sắc. Giúp model tổng quát hóa trong các điều kiện ánh sáng khác nhau. Đối với classify, tùy chọn này chỉ áp dụng khi auto_augment=None. |
hsv_s | float | 0.7 | detect, segment, semantic, depth, classify, pose, obb | 0.0 - 1.0 | Thay đổi saturation của ảnh theo một tỷ lệ, ảnh hưởng đến cường độ màu. Hữu ích để mô phỏng các điều kiện môi trường khác nhau. Đối với classify, tùy chọn này chỉ áp dụng khi auto_augment=None. |
hsv_v | float | 0.4 | detect, segment, semantic, depth, classify, pose, obb | 0.0 - 1.0 | Điều chỉnh value (độ sáng) của ảnh theo một tỷ lệ, giúp model hoạt động tốt trong nhiều điều kiện ánh sáng. Đối với classify, tùy chọn này chỉ áp dụng khi auto_augment=None. |
degrees | float | 0 | detect, segment, semantic, depth, pose, obb | 0.0 - 180 | Xoay ngẫu nhiên ảnh trong phạm vi số độ được chỉ định, cải thiện khả năng nhận diện đối tượng ở nhiều hướng khác nhau. |
translate | float | 0.1 | detect, segment, semantic, depth, pose, obb | 0.0 - 1.0 | Dịch ảnh theo chiều ngang và chiều dọc theo một phần kích thước ảnh, hỗ trợ model học cách phát hiện các đối tượng chỉ hiển thị một phần. |
scale | float | tuple | 0.5 | detect, segment, semantic, depth, classify, pose, obb | 0 - 1, hoặc tuple (min, max) được chỉ định rõ (không dành cho classify) | Scale ảnh theo hệ số gain, mô phỏng các đối tượng ở những khoảng cách khác nhau so với camera. |
shear | float | 0 | detect, segment, semantic, depth, pose, obb | -180 - +180 | Shear ảnh theo số độ được chỉ định, mô phỏng hiệu ứng khi quan sát đối tượng từ các góc khác nhau. |
perspective | float | 0 | detect, segment, semantic, depth, pose, obb | 0.0 - 0.001 | Áp dụng phép biến đổi perspective ngẫu nhiên cho ảnh, nâng cao khả năng nhận biết đối tượng trong không gian 3D của model. |
flipud | float | 0 | detect, segment, semantic, depth, classify, pose, obb | 0.0 - 1.0 | Lật ngược ảnh theo xác suất được chỉ định, tăng độ biến thiên của dữ liệu mà không ảnh hưởng đến đặc điểm của đối tượng. |
fliplr | float | 0.5 | detect, segment, semantic, depth, classify, pose, obb | 0.0 - 1.0 | Lật ảnh từ trái sang phải theo xác suất được chỉ định, hữu ích cho việc học các đối tượng đối xứng và tăng tính đa dạng của dataset. |
bgr | float | 0 | detect, segment, semantic, depth, pose, obb | 0.0 - 1.0 | Đảo các channel của ảnh từ RGB sang BGR theo xác suất được chỉ định, hữu ích để tăng độ robust trước việc sắp xếp channel không chính xác. |
mosaic | float | 1 | detect, segment, semantic, pose, obb | 0.0 - 1.0 | Kết hợp bốn ảnh training thành một, mô phỏng các cách bố cục cảnh và tương tác đối tượng khác nhau. Đặc biệt hiệu quả cho việc hiểu các cảnh phức tạp. |
mixup | float | 0 | detect, segment, semantic, pose, obb | 0.0 - 1.0 | Trộn hai ảnh và nhãn của chúng để tạo thành một ảnh tổng hợp. Cải thiện khả năng tổng quát hóa của model bằng cách đưa vào nhiễu nhãn và sự biến thiên trực quan. |
cutmix | float | 0 | detect, segment, pose, obb | 0.0 - 1.0 | Kết hợp các phần của hai ảnh, tạo ra sự pha trộn từng phần trong khi vẫn duy trì các vùng riêng biệt. Cải thiện độ robust của model bằng cách tạo ra các tình huống bị che khuất. |
copy_paste | float | 0 | segment, obb | 0.0 - 1.0 | Tỷ lệ các đối tượng đủ điều kiện được dán; flip phản chiếu chúng trong ảnh, trong khi mixup cũng sử dụng giá trị này làm xác suất áp dụng giữa các ảnh. |
copy_paste_mode | str | flip | segment, obb | - | Chỉ định chiến lược copy-paste cần sử dụng. Các tùy chọn gồm 'flip' và 'mixup'. |
auto_augment | str | randaugment | classify | - | Áp dụng policy augmentation được định nghĩa sẵn ('randaugment', 'autoaugment' hoặc 'augmix') để cải thiện performance của model thông qua sự đa dạng về hình ảnh. |
erasing | float | 0.4 | classify | 0.0 - 1.0 | Xóa ngẫu nhiên các vùng trong ảnh trong quá trình training để khuyến khích model tập trung vào những đặc trưng ít rõ ràng hơn. |
augmentations | list | None | detect, segment, semantic, depth, pose, obb | - | Các phép biến đổi Albumentations tùy chỉnh cho data augmentation nâng cao (chỉ dành cho Python API). Nhận một list các object transform cho những nhu cầu augmentation chuyên biệt. |
These settings can be adjusted to meet the specific requirements of the dataset and task at hand. Experimenting with different values can help find the optimal augmentation strategy that leads to the best model performance.
For more information about training augmentation operations, see the reference section.
Ghi log#
Các chỉ số huấn luyện, biểu đồ và điểm kiểm tra (checkpoint) luôn được ghi vào thư mục chạy, đồng thời Ultralytics cũng truyền phát chúng tới bất kỳ trình theo dõi thí nghiệm nào bạn đã cài đặt và bật: Comet, ClearML, TensorBoard, MLflow, Weights & Biases và DVCLive. Mỗi trình ghi nhật ký được bật tắt thông qua cài đặt Ultralytics, ví dụ như yolo settings tensorboard=True. Ba thiết lập phổ biến nhất được hiển thị bên dưới.
Comet#
Comet is a platform that allows data scientists and developers to track, compare, explain and optimize experiments and models. It provides functionalities such as real-time metrics, code diffs, and hyperparameters tracking.
To use Comet:
# pip install comet_ml
import comet_ml
comet_ml.init()Remember to sign in to your Comet account on their website and get your API key. You will need to add this to your environment variables or your script to log your experiments.
ClearML#
ClearML is an open-source platform that automates tracking of experiments and helps with efficient sharing of resources. It is designed to help teams manage, execute, and reproduce their ML work more efficiently.
To use ClearML:
# pip install clearml
import clearml
clearml.browser_login()After running this script, you will need to sign in to your ClearML account on the browser and authenticate your session.
TensorBoard#
TensorBoard is a visualization toolkit for TensorFlow. It allows you to visualize your TensorFlow graph, plot quantitative metrics about the execution of your graph, and show additional data like images that pass through it.
To use TensorBoard in Google Colab:
%load_ext tensorboard
tensorboard --logdir ultralytics/runs # replace with 'runs' directoryTo use TensorBoard locally run the below command and view results at localhost:6006.
tensorboard --logdir ultralytics/runs # replace with 'runs' directoryThis will load TensorBoard and direct it to the directory where your training logs are saved.
After setting up your logger, you can then proceed with your model training. All training metrics will be automatically logged in your chosen platform, and you can access these logs to monitor your model's performance over time, compare different models, and identify areas for improvement.
Tiếp theo là gì?#
Validate your trained model against held-out data to check its real-world accuracy, then export it to ONNX, TensorRT, or another deployment format. Training on your own data instead of COCO8? Format it first with the Datasets guide.
FAQ#
Yes. Ultralytics Platform cloud training includes free credits to get started. Upload your dataset, select a model and GPU, and train directly from the browser.
To train an object detection model using Ultralytics YOLO26, you can either use the Python API or the CLI. Below is an example for both:
Single-GPU and CPU Training Examplefrom ultralytics import YOLO # Load a model model = YOLO("yolo26n.pt") # load a pretrained model (recommended for training) # Train the model results = model.train(data="coco8.yaml", epochs=100, imgsz=640)For more details, refer to the Train Settings section.
The key features of Ultralytics YOLO26's Train mode include:
- Automatic Dataset Download: Automatically downloads standard datasets like COCO, VOC, and ImageNet.
- Multi-GPU Support: Scale training across multiple GPUs for faster processing.
- Hyperparameter Configuration: Customize hyperparameters through YAML files or CLI arguments.
- Visualization and Monitoring: Real-time tracking of training metrics for better insights.
These features make training efficient and customizable to your needs. For more details, see the Key Features of Train Mode section.
Để tiếp tục huấn luyện từ một phiên bị gián đoạn, hãy đặt tham số
resumethànhTruevà chỉ định đường dẫn đến điểm kiểm tra được lưu gần nhất.Resume Training Examplefrom ultralytics import YOLO # Load the partially trained model model = YOLO("path/to/last.pt") # Resume training results = model.train(resume=True)Xem phần Tiếp Tục Huấn Luyện Bị Gián Đoạn để biết thêm thông tin.
Sự mất cân bằng lớp xảy ra khi một số lớp có ít mẫu hơn đáng kể so với các lớp khác trong dữ liệu huấn luyện của bạn. Điều này có thể khiến model hoạt động kém hiệu quả trên các lớp hiếm. Ultralytics YOLO hỗ trợ trọng số lớp thông qua tham số
cls_pwđể giải quyết vấn đề này.Tham số
cls_pwđiều khiển mức độ trọng số lớp dựa trên tần suất lớp nghịch đảo:cls_pw=0.0(mặc định): Vô hiệu hóa trọng số lớpcls_pw=1.0: Áp dụng trọng số tần suất nghịch đảo hoàn toàn- Giá trị giữa
0.0và1.0: Cung cấp trọng số một phần cho tình trạng mất cân bằng vừa phải
Trọng số lớp được tính toán dưới dạng
(1.0 / class_counts) ^ cls_pwvà được chuẩn hóa sao cho giá trị trung bình bằng 1.0.Huấn Luyện trên Tập Dữ Liệu Mất Cân Bằngfrom ultralytics import YOLO # Load a pretrained model model = YOLO("yolo26n.pt") # Train with full class weighting for severely imbalanced data results = model.train(data="custom.yaml", epochs=100, imgsz=640, cls_pw=1.0) # Or use partial weighting (0.25) for moderate imbalance results = model.train(data="custom.yaml", epochs=100, imgsz=640, cls_pw=0.25)MẹoBắt đầu với
cls_pw=0.25cho các tập dữ liệu mất cân bằng vừa phải và tăng lên1.0nếu các lớp hiếm vẫn kém hiệu quả. Bạn có thể kiểm tra trọng số lớp đã tính toán trong nhật ký huấn luyện để xác minh phân phối trọng số.Có, Ultralytics YOLO26 hỗ trợ huấn luyện trên chip Apple silicon tận dụng framework MPS. Chỉ định 'mps' làm thiết bị huấn luyện của bạn.
MPS Training Examplefrom ultralytics import YOLO # Load a pretrained model model = YOLO("yolo26n.pt") # Train the model on Apple silicon chip (M1/M2/M3/M4) results = model.train(data="coco8.yaml", epochs=100, imgsz=640, device="mps")Để biết thêm chi tiết, hãy tham khảo phần Huấn Luyện MPS trên Apple Silicon.
Ultralytics YOLO26 cho phép bạn định cấu hình nhiều cài đặt huấn luyện khác nhau như kích thước batch, tốc độ học, số epoch và nhiều cài đặt khác thông qua các tham số. Dưới đây là tổng quan nhanh:
Đối số Mặc định Mô tả modelNoneĐường dẫn đến tệp model để huấn luyện. dataNoneĐường dẫn đến YAML tập dữ liệu (ví dụ: coco8.yaml), hoặc thư mục hoặc tên tập dữ liệu (ví dụ:imagenet10) cho phân loại.epochs100Tổng số epoch huấn luyện. batch16Kích thước batch, có thể điều chỉnh dưới dạng số nguyên hoặc chế độ tự động. imgsz640Kích thước hình ảnh mục tiêu để huấn luyện. deviceNone(Các) thiết bị tính toán để huấn luyện như cpu,0,0,1hoặcmps.saveTrueCho phép lưu các điểm kiểm tra huấn luyện và trọng số model cuối cùng. Để có hướng dẫn chi tiết về cài đặt huấn luyện, hãy xem phần Cài Đặt Huấn Luyện.