Ultralytics YOLO27:

Tùy chỉnh Nâng cao#

Cả giao diện dòng lệnh và Python của Ultralytics YOLO đều là các abstraction cấp cao được xây dựng trên các engine executor 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
Mẹo

Để có các ví dụ thực tế về các tùy chỉnh trainer phổ biến — custom metric, hàm mất mát có trọng số theo lớp, lưu model, đóng băng backbone và tốc độ học theo từng layer — hãy xem hướng dẫn Tùy chỉnh Trainer.

BaseTrainer#

Lớp BaseTrainer cung cấp một quy trình huấn luyện tổng quát có thể thích ứng với nhiều tác vụ khác nhau. Tùy chỉnh lớp này bằng cách ghi đè các hàm hoặc thao tác cụ thể, đồng thời tuân thủ các định dạng bắt buộc. Ví dụ: tích hợp model và dataloader tùy chỉnh 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 DetectionTrainer của Ultralytics YOLO:

from ultralytics.models.yolo.detect import DetectionTrainer

trainer = DetectionTrainer(overrides={...})
trainer.train()
trained_model = trainer.best  # Get the best model

Tùy chỉnh DetectionTrainer#

Để huấn luyện một detection model tùy chỉnh không được hỗ trợ trực tiếp, hãy nạp chồng (overload) chức 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 mất mát hoặc thêm một 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à các điểm 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ư ValidatorsPredictors theo cách tương tự. Để biết thêm thông tin, hãy tham khảo tài liệu cho ValidatorsPredictors.

Sử dụng YOLO với Custom Trainer#

Model class YOLO cung cấp một trình bao bọc (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 lớn hơn trong các quy trình máy học 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ì sự đơn giản của giao diện YOLO đồng thời tùy chỉnh quá trình huấn luyện cơ bản cho phù hợp với các yêu cầu cụ thể của bạn.

FAQ#

  • Tùy chỉnh DetectionTrainer cho các tác vụ cụ thể bằng cách ghi đè các phương thức của lớp để thích ứng với model và dataloader tùy chỉnh của bạn. Bắt đầu bằng cách kế thừa từ DetectionTrainer và định nghĩa lại các phương thức như get_model để triển khai các chức năng tùy chỉnh. 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 mất mát hoặc thêm một callback, hãy tham khảo Hướng dẫn Callbacks.

  • BaseTrainer 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 tổng quát. 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ý trước batch trước khi model thực hiện forward pass.
    • set_model_attributes(): Thiết lập các thuộc tính của model dựa trên thông tin tập dữ liệu.
    • 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 để theo dõi và sửa đổi quá trình huấn luyện trong DetectionTrainer. Dưới đây là cách thêm callback để ghi nhật ký 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à các điểm entry point, hãy tham khảo Hướng dẫn Callbacks.

  • Ultralytics YOLO cung cấp một abstraction cấp cao đối với các engine executor mạnh mẽ, làm cho nó trở nên lý tưởng cho việc phát triển và tùy chỉnh nhanh chóng. 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à nhiều ứng dụng AI thị giác khác nhau.
    • Tùy chỉnh: Dễ dàng mở rộng cho các model tùy chỉnh, hàm mất mát 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 Ultralytics YOLO chính.

  • Có, DetectionTrainer có tính linh hoạt cao và có thể tùy chỉnh cho các model không tiêu chuẩn. Kế thừa từ DetectionTrainer và 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.

Bình luận