Tùy chỉnh Nâng cao#
Cả giao diện dòng lệnh Ultralytics YOLO và Python đều là các abstraction cấp cao được xây dựng dựa trên các executor của engine cơ sở. Hướng dẫn này tập trung vào engine Trainer, giải thích cách tùy chỉnh nó cho các nhu cầu cụ thể của bạn.
Watch: Mastering Ultralytics YOLO: Advanced Customization
Để có các ví dụ thực tế về các tùy chỉnh trainer phổ biến — custom metric, loss có trọng số theo class, lưu model, đóng băng backbone và learning rate theo từng layer — hãy xem hướng dẫn Customizing Trainer.
BaseTrainer#
Class BaseTrainer cung cấp một quy trình huấn luyện chung có thể thích ứng với nhiều tác vụ khác nhau. Tùy chỉnh nó bằng cách ghi đè các hàm hoặc thao tác cụ thể trong khi tuân thủ các định dạng được yêu cầu. Ví dụ, tích hợp model và dataloader custom của riêng bạn bằng cách ghi đè các hàm sau:
get_model(cfg, weights): Xây dựng model cần huấn luyện.get_dataloader(): Xây dựng dataloader.
Để biết thêm chi tiết và mã nguồn, hãy xem Tài liệu tham khảo BaseTrainer.
DetectionTrainer#
Sau đây là cách sử dụng và tùy chỉnh Ultralytics YOLO DetectionTrainer:
from ultralytics.models.yolo.detect import DetectionTrainer
trainer = DetectionTrainer(overrides={...})
trainer.train()
trained_model = trainer.best # Get the best modelTùy chỉnh DetectionTrainer#
Để huấn luyện một detection model custom không được hỗ trợ trực tiếp, hãy nạp chồng (overload) tính năng get_model hiện có:
from ultralytics.models.yolo.detect import DetectionTrainer
class CustomTrainer(DetectionTrainer):
def get_model(self, cfg=None, weights=None, verbose=True):
"""Loads a custom detection model given configuration and weight files."""
trainer = CustomTrainer(overrides={...})
trainer.train()Tùy chỉnh thêm trainer bằng cách sửa đổi hàm loss hoặc thêm callback để tải model lên Google Drive sau mỗi 10 epoch. Dưới đây là một ví dụ:
from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.nn.tasks import DetectionModel
class MyCustomModel(DetectionModel):
def init_criterion(self):
"""Initializes the loss function and adds a callback for uploading the model to Google Drive every 10 epochs."""
class CustomTrainer(DetectionTrainer):
def get_model(self, cfg=None, weights=None, verbose=True):
"""Returns a customized detection model instance configured with specified config and weights."""
return MyCustomModel(...)
# Callback to upload model weights
def log_model(trainer):
"""Logs the path of the last model weight used by the trainer."""
last_weight_path = trainer.last
print(last_weight_path)
trainer = CustomTrainer(overrides={...})
trainer.add_callback("on_train_epoch_end", log_model) # Adds to existing callbacks
trainer.train()Để biết thêm thông tin về các sự kiện kích hoạt callback và điểm nhập (entry point), hãy xem Hướng dẫn Callbacks.
Các Thành phần Engine Khác#
Tùy chỉnh các thành phần khác như Validators và Predictors tương tự. Để biết thêm thông tin, hãy tham khảo tài liệu về Validators và Predictors.
Sử dụng YOLO với Custom Trainer#
Class model YOLO cung cấp một wrapper cấp cao cho các Trainer class. Bạn có thể tận dụng kiến trúc này để có độ linh hoạt cao hơn trong các workflow machine learning của mình:
from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer
# Create a custom trainer
class MyCustomTrainer(DetectionTrainer):
def get_model(self, cfg=None, weights=None, verbose=True):
"""Custom code implementation."""
# Initialize YOLO model
model = YOLO("yolo26n.pt")
# Train with custom trainer
results = model.train(trainer=MyCustomTrainer, data="coco8.yaml", epochs=3)Phương pháp này cho phép bạn duy trì tính đơn giản của giao diện YOLO đồng thời tùy chỉnh quy trình huấn luyện cơ bản để phù hợp với các yêu cầu cụ thể của bạn.
Câu hỏi thường gặp#
Tùy chỉnh
DetectionTrainercho các tác vụ cụ thể bằng cách ghi đè các phương thức của nó để thích ứng với model và dataloader custom của bạn. Bắt đầu bằng cách kế thừa từDetectionTrainervà định nghĩa lại các phương thức nhưget_modelđể triển khai các chức năng custom. Dưới đây là một ví dụ:from ultralytics.models.yolo.detect import DetectionTrainer class CustomTrainer(DetectionTrainer): def get_model(self, cfg=None, weights=None, verbose=True): """Loads a custom detection model given configuration and weight files.""" trainer = CustomTrainer(overrides={...}) trainer.train() trained_model = trainer.best # Get the best modelĐể tùy chỉnh thêm, chẳng hạn như thay đổi hàm loss hoặc thêm callback, hãy tham khảo Hướng dẫn Callbacks.
BaseTrainerđóng vai trò là nền tảng cho các quy trình huấn luyện, có thể tùy chỉnh cho nhiều tác vụ khác nhau bằng cách ghi đè các phương thức chung của nó. Các thành phần chính bao gồm:get_model(cfg, weights): Xây dựng model cần huấn luyện.get_dataloader(): Xây dựng dataloader.preprocess_batch(): Xử lý tiền xử lý batch trước khi thực hiện forward pass của model.set_model_attributes(): Thiết lập các thuộc tính của model dựa trên thông tin dataset.get_validator(): Trả về một validator để đánh giá model.
Để biết thêm chi tiết về tùy chỉnh và mã nguồn, hãy xem Tài liệu tham khảo
BaseTrainer.Thêm các callback để giám sát và sửa đổi quá trình huấn luyện trong
DetectionTrainer. Dưới đây là cách thêm một callback để ghi log trọng số model sau mỗi epoch huấn luyện:from ultralytics.models.yolo.detect import DetectionTrainer # Callback to upload model weights def log_model(trainer): """Logs the path of the last model weight used by the trainer.""" last_weight_path = trainer.last print(last_weight_path) trainer = DetectionTrainer(overrides={...}) trainer.add_callback("on_train_epoch_end", log_model) # Adds to existing callbacks trainer.train()Để biết thêm chi tiết về các sự kiện callback và điểm nhập, hãy tham khảo Hướng dẫn Callbacks.
Ultralytics YOLO cung cấp một lớp trừu tượng cấp cao trên các bộ thực thi engine mạnh mẽ, lý tưởng cho việc phát triển nhanh và tùy chỉnh. Các lợi ích chính bao gồm:
- Dễ sử dụng: Cả giao diện dòng lệnh và Python đều đơn giản hóa các tác vụ phức tạp.
- Hiệu năng: Được tối ưu hóa cho phát hiện đối tượng thời gian thực và các ứng dụng vision AI khác nhau.
- Tùy chỉnh: Dễ dàng mở rộng cho các model custom, hàm loss và dataloader.
- Tính mô-đun: Các thành phần có thể được sửa đổi độc lập mà không ảnh hưởng đến toàn bộ pipeline.
- Tích hợp: Hoạt động liền mạch với các framework và công cụ phổ biến trong hệ sinh thái ML.
Tìm hiểu thêm về các tính năng của YOLO bằng cách khám phá trang chính Ultralytics YOLO.
Có,
DetectionTrainercó độ linh hoạt cao và có thể tùy chỉnh cho các model phi tiêu chuẩn. Kế thừa từDetectionTrainervà nạp chồng các phương thức để hỗ trợ các nhu cầu cụ thể của model bạn. Dưới đây là một ví dụ đơn giản:from ultralytics.models.yolo.detect import DetectionTrainer class CustomDetectionTrainer(DetectionTrainer): def get_model(self, cfg=None, weights=None, verbose=True): """Loads a custom detection model.""" trainer = CustomDetectionTrainer(overrides={...}) trainer.train()Để có các hướng dẫn và ví dụ toàn diện, hãy xem lại Tài liệu tham khảo
DetectionTrainer.