高度なカスタマイズ#
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ドライブにモデルをアップロードするコールバックを追加して、トレーナーをさらにカスタマイズします。以下に例を示します。
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などの他のコンポーネントも同様にカスタマイズできます。詳細については、バリデータおよびプレディクターのドキュメントを参照してください。
カスタムトレーナーでの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#
カスタムモデルとデータローダーに適応するようにメソッドをオーバーライドすることで、特定のタスクに合わせて
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 modelBaseTrainerはトレーニングルーチンの基礎として機能し、その汎用メソッドをオーバーライドすることでさまざまなタスクに合わせてカスタマイズ可能です。主なコンポーネントは次のとおりです。get_model(cfg, weights): トレーニングするモデルを構築します。get_dataloader(): データローダーを構築します。preprocess_batch(): モデルの順伝播の前にバッチの前処理を処理します。set_model_attributes(): データセット情報に基づいてモデルの属性を設定します。get_validator(): モデル評価用のバリデータを返します。
カスタマイズとソースコードの詳細については、
BaseTrainerリファレンスを参照してください。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は、強力なエンジンエグゼキューターに対する高レベルの抽象化を提供するため、迅速な開発とカスタマイズに最適です。主な利点は次のとおりです。
- 使いやすさ: コマンドラインとPythonインターフェースの両方により、複雑なタスクが簡素化されます。
- パフォーマンス: リアルタイムの物体検出やさまざまなビジョンAIアプリケーション向けに最適化されています。
- カスタマイズ: カスタムモデル、損失関数、データローダーに合わせて簡単に拡張できます。
- モジュール性: パイプライン全体に影響を与えることなく、コンポーネントを個別に変更できます。
- 統合: MLエコシステムの一般的なフレームワークやツールとシームレスに連携します。
メインのUltralytics YOLOページを調べて、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リファレンスを確認してください。