Bắt đầu

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 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 và giải thích cách tùy chỉnh engine theo nhu cầu cụ thể.



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
  • 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à sửa đổi quá trình huấn luyện trong DetectionTrainer. Sau đâ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 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, rất phù hợp cho quá trình phát triển và tùy chỉnh nhanh. 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.
    • Tùy chỉnh: Có thể mở rộng bằng 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 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 có thể được tùy chỉnh cho các model không theo tiêu chuẩn. Kế thừa từ DetectionTrainer và ghi đè các method để đáp ứng nhu cầu cụ thể của model. Sau đâ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ận10

Đặt câu hỏi, chia sẻ kết quả hoặc giúp đỡ người khác.

  1. UltralyticsAssistantGitHubUltralytics

    👋 Hello, thank you for your interest in Ultralytics 🚀! We recommend visiting the Docs for new users, where you can explore numerous Python and CLI usage examples. Many common questions may already be answered there, including step-by-step guides tailored for different tasks.

    If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug the issue.

    If you have a custom training ❓ Question, please include as much information as possible, such as dataset image samples and training logs, and make sure you are following our Tips for Best Training Results.

    Join the Ultralytics community where it suits you best! For real-time chat, head to Discord 🎧. Prefer in-depth discussions? Check out Discourse. Or explore threads on our Subreddit and connect with other users.

    Upgrade

    Upgrade to the latest ultralytics package, including all requirements, in a Python>=3.8 environment with PyTorch>=1.8 to ensure your issue is not already resolved:

    pip install -U ultralytics

    Environments

    YOLO can be run in any of the following up-to-date verified environments (with all dependencies, including CUDA/CUDNN, Python, and PyTorch preinstalled):

    Status

    Ultralytics CI

    If this badge is green, all Ultralytics CI tests are currently passing. CI tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.


    This is an automated response 🤖. An Ultralytics engineer will also assist you soon!

    1. Glenn JocherUltralytics

      @ablyzniuk to set a custom loss function, you can override the init_criterion method in your custom model class, as shown in the Advanced Customization documentation. This method allows you to define and initialize your loss function according to your requirements. Let me know if you need an example!

    2. ablyzniukGitHub

      @glen-jocher thank you) I will be glad and thankfull if you will give a detailed example of training default Ultralytics Yolo(5-11 versions) with custom trainer e.t.c. I think there must be much easier and convinient way opposite what I did (I edited source code and overrides DetectionTrainer methods after)

    3. Glenn JocherUltralytics(đã chỉnh sửa)

      For custom training without modifying source code, subclass DetectionTrainer and override methods like this:

      from ultralytics.models.yolo.detect import DetectionTrainer
      from ultralytics.nn.tasks import DetectionModel
      
      class CustomModel(DetectionModel):
          def init_criterion(self):
              # Your custom loss initialization here
              pass
      
      class CustomTrainer(DetectionTrainer):
          def get_model(self, cfg=None, weights=None, verbose=True):
              return CustomModel(cfg, nc=self.data["nc"], verbose=verbose)  # Replace with your model config
      
      trainer = CustomTrainer(overrides={'model': 'yolo26n.yaml', 'data': 'coco128.yaml', 'epochs': 100})
      trainer.train()

      This maintains upgrade compatibility while allowing customization. The Advanced Customization Guide shows additional methods you can override.

  2. ternausGitHub

    Is it possible to define custom DataLoader or Augmentation pipeline in DetectionTrainer?

    1. Paula DerrengerUltralytics

      Yes, it's definitely possible to define custom DataLoader and Augmentation pipelines in DetectionTrainer! 🚀 To do so, you'd primarily override the get_dataloader() method in a subclass of DetectionTrainer. Here's a brief example on how you might go about customizing your DataLoader:

      from ultralytics.models.yolo.detect import DetectionTrainer
      
      class CustomTrainer(DetectionTrainer):
          def get_dataloader(self, ...):
              # Your custom DataLoader logic here
              ...

      For augmentations, you can integrate them within your custom DataLoader or modify datasets accordingly. If you need further customization or to include a custom Augmentation pipeline directly tied with the models' training loop, you could adjust or extend methods in the model itself or within the get_dataloader method to apply augmentations.

      Don't forget to explore our Advanced Customization section and BaseTrainer Reference for more details on customizing training routines, models, and DataLoaders. 😄 Happy coding!

      1
  3. UttamToniGitHub

    As mentioned in the advanced customization of ultralytics:

    from ultralytics.models.yolo.detect import DetectionTrainer trainer = DetectionTrainer(overrides={...})

    i am confuced that which file should i place in the curly brackets of overrides={...} . Is the args.yaml file is allowed , which is created after the training step? I have used the args.yaml file which is created after training step but got this error:

    /usr/local/lib/python3.10/dist-packages/ultralytics/engine/trainer.py in __init__(self, cfg, overrides, _callbacks)
         96             overrides (dict, optional): Configuration overrides. Defaults to None.
         97         """
    ---> 98         self.args = get_cfg(cfg, overrides)
         99         self.check_resume(overrides)
        100         self.device = select_device(self.args.device, self.args.batch)
    
    /usr/local/lib/python3.10/dist-packages/ultralytics/cfg/__init__.py in get_cfg(cfg, overrides)
        207         overrides = cfg2dict(overrides)
        208         if "save_dir" not in cfg:
    --> 209             overrides.pop("save_dir", None)  # special override keys to ignore
        210         check_dict_alignment(cfg, overrides)
        211         cfg = {**cfg, **overrides}  # merge cfg and overrides dicts (prefer overrides)
    
    TypeError: set.pop() takes no arguments (2 given)
    
    1. Glenn JocherUltralytics(đã chỉnh sửa)

      Hello! It seems like there’s been a little confusion regarding the overrides={...} usage, and I appreciate you reaching out for clarification. 🙌

      To directly answer your question, the overrides={...} parameter is designed to accept a dictionary of configuration overrides, not a file. It's intended to programmatically override specific configuration entries. For example:

      from ultralytics.models.yolo.detect import DetectionTrainer
      
      # Example override dictionary
      overrides = {
          "batch": 16,
          "imgsz": 640,
      }
      
      trainer = DetectionTrainer(overrides=overrides)

      If you're looking to use the configurations from an args.yaml file created after training, you'd first need to read this YAML file into a Python dictionary, which you could then pass to overrides. Here's a quick way to do it:

      import yaml
      
      # Load your args.yaml content into a dictionary
      with open('path/to/your/args.yaml', 'r') as file:
          yaml_content = yaml.safe_load(file)
      
      # Now, pass the loaded dictionary to overrides
      trainer = DetectionTrainer(overrides=yaml_content)

      Regarding the error you're encountering, it appears there's a misunderstanding in how the overrides dictionary is being used or possibly an issue with the implementation. If following the above pattern doesn't resolve your issue, could you please share more details about what you're trying to achieve with the overrides? This way, I or someone from the community can offer more targeted advice. 😊

      Thank you for your patience, and looking forward to helping you get this sorted!