はじめる

高度なカスタマイズ

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リファレンスをご覧ください。

コントリビューター

コメント10

質問したり、結果を共有したり、ほかの人をサポートしたりできます。

  1. UltralyticsAssistantGitHubUltralytics

    👋 Hello, thank you for your interest in Ultralytics 🚀! We recommend visiting the Docs for new users, where you can explore numerous Python and CLI usage examples. Many common questions may already be answered there, including step-by-step guides tailored for different tasks.

    If this is a 🐛 Bug Report, please provide a minimum reproducible example to help us debug the issue.

    If you have a custom training ❓ Question, please include as much information as possible, such as dataset image samples and training logs, and make sure you are following our Tips for Best Training Results.

    Join the Ultralytics community where it suits you best! For real-time chat, head to Discord 🎧. Prefer in-depth discussions? Check out Discourse. Or explore threads on our Subreddit and connect with other users.

    Upgrade

    Upgrade to the latest ultralytics package, including all requirements, in a Python>=3.8 environment with PyTorch>=1.8 to ensure your issue is not already resolved:

    pip install -U ultralytics

    Environments

    YOLO can be run in any of the following up-to-date verified environments (with all dependencies, including CUDA/CUDNN, Python, and PyTorch preinstalled):

    Status

    Ultralytics CI

    If this badge is green, all Ultralytics CI tests are currently passing. CI tests verify correct operation of all YOLO Modes and Tasks on macOS, Windows, and Ubuntu every 24 hours and on every commit.


    This is an automated response 🤖. An Ultralytics engineer will also assist you soon!

    1. Glenn JocherUltralytics

      @ablyzniuk to set a custom loss function, you can override the init_criterion method in your custom model class, as shown in the Advanced Customization documentation. This method allows you to define and initialize your loss function according to your requirements. Let me know if you need an example!

    2. ablyzniukGitHub

      @glen-jocher thank you) I will be glad and thankfull if you will give a detailed example of training default Ultralytics Yolo(5-11 versions) with custom trainer e.t.c. I think there must be much easier and convinient way opposite what I did (I edited source code and overrides DetectionTrainer methods after)

    3. Glenn JocherUltralytics(編集済み)

      For custom training without modifying source code, subclass DetectionTrainer and override methods like this:

      from ultralytics.models.yolo.detect import DetectionTrainer
      from ultralytics.nn.tasks import DetectionModel
      
      class CustomModel(DetectionModel):
          def init_criterion(self):
              # Your custom loss initialization here
              pass
      
      class CustomTrainer(DetectionTrainer):
          def get_model(self, cfg=None, weights=None, verbose=True):
              return CustomModel(cfg, nc=self.data["nc"], verbose=verbose)  # Replace with your model config
      
      trainer = CustomTrainer(overrides={'model': 'yolo26n.yaml', 'data': 'coco128.yaml', 'epochs': 100})
      trainer.train()

      This maintains upgrade compatibility while allowing customization. The Advanced Customization Guide shows additional methods you can override.

  2. ternausGitHub

    Is it possible to define custom DataLoader or Augmentation pipeline in DetectionTrainer?

    1. Paula DerrengerUltralytics

      Yes, it's definitely possible to define custom DataLoader and Augmentation pipelines in DetectionTrainer! 🚀 To do so, you'd primarily override the get_dataloader() method in a subclass of DetectionTrainer. Here's a brief example on how you might go about customizing your DataLoader:

      from ultralytics.models.yolo.detect import DetectionTrainer
      
      class CustomTrainer(DetectionTrainer):
          def get_dataloader(self, ...):
              # Your custom DataLoader logic here
              ...

      For augmentations, you can integrate them within your custom DataLoader or modify datasets accordingly. If you need further customization or to include a custom Augmentation pipeline directly tied with the models' training loop, you could adjust or extend methods in the model itself or within the get_dataloader method to apply augmentations.

      Don't forget to explore our Advanced Customization section and BaseTrainer Reference for more details on customizing training routines, models, and DataLoaders. 😄 Happy coding!

      1
  3. UttamToniGitHub

    As mentioned in the advanced customization of ultralytics:

    from ultralytics.models.yolo.detect import DetectionTrainer trainer = DetectionTrainer(overrides={...})

    i am confuced that which file should i place in the curly brackets of overrides={...} . Is the args.yaml file is allowed , which is created after the training step? I have used the args.yaml file which is created after training step but got this error:

    /usr/local/lib/python3.10/dist-packages/ultralytics/engine/trainer.py in __init__(self, cfg, overrides, _callbacks)
         96             overrides (dict, optional): Configuration overrides. Defaults to None.
         97         """
    ---> 98         self.args = get_cfg(cfg, overrides)
         99         self.check_resume(overrides)
        100         self.device = select_device(self.args.device, self.args.batch)
    
    /usr/local/lib/python3.10/dist-packages/ultralytics/cfg/__init__.py in get_cfg(cfg, overrides)
        207         overrides = cfg2dict(overrides)
        208         if "save_dir" not in cfg:
    --> 209             overrides.pop("save_dir", None)  # special override keys to ignore
        210         check_dict_alignment(cfg, overrides)
        211         cfg = {**cfg, **overrides}  # merge cfg and overrides dicts (prefer overrides)
    
    TypeError: set.pop() takes no arguments (2 given)
    
    1. Glenn JocherUltralytics(編集済み)

      Hello! It seems like there’s been a little confusion regarding the overrides={...} usage, and I appreciate you reaching out for clarification. 🙌

      To directly answer your question, the overrides={...} parameter is designed to accept a dictionary of configuration overrides, not a file. It's intended to programmatically override specific configuration entries. For example:

      from ultralytics.models.yolo.detect import DetectionTrainer
      
      # Example override dictionary
      overrides = {
          "batch": 16,
          "imgsz": 640,
      }
      
      trainer = DetectionTrainer(overrides=overrides)

      If you're looking to use the configurations from an args.yaml file created after training, you'd first need to read this YAML file into a Python dictionary, which you could then pass to overrides. Here's a quick way to do it:

      import yaml
      
      # Load your args.yaml content into a dictionary
      with open('path/to/your/args.yaml', 'r') as file:
          yaml_content = yaml.safe_load(file)
      
      # Now, pass the loaded dictionary to overrides
      trainer = DetectionTrainer(overrides=yaml_content)

      Regarding the error you're encountering, it appears there's a misunderstanding in how the overrides dictionary is being used or possibly an issue with the implementation. If following the above pattern doesn't resolve your issue, could you please share more details about what you're trying to achieve with the overrides? This way, I or someone from the community can offer more targeted advice. 😊

      Thank you for your patience, and looking forward to helping you get this sorted!