Meet YOLO26: next-gen vision AI.

Link to this sectionトレーナーのカスタマイズ#

Ultralyticsのトレーニングパイプラインは、BaseTrainerDetectionTrainerのようなタスク固有のトレーナーを中心に構築されています。これらのクラスは、トレーニングループ、バリデーション、チェックポイント保存、ロギングを標準機能として処理します。カスタムメトリクスの追跡、損失関数の重み付け調整、学習率スケジュールの実装など、より細かな制御が必要な場合は、トレーナーをサブクラス化して特定のメソッドをオーバーライドできます。

このガイドでは、7つの一般的なカスタマイズについて説明します。

  1. Logging custom metrics (F1 score) at the end of each epoch
  2. クラス不均衡に対処するためのクラス重みの追加
  3. 異なるメトリクスに基づく最適なモデルの保存
  4. 最初のNエポックはバックボーンをフリーズし、その後フリーズを解除する
  5. レイヤーごとの学習率の指定
  6. マルチGPUトレーニング用のBatchNormの同期
  7. 安定性向上のための勾配クリッピングの設定
前提条件

Before reading this guide, make sure you're familiar with the basics of training YOLO models and the Advanced Customization page, which covers the BaseTrainer architecture.

Link to this sectionカスタムトレーナーの仕組み#

The YOLO model class accepts a trainer parameter in the train() method. This allows you to pass your own trainer class that extends the default behavior:

from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer

class CustomTrainer(DetectionTrainer):
    """A custom trainer that extends DetectionTrainer with additional functionality."""

    pass  # Add your customizations here

model = YOLO("yolo26n.pt")
model.train(data="coco8.yaml", epochs=10, trainer=CustomTrainer)

カスタムトレーナーはDetectionTrainerからすべての機能を継承するため、カスタマイズしたい特定のメソッドのみをオーバーライドすれば十分です。

Link to this sectionカスタムメトリクスのロギング#

バリデーションステップでは、精度 (precision)再現率 (recall)、およびmAPが計算されます。クラスごとのF1スコアのような追加のメトリクスが必要な場合は、validate()をオーバーライドしてください。

import numpy as np

from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.utils import LOGGER

class MetricsTrainer(DetectionTrainer):
    """Custom trainer that computes and logs F1 score at the end of each epoch."""

    def validate(self):
        """Run validation and compute per-class F1 scores."""
        metrics, fitness = super().validate()
        if metrics is None:
            return metrics, fitness

        if hasattr(self.validator, "metrics") and hasattr(self.validator.metrics, "box"):
            box = self.validator.metrics.box
            f1_per_class = box.f1
            class_indices = box.ap_class_index
            names = self.validator.names

            valid_f1 = f1_per_class[f1_per_class > 0]
            mean_f1 = np.mean(valid_f1) if len(valid_f1) > 0 else 0.0

            LOGGER.info(f"Mean F1 Score: {mean_f1:.4f}")
            per_class_str = [
                f"{names[i]}: {f1_per_class[j]:.3f}" for j, i in enumerate(class_indices) if f1_per_class[j] > 0
            ]
            LOGGER.info(f"Per-class F1: {per_class_str}")

        return metrics, fitness

model = YOLO("yolo26n.pt")
model.train(data="coco8.yaml", epochs=5, trainer=MetricsTrainer)

これは、各バリデーション実行後に、全クラスにわたる平均F1スコアとクラスごとの内訳をログに記録します。

利用可能なメトリクス

バリデーターは、self.validator.metrics.boxを通じて多くのメトリクスへのアクセスを提供します。

属性説明
f1クラスごとのF1スコア
image_metrics精度、再現率、F1、TP、FP、FNを含む画像ごとのメトリクス辞書
pクラスごとの精度
rクラスごとの再現率
ap50クラスごとのIoU 0.5におけるAP
apクラスごとのIoU 0.5:0.95におけるAP
mp, mr平均精度と再現率
map50, map平均APメトリクス

Link to this sectionクラス重みの追加#

データセットのクラスに偏りがある場合(例:製造検査における稀な欠陥など)、損失関数内で少数クラスの重みを大きく設定できます。これにより、モデルは少数クラスの誤分類に対してより厳しいペナルティを課すようになります。

損失関数をカスタマイズするには、損失クラス、モデル、およびトレーナーをサブクラス化します。

import torch
from torch import nn

from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.nn.tasks import DetectionModel
from ultralytics.utils import RANK
from ultralytics.utils.loss import E2ELoss, v8DetectionLoss

class WeightedDetectionLoss(v8DetectionLoss):
    """Detection loss with class weights applied to BCE classification loss."""

    def __init__(self, model, class_weights=None, tal_topk=10, tal_topk2=None):
        """Initialize loss with optional per-class weights for BCE."""
        super().__init__(model, tal_topk=tal_topk, tal_topk2=tal_topk2)
        if class_weights is not None:
            self.bce = nn.BCEWithLogitsLoss(
                pos_weight=class_weights.to(self.device),
                reduction="none",
            )

class WeightedE2ELoss(E2ELoss):
    """E2E Loss with class weights for YOLO26."""

    def __init__(self, model, class_weights=None):
        """Initialize E2E loss with weighted detection loss."""

        def weighted_loss_fn(model, tal_topk=10, tal_topk2=None):
            return WeightedDetectionLoss(model, class_weights=class_weights, tal_topk=tal_topk, tal_topk2=tal_topk2)

        super().__init__(model, loss_fn=weighted_loss_fn)

class WeightedDetectionModel(DetectionModel):
    """Detection model that uses class-weighted loss."""

    def init_criterion(self):
        """Initialize weighted loss criterion with per-class weights."""
        class_weights = torch.ones(self.nc)
        class_weights[0] = 2.0  # upweight class 0
        class_weights[1] = 3.0  # upweight rare class 1
        return WeightedE2ELoss(self, class_weights=class_weights)

class WeightedTrainer(DetectionTrainer):
    """Trainer that returns a WeightedDetectionModel."""

    def get_model(self, cfg=None, weights=None, verbose=True):
        """Return a WeightedDetectionModel."""
        model = WeightedDetectionModel(cfg, nc=self.data["nc"], verbose=verbose and RANK == -1)
        if weights:
            model.load(weights)
        return model

model = YOLO("yolo26n.pt")
model.train(data="coco8.yaml", epochs=10, trainer=WeightedTrainer)
データセットからの重みの計算

データセットのラベル分布からクラス重みを自動的に計算できます。一般的な手法は逆頻度重み付けです。

import numpy as np

# class_counts: number of instances per class
class_counts = np.array([5000, 200, 3000])
# Inverse frequency: rarer classes get higher weight
class_weights = max(class_counts) / class_counts
# Result: [1.0, 25.0, 1.67]

Link to this sectionカスタムメトリクスによるベストモデルの保存#

The trainer saves best.pt based on fitness, which defaults to 0.9 × mAP@0.5:0.95 + 0.1 × mAP@0.5. To use a different metric (like mAP@0.5 or recall), override validate() and return your chosen metric as the fitness value. The built-in save_model() will then use it automatically:

from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer

class CustomSaveTrainer(DetectionTrainer):
    """Trainer that saves the best model based on mAP@0.5 instead of default fitness."""

    def validate(self):
        """Override fitness to use mAP@0.5 for best model selection."""
        metrics, fitness = super().validate()
        if metrics:
            fitness = metrics.get("metrics/mAP50(B)", fitness)
            if self.best_fitness is None or fitness > self.best_fitness:
                self.best_fitness = fitness
        return metrics, fitness

model = YOLO("yolo26n.pt")
model.train(data="coco8.yaml", epochs=20, trainer=CustomSaveTrainer)
利用可能なメトリクス

バリデーション後に self.metrics で利用可能な一般的なメトリクスは以下の通りです。

キー説明
metrics/precision(B)精度
metrics/recall(B)再現率
metrics/mAP50(B)IoU 0.5におけるmAP
metrics/mAP50-95(B)IoU 0.5:0.95におけるmAP

Link to this sectionバックボーンのフリーズと解除#

転移学習のワークフローでは、最初のNエポックで事前学習済みのバックボーンをフリーズすることで、ネットワーク全体をファインチューニングする前に検出ヘッドを適応させることが有効な場合があります。Ultralyticsは、トレーニング開始時にレイヤーをフリーズする freeze パラメータを提供しており、コールバックを使用してNエポック後にそれらを解除できます。

from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.utils import LOGGER

FREEZE_EPOCHS = 5

def unfreeze_backbone(trainer):
    """Callback to unfreeze all layers after FREEZE_EPOCHS."""
    if trainer.epoch == FREEZE_EPOCHS:
        LOGGER.info(f"Epoch {trainer.epoch}: Unfreezing all layers for fine-tuning")
        for name, param in trainer.model.named_parameters():
            if not param.requires_grad:
                param.requires_grad = True
                LOGGER.info(f"  Unfroze: {name}")
        trainer.freeze_layer_names = [".dfl"]

class FreezingTrainer(DetectionTrainer):
    """Trainer with backbone freezing for first N epochs."""

    def __init__(self, *args, **kwargs):
        """Initialize and register the unfreeze callback."""
        super().__init__(*args, **kwargs)
        self.add_callback("on_train_epoch_start", unfreeze_backbone)

model = YOLO("yolo26n.pt")
model.train(data="coco8.yaml", epochs=20, freeze=10, trainer=FreezingTrainer)

freeze=10パラメータは、トレーニング開始時に最初の10レイヤー(バックボーン)をフリーズします。on_train_epoch_startコールバックは各エポックの開始時に実行され、フリーズ期間が完了するとすべてのパラメータを解凍します。

何をフリーズするかを選択する
  • freeze=10は最初の10レイヤーをフリーズします(通常、YOLOアーキテクチャのバックボーン)。
  • freeze=[0, 1, 2, 3]はインデックスによって特定のレイヤーをフリーズします。
  • FREEZE_EPOCHSの値を大きくすると、バックボーンが変化する前にヘッドが適応するための時間をより長く確保できます。

Link to this sectionレイヤーごとの学習率#

ネットワークの各部分は、異なる学習率の恩恵を受ける可能性があります。一般的な戦略は、学習済みの特徴を保持するために事前学習済みのバックボーンには低い学習率を使用し、より高い学習率で検出ヘッドを迅速に適応させることです。

import torch

from ultralytics import YOLO
from ultralytics.models.yolo.detect import DetectionTrainer
from ultralytics.utils import LOGGER
from ultralytics.utils.torch_utils import unwrap_model

class PerLayerLRTrainer(DetectionTrainer):
    """Trainer with different learning rates for backbone and head."""

    def build_optimizer(self, model, name="auto", lr=0.001, momentum=0.9, decay=1e-5, iterations=1e5):
        """Build optimizer with separate learning rates for backbone and head."""
        backbone_params = []
        head_params = []

        for k, v in unwrap_model(model).named_parameters():
            if not v.requires_grad:
                continue
            is_backbone = any(k.startswith(f"model.{i}.") for i in range(10))
            if is_backbone:
                backbone_params.append(v)
            else:
                head_params.append(v)

        backbone_lr = lr * 0.1

        optimizer = torch.optim.AdamW(
            [
                {"params": backbone_params, "lr": backbone_lr, "weight_decay": decay},
                {"params": head_params, "lr": lr, "weight_decay": decay},
            ],
        )

        LOGGER.info(
            f"PerLayerLR optimizer: backbone ({len(backbone_params)} params, lr={backbone_lr}) "
            f"| head ({len(head_params)} params, lr={lr})"
        )
        return optimizer

model = YOLO("yolo26n.pt")
model.train(data="coco8.yaml", epochs=20, trainer=PerLayerLRTrainer)

Link to this sectionRT-DETRバリアント#

RT-DETRの場合もパターンは同じですが、2つの改善点があります。バックボーンの長さはmodel.yaml["backbone"]から読み取られるため、レイヤー数をハードコーディングすることなく、同じトレーナーがRT-DETRのバリアント(RT-DETR-L, RT-DETR-X, ResNet-50/101バックボーン)全体で機能します。また、パラメータはセクション内で重み、BatchNorm、バイアスグループに分割されるため、デフォルトのトレーナーのポリシーに合わせて、BatchNormパラメータとバイアスからウェイトディケイが除外されます。これは特にRT-DETRのファインチューニングに役立ちます。デコーダーヘッドは通常ランダムに初期化されますが、バックボーンは低い学習率から恩恵を受ける事前学習済み特徴を保持しているためです。

import torch
from torch import nn

from ultralytics import RTDETR
from ultralytics.models.rtdetr.train import RTDETRTrainer
from ultralytics.utils import LOGGER, colorstr
from ultralytics.utils.torch_utils import unwrap_model

class RTDETRBackboneLRTrainer(RTDETRTrainer):
    """RT-DETR trainer with a lower learning rate for backbone parameters."""

    backbone_lr_ratio = 0.1  # backbone learning rate as a fraction of head learning rate

    def build_optimizer(self, model, name="auto", lr=0.001, momentum=0.9, decay=1e-5, iterations=1e5):
        """Build an AdamW optimizer with six param groups: head and backbone x {weight, bn, bias}."""
        # Resolve optimizer name; "auto" maps to AdamW with RT-DETR-style defaults
        canonical = {"Adam", "Adamax", "AdamW", "NAdam", "RAdam", "auto"}
        name = {x.lower(): x for x in canonical}.get(name.lower(), name)
        if name == "auto":
            name, lr, momentum = "AdamW", 1e-4, 0.9
        self.args.warmup_bias_lr = 0.0  # RT-DETR warms biases from 0, unlike YOLO's 0.1
        if name not in {"Adam", "Adamax", "AdamW", "NAdam", "RAdam"}:
            raise NotImplementedError(f"This trainer only supports AdamW-family optimizers; got {name}")

        # Identify backbone parameters from model.yaml and route each param into a (section, kind) group
        unwrapped = unwrap_model(model)
        backbone_len = len(unwrapped.yaml["backbone"])
        norm_types = tuple(v for k, v in nn.__dict__.items() if "Norm" in k)
        groups = {f"{s}_{k}": [] for s in ("head", "backbone") for k in ("weight", "bn", "bias")}

        for module_name, module in unwrapped.named_modules():
            for param_name, param in module.named_parameters(recurse=False):
                if not param.requires_grad:
                    continue
                fullname = f"{module_name}.{param_name}" if module_name else param_name
                parts = fullname.split(".")
                section = (
                    "backbone"
                    if len(parts) > 1 and parts[0] == "model" and parts[1].isdigit() and int(parts[1]) < backbone_len
                    else "head"
                )
                if "bias" in param_name:
                    kind = "bias"
                elif isinstance(module, norm_types) or "logit_scale" in fullname:
                    kind = "bn"
                else:
                    kind = "weight"
                groups[f"{section}_{kind}"].append(param)

        # Build the optimizer with per-group lr and weight decay; backbone groups use lr * backbone_lr_ratio
        backbone_lr = lr * self.backbone_lr_ratio
        param_groups = [
            {"params": groups["head_weight"], "lr": lr, "weight_decay": decay, "param_group": "weight"},
            {"params": groups["head_bn"], "lr": lr, "weight_decay": 0.0, "param_group": "bn"},
            {"params": groups["head_bias"], "lr": lr, "weight_decay": 0.0, "param_group": "bias"},
            {"params": groups["backbone_weight"], "lr": backbone_lr, "weight_decay": decay, "param_group": "weight"},
            {"params": groups["backbone_bn"], "lr": backbone_lr, "weight_decay": 0.0, "param_group": "bn"},
            {"params": groups["backbone_bias"], "lr": backbone_lr, "weight_decay": 0.0, "param_group": "bias"},
        ]
        param_groups = [pg for pg in param_groups if pg["params"]]  # drop empty groups
        optimizer = getattr(torch.optim, name)(param_groups, betas=(momentum, 0.999))

        LOGGER.info(
            f"{colorstr('optimizer:')} {name}(lr={lr}, backbone_lr={backbone_lr}) with parameter groups\n"
            f"  Head:     {len(groups['head_bn'])} bn, {len(groups['head_weight'])} weight(decay={decay}), "
            f"{len(groups['head_bias'])} bias (lr={lr})\n"
            f"  Backbone: {len(groups['backbone_bn'])} bn, {len(groups['backbone_weight'])} weight(decay={decay}), "
            f"{len(groups['backbone_bias'])} bias (lr={backbone_lr})"
        )
        return optimizer

model = RTDETR("rtdetr-l.pt")
model.train(data="coco8.yaml", epochs=20, trainer=RTDETRBackboneLRTrainer)
`backbone_lr_ratio`の選択

一般的な開始点は backbone_lr_ratio = 0.1 であり、HGNetV2バックボーンを使用したオリジナルのRT-DETRセットアップに適合します。文献では、バックボーンサイズと事前学習データの規模に反比例して比率をスケーリングすることが推奨されています。非常に大規模なデータセットで事前学習された大きなバックボーン(例:何億もの画像でDINO, CLIP, MAEを使用して学習されたViT-L/H)は、学習済みの特徴を維持するために 0.01 以下の小さな比率を使用するのが一般的です。一方、より軽量な事前学習を行った小さなバックボーンは、0.5 以上の大きな比率を許容します。

学習率スケジューラー

内蔵の学習率スケジューラー(cosineまたはlinear)は、グループごとのベース学習率の上に適用されます。バックボーンとヘッドの両方の学習率は同じ減衰スケジュールに従い、トレーニング全体を通じてそれらの間の比率を維持します。

テクニックの組み合わせ

これらのカスタマイズは、必要に応じて複数のメソッドをオーバーライドし、コールバックを追加することで、単一のトレーナークラスに組み合わせることができます。

Link to this sectionマルチGPUトレーニングのための同期BatchNorm#

DistributedDataParallelを使用して複数のGPUでトレーニングする場合、デフォルトの BatchNorm2d レイヤーは各GPUで独立して統計量を計算します。RT-DETRのファインチューニングや、GPUあたりのバッチサイズが小さい他の手法では、GPUごとのバッチ統計がノイズになる可能性があります。PyTorchの SyncBatchNorm は、単一のグローバルバッチ統計のためにすべてのランク間で平均と分散を同期させます。これにより、GPU間のわずかな通信オーバーヘッドを犠牲にして、収束が改善されることがよくあります。

変換は、モデルがGPU上にある後、DDPがそれをラップする前に行う必要があります。これに最適なフックは set_model_attributes() であり、BaseTrainer はまさにそのタイミングでこれを呼び出します。

from torch import nn

from ultralytics import RTDETR
from ultralytics.models.rtdetr.train import RTDETRTrainer

class SyncBNTrainer(RTDETRTrainer):
    """RT-DETR trainer that converts BatchNorm to SyncBatchNorm for multi-GPU training."""

    def set_model_attributes(self):
        """Run the parent setup, then convert BN to SyncBatchNorm when training on multiple GPUs."""
        super().set_model_attributes()
        if self.world_size > 1:
            self.model = nn.SyncBatchNorm.convert_sync_batchnorm(self.model)

model = RTDETR("rtdetr-l.pt")
model.train(data="coco8.yaml", epochs=20, device=[0, 1], trainer=SyncBNTrainer)

world_size > 1 のガードにより、このトレーナーはシングルGPU実行でも安全に使用できます。シングルGPUでは変換がスキップされ、通常の BatchNorm2d でトレーニングが進行します。同じパターンがYOLOにも有効で、親クラスを DetectionTrainer に切り替えることで対応できます。

SyncBatchNormを使用すべきタイミング
シナリオ推奨事項
マルチGPUトレーニング、GPUあたりのバッチサイズが小さい(≤ 16)有効にする
マルチGPUトレーニング、GPUあたりのバッチサイズが大きい(≥ 32)任意;わずかな利点
シングルGPUトレーニング適用外(スキップされる)

Link to this section設定可能な勾配クリッピング#

The default trainer clips gradients to max_norm=10.0 in optimizer_step(), a loose value tuned for YOLO models where gradients rarely exceed it. DETR-family detectors (RT-DETR, DEIM, DINO) typically use much tighter values such as 0.1 to stabilize the decoder's cross-attention layers, where gradient magnitudes can spike. To override the clip value, subclass the trainer and override optimizer_step():

import torch

from ultralytics import RTDETR
from ultralytics.models.rtdetr.train import RTDETRTrainer

class CustomClipTrainer(RTDETRTrainer):
    """RT-DETR trainer with configurable gradient clipping."""

    clip_grad_norm = 0.1  # max gradient norm; set to 0 to disable clipping

    def optimizer_step(self):
        """Run an optimizer step with a configurable gradient-norm clip."""
        self.scaler.unscale_(self.optimizer)
        if self.clip_grad_norm > 0:
            torch.nn.utils.clip_grad_norm_(self.model.parameters(), max_norm=self.clip_grad_norm)
        self.scaler.step(self.optimizer)
        self.scaler.update()
        self.optimizer.zero_grad()
        if self.ema:
            self.ema.update(self.model)

model = RTDETR("rtdetr-l.pt")
model.train(data="coco8.yaml", epochs=20, trainer=CustomClipTrainer)

同じトレーナーがYOLOでも機能します。親クラスを DetectionTrainer に切り替え(from ultralytics.models.yolo.detect import DetectionTrainer)、YOLO("yolo26n.pt") でYOLOチェックポイントをロードします。optimizer_step の本体は変更されません。

典型的な `clip_grad_norm` 値
アーキテクチャファミリー典型的な max_norm
RT-DETR / DEIM / DETRファミリー0.1
YOLO (Ultralyticsデフォルト)10.0
クリッピングを無効化0

Link to this sectionFAQ#

Link to this sectionYOLOにカスタムトレーナーを渡すには?#

Pass your custom trainer class (not an instance) to the trainer parameter in model.train():

from ultralytics import YOLO

model = YOLO("yolo26n.pt")
model.train(data="coco8.yaml", trainer=MyCustomTrainer)

YOLOクラスはトレーナーのインスタンス化を内部的に処理します。トレーナーアーキテクチャの詳細については、高度なカスタマイズページを参照してください。

Link to this sectionオーバーライドできるBaseTrainerのメソッドは?#

カスタマイズ用に利用可能な主要なメソッド:

メソッド目的
validate()バリデーションを実行し、メトリクスを返す
build_optimizer()オプティマイザーを構築する
save_model()トレーニングのチェックポイントを保存します
get_model()モデルインスタンスを返します
get_validator()バリデーターインスタンスを返します
get_dataloader()データローダーを構築します
preprocess_batch()入力バッチを前処理します
label_loss_items()ログ出力用に損失項目をフォーマットします

完全なAPIリファレンスについては、BaseTrainer ドキュメントをご覧ください。

Link to this sectionトレーナーをサブクラス化する代わりにコールバックを使用できますか?#

はい、より単純なカスタマイズであれば、コールバックで十分な場合が多いです。利用可能なコールバックイベントには on_train_starton_train_epoch_starton_train_epoch_endon_fit_epoch_endon_model_save があります。これらを使用することで、サブクラス化せずにトレーニングループにフックできます。上記のバックボーン凍結の例で、このアプローチを実演しています。

Link to this sectionモデルをサブクラス化せずに損失関数をカスタマイズするにはどうすればよいですか?#

変更が単純な場合(損失ゲインの調整など)、ハイパーパラメータを直接変更できます。

model.train(data="coco8.yaml", box=10.0, cls=1.5, dfl=2.0)

損失に対する構造的な変更(クラスウェイトの追加など)が必要な場合は、クラスウェイトのセクションで示されているように、損失とモデルをサブクラス化する必要があります。

コメント