고급 사용자 지정#
Ultralytics YOLO의 CLI와 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참조 문서를 확인하세요.