Ultralytics YOLO27:
Get Started

Tùy chỉnh nâng cao#

Cả giao diện dòng lệnh và giao diện Python của Ultralytics YOLO đều là các lớp trừu tượng cấp cao được xây dựng trên các bộ thực thi 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 engine cho nhu cầu cụ thể của bạn.



Xem: Làm chủ Ultralytics YOLO: Tùy chỉnh nâng cao
Mẹo

Để xem các ví dụ thực tế về những tùy chỉnh trainer thường gặp — metric tùy chỉnh, loss có trọng số theo class, lưu model, đóng băng backbone và learning rate riêng cho từng layer — hãy xem hướng dẫn Tùy chỉnh Trainer.

BaseTrainer#

Class BaseTrainer cung cấp quy trình training tổng quát có thể điều chỉnh cho nhiều tác vụ. Hãy tùy chỉnh 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 training.
  • get_dataloader(dataset_path, batch_size, rank, mode): Xây dựng dataloader.

Để biết thêm chi tiết và xem mã nguồn, hãy tham khảo tài liệu tham khảo BaseTrainer.

DetectionTrainer#

Dưới đâ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  # Lấy model tốt nhất

Tùy chỉnh DetectionTrainer#

Để training model phát hiện tùy chỉnh chưa được hỗ trợ trực tiếp, hãy ghi đè chức năng hiện có của get_model:

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 trainer thêm bằng cách sửa đổi hàm loss hoặc thêm callback chạy ở cuối mỗi epoch, chẳng hạn để ghi log hoặc tải lên weights mới nhất. Dưới đây là ví dụ:

from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.nn.tasks import DetectionModel

class MyCustomModel(DetectionModel):
    def init_criterion(self):
        """Initializes a custom loss function for the model."""

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 ghi log weights của model
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)  # Bổ sung vào các callback hiện có
trainer.train()

Để biết thêm thông tin về các sự kiện kích hoạt callback và điểm truy cập, hãy xem Hướng dẫn về 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 theo cách 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 Trainer tùy chỉnh#

Class model YOLO cung cấp wrapper cấp cao cho các class Trainer. Bạn có thể tận dụng kiến trúc này để linh hoạt hơn trong quy trình machine learning:

from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer

# Tạo trainer tùy chỉnh
class MyCustomTrainer(DetectionTrainer):
    def get_model(self, cfg=None, weights=None, verbose=True):
        """Custom code implementation."""

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

# Training bằng trainer tùy chỉnh
results = model.train(trainer=MyCustomTrainer, data="coco8.yaml", epochs=3)

Cách tiếp cận này giúp bạn duy trì sự đơn giản của giao diện YOLO, đồng thời tùy chỉnh quy trình training bên dưới để đáp ứng các yêu cầu cụ thể.

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

  • Tùy chỉnh DetectionTrainer cho các tác vụ cụ thể bằng cách ghi đè các phương thức để điều chỉnh theo model và dataloader tùy chỉnh của bạn. Bắt đầu bằng cách kế thừa DetectionTrainer và định nghĩa lại các phương thức như get_model để triển khai chức năng tùy chỉnh. Dưới đây là 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  # Lấy model tốt nhất

    Để 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 về Callbacks.

  • BaseTrainer là nền tảng cho các quy trình training và có thể tùy chỉnh cho nhiều tác vụ bằng cách ghi đè các phương thức tổng quát. Các thành phần chính gồm:

    • get_model(cfg, weights): Xây dựng model cần training.
    • get_dataloader(dataset_path, batch_size, rank, mode): Xây dựng dataloader.
    • preprocess_batch(): Xử lý tiền xử lý batch trước lượt forward của model.
    • set_model_attributes(): Thiết lập thuộc tính model dựa trên thông tin dataset.
    • get_validator(): Trả về validator để đánh giá model.

    Để biết thêm chi tiết về tùy chỉnh và mã nguồn, hãy tham khảo tài liệu tham khảo BaseTrainer.

  • Thêm callback để theo dõi và điều chỉnh quy trình training trong DetectionTrainer. Dưới đây là cách thêm callback để ghi log weights của model sau mỗi epoch training:

    from ultralytics.models.yolo.detect import DetectionTrainer
    
    # Callback ghi log weights của model
    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)  # Bổ sung vào các callback hiện có
    trainer.train()

    Để biết thêm chi tiết về các sự kiện callback và điểm truy cập, hãy tham khảo Hướng dẫn về Callbacks.

  • Ultralytics YOLO cung cấp lớp trừu tượng cấp cao trên các bộ thực thi engine mạnh mẽ, phù hợp cho phát triển và tùy chỉnh nhanh chóng. Các lợi ích chính gồm:

    • Dễ sử dụng: Giao diện dòng lệnh và Python đều giúp đơn giản hóa các tác vụ phức tạp.
    • Hiệu năng: Được tối ưu 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.
    • Khả năng tùy chỉnh: Dễ dàng mở rộng để hỗ trợ model, hàm loss và dataloader tùy chỉnh.
    • Tính mô-đun: Có thể sửa đổi riêng từng thành phần 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 khả năng của YOLO bằng cách khám phá trang Ultralytics YOLO chính.

  • Có, DetectionTrainer rất linh hoạt và có thể tùy chỉnh cho các model không theo tiêu chuẩn. Hãy kế thừa DetectionTrainer và ghi đè các phương thức để đáp ứng nhu cầu cụ thể của model. Dưới đây là 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()

    Để xem hướng dẫn và ví dụ đầy đủ, hãy tham khảo tài liệu tham khảo DetectionTrainer.

Bình luận