Tùy chỉnh Nâng cao#
Cả giao diện dòng lệnh Ultralytics YOLO và Python đều là các lớp trừu tượng bậc cao được xây dựng dựa 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 nó cho các nhu cầu cụ thể của bạn.
Watch: Mastering Ultralytics YOLO: Advanced Customization
Để xem các ví dụ thực tế về các tùy chỉnh trainer phổ biến — số liệu tùy chỉnh, 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 chung có thể thích ứng cho 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 vẫn 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 BaseTrainer Reference.
DetectionTrainer#
Dưới đâ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 model phát hiện 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 cứ sau 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 truy cập, hãy xem Hướng dẫn Callback.
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 Custom Trainer#
Lớp model YOLO cung cấp một trình bao bọc (wrapper) cấp cao cho các lớp Trainer. Bạn có thể tận dụng kiến trúc này để có độ linh hoạt cao hơn trong các quy trình làm việc học máy 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#
Làm thế nào để tùy chỉnh Ultralytics YOLO DetectionTrainer cho các tác vụ cụ thể?#
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 nó để 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 để thực hiện 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 Callback.
Các thành phần chính của BaseTrainer trong Ultralytics YOLO là gì?#
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 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ề cách tùy chỉnh và mã nguồn, hãy xem BaseTrainer Reference.
Làm cách nào để thêm callback vào Ultralytics YOLO DetectionTrainer?#
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 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 truy cập, hãy tham khảo Hướng dẫn Callback.
Tại sao tôi nên sử dụng Ultralytics YOLO để huấn luyện model?#
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 suất: Đượ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.
Tôi có thể sử dụng Ultralytics YOLO DetectionTrainer cho các model không tiêu chuẩn không?#
Có, DetectionTrainer rất linh hoạt 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ó hướng dẫn chi tiết và các ví dụ, hãy xem lại DetectionTrainer Reference.