고급 사용자 정의
Ultralytics YOLO 명령줄 및 python 인터페이스는 모두 기본 엔진 실행기를 기반으로 구축된 고급 추상화입니다. 이 가이드는 다음 사항에 중점을 둡니다. Trainer
엔진을 통해 특정 요구 사항에 맞게 사용자 정의하는 방법을 설명합니다.
참고: Ultralytics YOLO 마스터하기: 고급 커스터마이징
BaseTrainer
에 지정되어 있습니다. BaseTrainer
클래스는 다양한 작업에 적용할 수 있는 일반적인 학습 루틴을 제공합니다. 필요한 형식을 준수하면서 특정 함수 또는 작업을 재정의하여 사용자 정의하십시오. 예를 들어, 다음 함수를 재정의하여 사용자 정의 모델 및 데이터 로더를 통합합니다.
get_model(cfg, weights)
: 훈련할 모델을 빌드합니다.get_dataloader()
: 데이터 로더를 빌드합니다.
자세한 내용 및 소스 코드는 다음을 참조하십시오. BaseTrainer
참조.
DetectionTrainer
다음은 Ultralytics YOLO를 사용하고 사용자 정의하는 방법입니다. DetectionTrainer
:
from ultralytics.models.yolo.detect import DetectionTrainer
trainer = DetectionTrainer(overrides={...})
trainer.train()
trained_model = trainer.best # Get the best model
DetectionTrainer 사용자 정의하기
직접적으로 지원되지 않는 사용자 정의 감지 모델을 학습시키려면 기존 모델을 오버로드하십시오. get_model
기능:
from ultralytics.models.yolo.detect import DetectionTrainer
class CustomTrainer(DetectionTrainer):
def get_model(self, cfg, weights):
"""Loads a custom detection model given configuration and weight files."""
...
trainer = CustomTrainer(overrides={...})
trainer.train()
손실 함수를 수정하거나 10 에포크마다 모델을 Google Drive에 업로드하는 콜백을 추가하여 트레이너를 추가로 사용자 정의합니다. 다음은 예시입니다.
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, weights):
"""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()
콜백 트리거 이벤트 및 진입점에 대한 자세한 내용은 콜백 가이드를 참조하십시오.
기타 엔진 구성 요소
다음과 같은 다른 구성 요소를 사용자 정의하십시오. Validators
및 Predictors
마찬가지로. 자세한 내용은 다음 문서를 참조하십시오. 유효성 검사기 및 예측기.
커스텀 트레이너로 YOLO 사용하기
에 지정되어 있습니다. YOLO
모델 클래스는 트레이너 클래스에 대한 고급 래퍼를 제공합니다. 이 아키텍처를 활용하여 머신러닝 워크플로에서 더 큰 유연성을 확보할 수 있습니다.
from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer
# Create a custom trainer
class MyCustomTrainer(DetectionTrainer):
def get_model(self, cfg, weights):
"""Custom code implementation."""
...
# Initialize YOLO model
model = YOLO("yolo11n.pt")
# Train with custom trainer
results = model.train(trainer=MyCustomTrainer, data="coco8.yaml", epochs=3)
이 방법을 사용하면 특정 요구 사항에 맞게 기본 학습 프로세스를 사용자 지정하면서 YOLO 인터페이스의 단순성을 유지할 수 있습니다.
FAQ
특정 작업을 위해 Ultralytics YOLO DetectionTrainer를 어떻게 사용자 정의하나요?
다음을 사용자 정의합니다. DetectionTrainer
사용자 지정 모델 및 데이터 로더에 맞게 메서드를 재정의하여 특정 작업을 수행합니다. 다음에서 상속하여 시작하십시오. DetectionTrainer
다음과 같은 메서드를 재정의합니다. get_model
사용자 정의 기능을 구현합니다. 다음은 그 예입니다.
from ultralytics.models.yolo.detect import DetectionTrainer
class CustomTrainer(DetectionTrainer):
def get_model(self, cfg, weights):
"""Loads a custom detection model given configuration and weight files."""
...
trainer = CustomTrainer(overrides={...})
trainer.train()
trained_model = trainer.best # Get the best model
손실 함수 변경 또는 콜백 추가와 같은 추가 사용자 정의는 콜백 가이드를 참조하십시오.
Ultralytics YOLO에서 BaseTrainer의 주요 구성 요소는 무엇입니까?
에 지정되어 있습니다. BaseTrainer
일반적인 메서드를 재정의하여 다양한 작업에 맞게 사용자 정의할 수 있는 훈련 루틴의 기초 역할을 합니다. 주요 구성 요소는 다음과 같습니다.
get_model(cfg, weights)
: 훈련할 모델을 빌드합니다.get_dataloader()
: 데이터 로더를 빌드합니다.preprocess_batch()
: 모델 순방향 전달 전에 배치 전처리(batch preprocessing)를 처리합니다.set_model_attributes()
: 데이터 세트 정보를 기반으로 모델 속성을 설정합니다.get_validator()
: 모델 평가를 위한 유효성 검사기를 반환합니다.
사용자 정의 및 소스 코드에 대한 자세한 내용은 다음을 참조하십시오. BaseTrainer
참조.
Ultralytics YOLO DetectionTrainer에 콜백을 추가하려면 어떻게 해야 합니까?
콜백을 추가하여 다음의 학습 과정을 모니터링하고 수정합니다. DetectionTrainer
입니다. 다음은 모든 학습 후 모델 가중치를 기록하기 위해 콜백을 추가하는 방법입니다. epoch:
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()
콜백 이벤트 및 진입점에 대한 자세한 내용은 콜백 가이드를 참조하십시오.
모델 학습에 Ultralytics YOLO를 사용해야 하는 이유는 무엇인가요?
Ultralytics YOLO는 강력한 엔진 실행기에 대한 높은 수준의 추상화를 제공하므로 빠른 개발 및 사용자 정의에 이상적입니다. 주요 이점은 다음과 같습니다.
- 사용 편의성: 명령줄 및 Python 인터페이스 모두 복잡한 작업을 단순화합니다.
- 성능: 실시간 객체 감지 및 다양한 비전 AI 애플리케이션에 최적화되었습니다.
- 사용자 정의: 사용자 정의 모델, 손실 함수 및 데이터 로더에 맞게 쉽게 확장할 수 있습니다.
- 모듈성: 전체 파이프라인에 영향을 주지 않고 독립적으로 구성 요소를 수정할 수 있습니다.
- 통합: ML 에코시스템의 널리 사용되는 프레임워크 및 도구와 원활하게 작동합니다.
메인 Ultralytics YOLO 페이지를 탐색하여 YOLO의 기능에 대해 자세히 알아보세요.
Ultralytics YOLO DetectionTrainer를 표준이 아닌 모델에 사용할 수 있나요?
예, DetectionTrainer
비표준 모델에 대해 매우 유연하고 사용자 정의가 가능합니다. 다음에서 상속받습니다. DetectionTrainer
특정 모델의 요구 사항을 지원하기 위해 메서드를 오버로드합니다. 간단한 예는 다음과 같습니다.
from ultralytics.models.yolo.detect import DetectionTrainer
class CustomDetectionTrainer(DetectionTrainer):
def get_model(self, cfg, weights):
"""Loads a custom detection model."""
...
trainer = CustomDetectionTrainer(overrides={...})
trainer.train()
자세한 지침 및 예제는 다음을 검토하십시오. DetectionTrainer
참조.