コンテンツにスキップ

画像分類

画像分類の例

画像分類は3つのタスクの中で最も単純であり、画像全体を事前定義されたクラスの1つに分類します。

画像分類器の出力は、単一のクラスラベルと信頼度スコアです。画像分類は、画像がどのクラスに属するかを知るだけでよく、そのクラスのオブジェクトがどこにあるか、またはその正確な形状を知る必要がない場合に役立ちます。



見る: Ultralytics YOLOタスクをご覧ください: Ultralytics HUBを使用した画像分類

ヒント

YOLO11 Classifyモデルは、以下を使用します。 -cls 接尾辞、すなわち、 yolo11n-cls.pt, そして事前学習は ImageNet.

モデル

YOLO11 分類モデルをここに示します。検出、セグメンテーション、姿勢推定モデルは COCO データセットで事前学習され、分類モデルは ImageNet データセットで事前学習されています。

モデルは初回使用時に最新のUltralytics リリースから自動的にダウンロードされます。

モデルサイズ
(ピクセル)
acc
top1
acc
top5
速度
CPU ONNX
(ms)
速度
T4 TensorRT10
(ms)
params
(M)
FLOPs
(B) at 224
YOLO11n-cls22470.089.45.0 ± 0.31.1 ± 0.02.80.5
YOLO11s-cls22475.492.77.9 ± 0.21.3 ± 0.06.71.6
YOLO11m-cls22477.393.917.2 ± 0.42.0 ± 0.011.64.9
YOLO11l-cls22478.394.323.2 ± 0.32.8 ± 0.014.16.2
YOLO11x-cls22479.594.941.4 ± 0.93.8 ± 0.029.613.6
  • acc 値は、モデルの精度です。 ImageNet データセットの検証セット。
    再現方法 yolo val classify data=path/to/ImageNet device=0
  • 速度 を使用してImageNet val画像を平均化した。 Amazon EC2 P4d インスタンス。
    再現方法 yolo val classify data=path/to/ImageNet batch=1 device=0|cpu

トレーニング

画像サイズ64でMNIST160データセット上でYOLO11n-clsを100エポック学習させます。利用可能な引数の完全なリストは、設定ページを参照してください。

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.yaml")  # build a new model from YAML
model = YOLO("yolo11n-cls.pt")  # load a pretrained model (recommended for training)
model = YOLO("yolo11n-cls.yaml").load("yolo11n-cls.pt")  # build from YAML and transfer weights

# Train the model
results = model.train(data="mnist160", epochs=100, imgsz=64)
# Build a new model from YAML and start training from scratch
yolo classify train data=mnist160 model=yolo11n-cls.yaml epochs=100 imgsz=64

# Start training from a pretrained *.pt model
yolo classify train data=mnist160 model=yolo11n-cls.pt epochs=100 imgsz=64

# Build a new model from YAML, transfer pretrained weights to it and start training
yolo classify train data=mnist160 model=yolo11n-cls.yaml pretrained=yolo11n-cls.pt epochs=100 imgsz=64

ヒント

Ultralytics YOLO の分類では、 torchvision.transforms.RandomResizedCrop トレーニング用 torchvision.transforms.CenterCrop 検証と推論のため。 これらのクロップベースの変換は、正方形の入力を前提としており、極端なアスペクト比の画像から重要な領域を誤ってクロップアウトし、トレーニング中に重要な視覚情報が失われる可能性があります。 プロポーションを維持しながら画像を完全に保持するには、以下を使用することを検討してください。 torchvision.transforms.Resize クロップ変換の代わりに。

これは、カスタムを通じて拡張パイプラインをカスタマイズすることで実装できます。 ClassificationDataset および ClassificationTrainer.

import torch
import torchvision.transforms as T

from ultralytics import YOLO
from ultralytics.data.dataset import ClassificationDataset
from ultralytics.models.yolo.classify import ClassificationTrainer, ClassificationValidator


class CustomizedDataset(ClassificationDataset):
    """A customized dataset class for image classification with enhanced data augmentation transforms."""

    def __init__(self, root: str, args, augment: bool = False, prefix: str = ""):
        """Initialize a customized classification dataset with enhanced data augmentation transforms."""
        super().__init__(root, args, augment, prefix)

        # Add your custom training transforms here
        train_transforms = T.Compose(
            [
                T.Resize((args.imgsz, args.imgsz)),
                T.RandomHorizontalFlip(p=args.fliplr),
                T.RandomVerticalFlip(p=args.flipud),
                T.RandAugment(interpolation=T.InterpolationMode.BILINEAR),
                T.ColorJitter(brightness=args.hsv_v, contrast=args.hsv_v, saturation=args.hsv_s, hue=args.hsv_h),
                T.ToTensor(),
                T.Normalize(mean=torch.tensor(0), std=torch.tensor(1)),
                T.RandomErasing(p=args.erasing, inplace=True),
            ]
        )

        # Add your custom validation transforms here
        val_transforms = T.Compose(
            [
                T.Resize((args.imgsz, args.imgsz)),
                T.ToTensor(),
                T.Normalize(mean=torch.tensor(0), std=torch.tensor(1)),
            ]
        )
        self.torch_transforms = train_transforms if augment else val_transforms


class CustomizedTrainer(ClassificationTrainer):
    """A customized trainer class for YOLO classification models with enhanced dataset handling."""

    def build_dataset(self, img_path: str, mode: str = "train", batch=None):
        """Build a customized dataset for classification training and the validation during training."""
        return CustomizedDataset(root=img_path, args=self.args, augment=mode == "train", prefix=mode)


class CustomizedValidator(ClassificationValidator):
    """A customized validator class for YOLO classification models with enhanced dataset handling."""

    def build_dataset(self, img_path: str, mode: str = "train"):
        """Build a customized dataset for classification standalone validation."""
        return CustomizedDataset(root=img_path, args=self.args, augment=mode == "train", prefix=self.args.split)


model = YOLO("yolo11n-cls.pt")
model.train(data="imagenet1000", trainer=CustomizedTrainer, epochs=10, imgsz=224, batch=64)
model.val(data="imagenet1000", validator=CustomizedValidator, imgsz=224, batch=64)

データセット形式

YOLO分類データセット形式の詳細は、データセットガイドに記載されています。

Val

学習済み YOLO11n-cls モデルの検証 精度 MNIST160データセットで実行します。引数は必要ありません。 model 学習内容を保持 data および引数をモデル属性として。

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load an official model
model = YOLO("path/to/best.pt")  # load a custom model

# Validate the model
metrics = model.val()  # no arguments needed, dataset and settings remembered
metrics.top1  # top1 accuracy
metrics.top5  # top5 accuracy
yolo classify val model=yolo11n-cls.pt  # val official model
yolo classify val model=path/to/best.pt # val custom model

ヒント

に記載されているように トレーニングセクションを使用すると、カスタムを使用することで、トレーニング中に極端なアスペクト比を処理できます。 ClassificationTrainer一貫した検証結果を得るには、カスタムの ClassificationValidator 呼び出すとき val() メソッド。完全なコード例については、 トレーニングセクション 実装の詳細について。

予測

トレーニング済みの YOLO11n-cls モデルを使用して、画像に対する予測を実行する。

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load an official model
model = YOLO("path/to/best.pt")  # load a custom model

# Predict with the model
results = model("https://ultralytics.com/images/bus.jpg")  # predict on an image
yolo classify predict model=yolo11n-cls.pt source='https://ultralytics.com/images/bus.jpg'  # predict with official model
yolo classify predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg' # predict with custom model

詳細な predict モードの詳細については、 予測 ページ。

エクスポート

YOLO11n-clsモデルをONNX、CoreMLなどの異なる形式にエクスポートします。

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load an official model
model = YOLO("path/to/best.pt")  # load a custom-trained model

# Export the model
model.export(format="onnx")
yolo export model=yolo11n-cls.pt format=onnx  # export official model
yolo export model=path/to/best.pt format=onnx # export custom-trained model

利用可能なYOLO11-clsのエクスポート形式は、以下の表に記載されています。以下の方法で、任意の形式にエクスポートできます。 format 引数、すなわち、 format='onnx' または format='engine'エクスポートされたモデル上で直接予測または検証を行うことができます。すなわち、 yolo predict model=yolo11n-cls.onnxエクスポート完了後、モデルの使用例が表示されます。

形式format 引数モデルメタデータ引数
PyTorch-yolo11n-cls.pt-
TorchScripttorchscriptyolo11n-cls.torchscriptimgsz, half, dynamic, optimize, nms, batch, device
ONNXonnxyolo11n-cls.onnximgsz, half, dynamic, simplify, opset, nms, batch, device
OpenVINOopenvinoyolo11n-cls_openvino_model/imgsz, half, dynamic, int8, nms, batch, data, fraction, device
TensorRTengineyolo11n-cls.engineimgsz, half, dynamic, simplify, workspace, int8, nms, batch, data, fraction, device
CoreMLcoremlyolo11n-cls.mlpackageimgsz, dynamic, half, int8, nms, batch, device
TF SavedModelsaved_modelyolo11n-cls_saved_model/imgsz, keras, int8, nms, batch, device
TF GraphDefpbyolo11n-cls.pbimgsz, batch, device
TF Litetfliteyolo11n-cls.tfliteimgsz, half, int8, nms, batch, data, fraction, device
TF Edge TPUedgetpuyolo11n-cls_edgetpu.tfliteimgsz, device
TF.jstfjsyolo11n-cls_web_model/imgsz, half, int8, nms, batch, device
PaddlePaddlepaddleyolo11n-cls_paddle_model/imgsz, batch, device
MNNmnnyolo11n-cls.mnnimgsz, batch, int8, half, device
NCNNncnnyolo11n-cls_ncnn_model/imgsz, half, batch, device
IMX500imxyolo11n-cls_imx_model/imgsz, int8, data, fraction, device
RKNNrknnyolo11n-cls_rknn_model/imgsz, batch, name, device
エクゼキュートーチexecutorchyolo11n-cls_executorch_model/imgsz, device
アクセラaxelerayolo11n-cls_axelera_model/imgsz, int8, data, fraction, device

詳細な export 詳細は エクスポート ページ。

よくある質問

画像分類におけるYOLO11の目的は何ですか?

YOLO11モデル(例: yolo11n-cls.pt)は、効率的な画像分類のために設計されています。画像全体のクラスラベルと信頼度スコアを割り当てます。これは、画像内のオブジェクトの位置や形状を特定するのではなく、画像の特定のクラスを知るだけで十分な場合に特に役立ちます。

画像分類のために YOLO11 モデルをトレーニングするにはどうすればよいですか?

YOLO11モデルをトレーニングするには、pythonまたはCLIコマンドを使用できます。たとえば、 yolo11n-cls MNIST160 データセットで、画像サイズ 64 で 100 エポック学習させたモデル:

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load a pretrained model (recommended for training)

# Train the model
results = model.train(data="mnist160", epochs=100, imgsz=64)
yolo classify train data=mnist160 model=yolo11n-cls.pt epochs=100 imgsz=64

その他の構成オプションについては、構成ページをご覧ください。

事前学習済みのYOLO11分類モデルはどこにありますか?

事前学習済みのYOLO11分類モデルは、以下にあります。 モデル セクションを参照してください。のようなモデルは yolo11n-cls.pt, yolo11s-cls.pt, yolo11m-cls.pt)などは、 ImageNet データセットであり、さまざまな画像分類タスクのために簡単にダウンロードして使用できます。

トレーニング済みのYOLO11モデルをさまざまな形式にエクスポートするにはどうすればよいですか?

学習済みのYOLO11モデルは、pythonまたはCLIコマンドを使用してさまざまな形式にエクスポートできます。たとえば、モデルをONNX形式にエクスポートするには:

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load the trained model

# Export the model to ONNX
model.export(format="onnx")
yolo export model=yolo11n-cls.pt format=onnx # export the trained model to ONNX format

詳細なエクスポートオプションについては、Exportページを参照してください。

トレーニング済みのYOLO11分類モデルを検証するにはどうすればよいですか?

MNIST160のようなデータセットで、トレーニング済みモデルの精度を検証するには、次のpythonまたはCLIコマンドを使用できます。

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load the trained model

# Validate the model
metrics = model.val()  # no arguments needed, uses the dataset and settings from training
metrics.top1  # top1 accuracy
metrics.top5  # top5 accuracy
yolo classify val model=yolo11n-cls.pt # validate the trained model

詳細については、Validateセクションをご覧ください。



📅 2年前に作成されました✏️ 0日前に更新されました
glenn-jocherBurhan-QLaughing-qambitious-octopuspderrengerpicsalexRizwanMunawarUltralyticsAssistantMatthewNoycefcakyon

コメント