고급 사용자 지정

Ultralytics YOLO 명령줄 및 Python 인터페이스는 모두 기본 엔진 실행기를 기반으로 구축된 고수준 추상화입니다. 이 가이드에서는 Trainer 엔진을 중점적으로 다루며, 구체적인 요구 사항에 맞게 엔진을 사용자 지정하는 방법을 설명합니다.



시청: Ultralytics YOLO 마스터하기: 고급 사용자 지정
팁

사용자 지정 메트릭, 클래스 가중치 손실, 모델 저장, 백본 동결, 레이어별 학습률 등 일반적인 트레이너 사용자 지정 사례는 트레이너 사용자 지정 가이드를 참조하세요.

BaseTrainer#

BaseTrainer 클래스는 다양한 작업에 맞게 조정할 수 있는 범용 학습 루틴을 제공합니다. 필요한 형식을 준수하면서 특정 함수나 작업을 재정의하여 사용자 지정할 수 있습니다. 예를 들어, 다음 함수를 재정의하여 사용자 지정 모델과 데이터로더를 통합할 수 있습니다:

  • get_model(cfg, weights): 학습할 모델을 구성합니다.
  • get_dataloader(dataset_path, batch_size, rank, mode): 데이터로더를 구성합니다.

자세한 내용과 소스 코드는 BaseTrainer 참조 문서를 확인하세요.

DetectionTrainer#

Ultralytics YOLO DetectionTrainer의 사용 및 사용자 지정 방법은 다음과 같습니다:

from ultralytics.models.yolo.detect import DetectionTrainer

trainer = DetectionTrainer(overrides={...})
trainer.train()
trained_model = trainer.best  # 최적의 모델 가져오기

DetectionTrainer 사용자 지정#

직접 지원되지 않는 사용자 지정 감지 모델을 학습하려면 기존 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()

손실 함수를 수정하거나 모든 에폭 종료 시 실행되는 콜백을 추가하여 트레이너를 더 사용자 지정할 수 있습니다. 예를 들어 최신 가중치를 기록하거나 업로드할 수 있습니다. 예시는 다음과 같습니다:

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(...)

# 모델 가중치를 기록하는 콜백
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)  # 기존 콜백에 추가
trainer.train()

콜백 트리거 이벤트와 진입점에 대한 자세한 내용은 콜백 가이드를 확인하세요.

기타 엔진 구성 요소#

Validators 및 Predictors과 같은 다른 구성 요소도 동일한 방식으로 사용자 지정할 수 있습니다. 자세한 내용은 검증기 및 예측기 문서를 참조하세요.

사용자 지정 트레이너로 YOLO 사용하기#

YOLO 모델 클래스는 트레이너 클래스의 고수준 래퍼를 제공합니다. 이 아키텍처를 활용하여 머신러닝 워크플로의 유연성을 높일 수 있습니다:

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

# 사용자 지정 트레이너 생성
class MyCustomTrainer(DetectionTrainer):
    def get_model(self, cfg=None, weights=None, verbose=True):
        """Custom code implementation."""

# YOLO 모델 초기화
model = YOLO("yolo26n.pt")

# 사용자 지정 트레이너로 학습
results = model.train(trainer=MyCustomTrainer, data="coco8.yaml", epochs=3)

이 접근 방식을 사용하면 YOLO 인터페이스의 간편함을 유지하면서 기본 학습 프로세스를 특정 요구사항에 맞게 사용자 지정할 수 있습니다.

자주 묻는 질문#

  • 특정 작업에 맞게 DetectionTrainer을 사용자 지정하려면 메서드를 재정의하여 사용자 지정 모델과 데이터로더에 맞게 조정하세요. 먼저 DetectionTrainer을 상속하고 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()
    trained_model = trainer.best  # 최적의 모델 가져오기
  • BaseTrainer은 학습 루틴의 기반으로, 범용 메서드를 재정의하여 다양한 작업에 맞게 사용자 지정할 수 있습니다. 주요 구성 요소는 다음과 같습니다:

    • get_model(cfg, weights): 학습할 모델을 구성합니다.
    • get_dataloader(dataset_path, batch_size, rank, mode): 데이터로더를 구성합니다.
    • preprocess_batch(): 모델의 순전파 전에 배치 전처리를 처리합니다.
    • set_model_attributes(): 데이터셋 정보를 기반으로 모델 속성을 설정합니다.
    • get_validator(): 모델 평가에 사용할 검증기를 반환합니다.

    사용자 지정 및 소스 코드에 대한 자세한 내용은 BaseTrainer 참조 문서를 확인하세요.

  • DetectionTrainer에서 학습 과정을 모니터링하고 수정하기 위한 콜백을 추가합니다. 매 학습 에포크가 끝날 때 모델 가중치를 기록하는 콜백을 추가하는 방법은 다음과 같습니다:

    from ultralytics.models.yolo.detect import DetectionTrainer
    
    # 모델 가중치를 기록하는 콜백
    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)  # 기존 콜백에 추가
    trainer.train()

    콜백 이벤트와 진입점에 대한 자세한 내용은 콜백 가이드를 참조하세요.

  • Ultralytics YOLO는 엔진 실행기를 고수준으로 추상화하므로 신속한 개발과 사용자 지정에 적합합니다. 주요 장점은 다음과 같습니다:

    • 사용 편의성: CLI와 Python 인터페이스 모두 복잡한 작업을 간소화합니다.
    • 성능: 실시간 객체 감지와 다양한 비전 AI 애플리케이션에 최적화되어 있습니다.
    • 사용자 지정: 커스텀 모델, 손실 함수 및 데이터로더를 확장할 수 있습니다.
    • 모듈성: 전체 파이프라인에 영향을 주지 않고 구성 요소를 독립적으로 수정할 수 있습니다.
    • 통합: ML 생태계의 인기 있는 프레임워크 및 도구와 함께 작동합니다.

    YOLO의 기능에 대한 자세한 내용은 기본 Ultralytics YOLO 페이지를 확인하세요.

  • 네. DetectionTrainer은 표준이 아닌 모델에 맞게 사용자 지정할 수 있습니다. DetectionTrainer을 상속하고 메서드를 오버로드하여 특정 모델의 요구 사항을 지원하세요. 간단한 예시는 다음과 같습니다:

    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()

    자세한 지침과 예제는 DetectionTrainer 참조 문서를 확인하세요.

댓글10

질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.

  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(수정됨)

      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.

    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
  2. 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(수정됨)

      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!