Ultralytics YOLO27:
Get Started

高度なカスタマイズ#

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モデルクラスは、Trainerクラスの高水準ラッパーを提供します。このアーキテクチャを活用すると、機械学習のワークフローをより柔軟に構成できます。

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は、強力なエンジン実行クラスを高水準で抽象化しており、迅速な開発とカスタマイズに適しています。主な利点は次のとおりです。

    • 使いやすさ:コマンドラインと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リファレンスをご覧ください。

コメント