コンテンツにスキップ

画像分類

画像分類の例

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

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



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

ヒント

YOLO11 Classifyモデルは、以下を使用します。 -cls サフィックス(例:) yolo11n-cls.pt で事前トレーニングされています。 ImageNet.

モデル

ここに表示されているのは、YOLO11の学習済みClassifyモデルです。Detect、Segment、PoseモデルはCOCOデータセットで事前学習されていますが、ClassifyモデルはImageNetデータセットで事前学習されています。

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

モデル サイズ
(ピクセル)
acc
top1
acc
top5
速度
CPU ONNX
(ms)
速度
T4 TensorRT10
(ms)
params
(M)
FLOPs
(B) at 224
YOLO11n-cls 224 70.0 89.4 5.0 ± 0.3 1.1 ± 0.0 1.6 0.5
YOLO11s-cls 224 75.4 92.7 7.9 ± 0.2 1.3 ± 0.0 5.5 1.6
YOLO11m-cls 224 77.3 93.9 17.2 ± 0.4 2.0 ± 0.0 10.4 5.0
YOLO11l-cls 224 78.3 94.3 23.2 ± 0.3 2.8 ± 0.0 12.9 6.2
YOLO11x-cls 224 79.5 94.9 41.4 ± 0.9 3.8 ± 0.0 28.4 13.7
  • 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 -
TorchScript torchscript yolo11n-cls.torchscript imgsz, half, dynamic, optimize, nms, batch, device
ONNX onnx yolo11n-cls.onnx imgsz, half, dynamic, simplify, opset, nms, batch, device
OpenVINO openvino yolo11n-cls_openvino_model/ imgsz, half, dynamic, int8, nms, batch, data, fraction, device
TensorRT engine yolo11n-cls.engine imgsz, half, dynamic, simplify, workspace, int8, nms, batch, data, fraction, device
CoreML coreml yolo11n-cls.mlpackage imgsz, half, int8, nms, batch, device
TF SavedModel saved_model yolo11n-cls_saved_model/ imgsz, keras, int8, nms, batch, device
TF GraphDef pb yolo11n-cls.pb imgsz, batch, device
TF Lite tflite yolo11n-cls.tflite imgsz, half, int8, nms, batch, data, fraction, device
TF Edge TPU edgetpu yolo11n-cls_edgetpu.tflite imgsz, device
TF.js tfjs yolo11n-cls_web_model/ imgsz, half, int8, nms, batch, device
PaddlePaddle paddle yolo11n-cls_paddle_model/ imgsz, batch, device
MNN mnn yolo11n-cls.mnn imgsz, batch, int8, half, device
NCNN ncnn yolo11n-cls_ncnn_model/ imgsz, half, batch, device
IMX500 imx yolo11n-cls_imx_model/ imgsz, int8, data, fraction, device
RKNN rknn yolo11n-cls_rknn_model/ imgsz, batch, name, 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セクションをご覧ください。



📅 1年前に作成 ✏️ 6日前に更新

コメント