고급 커스텀#
Ultralytics YOLO 커맨드라인 및 Python 인터페이스는 모두 기본 엔진 실행기 위에 구축된 고수준 추상화입니다. 이 가이드는 Trainer 엔진에 초점을 맞추어 특정 요구 사항에 맞게 커스텀하는 방법을 설명합니다.
Watch: Mastering Ultralytics YOLO: Advanced Customization
커스텀 메트릭, 클래스 가중치 손실, 모델 저장, 백본 프리징, 레이어별 학습률 등 일반적인 트레이너 커스텀의 실용적인 예제는 트레이너 커스텀하기 가이드를 참조하세요.
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 modelDetectionTrainer 커스텀하기#
직접 지원되지 않는 커스텀 감지 모델을 학습하려면 기존 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()손실 함수를 수정하거나 콜백을 추가하여 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=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()콜백 트리거 이벤트 및 진입점에 대한 자세한 내용은 콜백 가이드를 참조하세요.
기타 엔진 컴포넌트#
Validators 및 Predictors와 같은 다른 컴포넌트도 유사하게 커스텀할 수 있습니다. 자세한 내용은 Validators 및 Predictors 문서를 참조하세요.
커스텀 트레이너와 함께 YOLO 사용하기#
YOLO 모델 클래스는 Trainer 클래스를 위한 고수준 래퍼를 제공합니다. 머신러닝 워크플로에서 더 큰 유연성을 위해 이 아키텍처를 활용할 수 있습니다:
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)이 접근 방식을 사용하면 YOLO 인터페이스의 단순성을 유지하면서 특정 요구 사항에 맞게 기본 학습 프로세스를 커스텀할 수 있습니다.
FAQ#
특정 작업을 위해 Ultralytics YOLO DetectionTrainer를 어떻게 커스텀하나요?#
커스텀 모델과 데이터로더에 맞게 메서드를 오버라이드하여 특정 작업용 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 # Get the best model손실 함수 변경 또는 콜백 추가와 같은 추가 커스텀에 대해서는 콜백 가이드를 참조하세요.
Ultralytics YOLO의 BaseTrainer의 주요 컴포넌트는 무엇인가요?#
BaseTrainer는 학습 루틴의 기반 역할을 하며, 일반적인 메서드를 오버라이드하여 다양한 작업에 맞게 커스텀할 수 있습니다. 주요 컴포넌트는 다음과 같습니다:
get_model(cfg, weights): 학습할 모델을 빌드합니다.get_dataloader(): 데이터로더를 빌드합니다.preprocess_batch(): 모델 순전파 전에 배치 전처리를 처리합니다.set_model_attributes(): 데이터셋 정보를 기반으로 모델 속성을 설정합니다.get_validator(): 모델 평가를 위한 검증기를 반환합니다.
커스텀 및 소스 코드에 대한 자세한 내용은 BaseTrainer 레퍼런스를 참조하세요.
Ultralytics YOLO DetectionTrainer에 콜백을 어떻게 추가할 수 있나요?#
DetectionTrainer에서 학습 프로세스를 모니터링하고 수정하기 위해 콜백을 추가합니다. 모든 학습 에폭 후에 모델 가중치를 로깅하는 콜백을 추가하는 방법은 다음과 같습니다:
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=None, weights=None, verbose=True):
"""Loads a custom detection model."""
trainer = CustomDetectionTrainer(overrides={...})
trainer.train()포괄적인 지침과 예제는 DetectionTrainer 레퍼런스를 검토하세요.