YOLO Vision 2026:

Bildklassifizierung mit Ultralytics YOLO#

Ultralytics YOLO image classification of objects and scenes

Image classification ist die einfachste der unterstützten Aufgaben und beinhaltet die Klassifizierung eines gesamten Bildes in eine von mehreren vordefinierten Klassen.

Die Ausgabe eines Bildklassifikators ist ein einzelnes Klassenlabel und ein Konfidenzwert. Die Bildklassifizierung ist nützlich, wenn du nur wissen musst, zu welcher Klasse ein Bild gehört, und nicht wissen musst, wo sich Objekte dieser Klasse befinden oder welche exakte Form sie haben.



Watch: Explore Ultralytics YOLO Tasks: Image Classification using Ultralytics Platform
Tipp

YOLO26 Classify-Modelle verwenden das Suffix -cls, d. h. yolo26n-cls.pt, und sind auf ImageNet vorab trainiert.

Models#

Vorab trainierte YOLO26 Classify-Modelle werden hier gezeigt. Detect-, Segment- und Pose-Modelle sind auf dem COCO-Datensatz vorab trainiert, Semantic-Modelle auf Cityscapes und Classify-Modelle auf dem ImageNet-Datensatz.

Modelle werden bei der ersten Verwendung automatisch vom neuesten Ultralytics-Release heruntergeladen.

ModellGröße
(Pixel)
acc
top1
acc
top5
Geschwindigkeit
CPU ONNX
(ms)
Geschwindigkeit
T4 TensorRT10
(ms)
Parameter
(M)
FLOPs
(B) bei 224
YOLO26n-cls22471.490.15.0 ± 0.31.1 ± 0.02.80.5
YOLO26s-cls22476.092.97.9 ± 0.21.3 ± 0.06.71.6
YOLO26m-cls22478.194.217.2 ± 0.42.0 ± 0.011.64.9
YOLO26l-cls22479.094.623.2 ± 0.32.8 ± 0.014.16.2
YOLO26x-cls22479.995.041.4 ± 0.93.8 ± 0.029.613.6
  • acc-Werte sind Modellgenauigkeiten auf dem Validierungssatz des ImageNet-Datensatzes.
    Reproduzieren mit yolo val classify data=path/to/ImageNet device=0
  • Geschwindigkeit gemittelt über ImageNet-Val-Bilder unter Verwendung einer Amazon EC2 P4d-Instanz.
    Reproduzieren mit yolo val classify data=path/to/ImageNet batch=1 device=0|cpu
  • Params- und FLOPs-Werte gelten für das fusionierte Modell nach model.fuse(), welches Conv- und BatchNorm-Schichten zusammenführt. Vortrainierte Checkpoints behalten die vollständige Trainingsarchitektur bei und können höhere Anzahlen aufweisen.

Trainieren#

Trainiere YOLO26n-cls auf dem MNIST160-Datensatz für 100 Epochen bei einer Bildgröße von 64. Eine vollständige Liste der verfügbaren Argumente findest du auf der Configuration-Seite.

Beispiel
from ultralytics import YOLO

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

# Train the model
results = model.train(data="mnist160", epochs=100, imgsz=64)
Tipp

Die Ultralytics YOLO-Klassifizierung verwendet torchvision.transforms.RandomResizedCrop für das Training und torchvision.transforms.CenterCrop für Validierung und Inferenz. Diese auf Zuschneiden basierenden Transformationen setzen quadratische Eingaben voraus und können versehentlich wichtige Regionen aus Bildern mit extremen Seitenverhältnissen ausschneiden, was während des Trainings möglicherweise zum Verlust kritischer visueller Informationen führt. Um das vollständige Bild zu erhalten und gleichzeitig seine Proportionen beizubehalten, ziehe die Verwendung von torchvision.transforms.Resize anstelle von Zuschnitt-Transformationen in Betracht.

Du kannst dies implementieren, indem du deine Augmentierungspipeline durch einen benutzerdefinierten ClassificationDataset und ClassificationTrainer anpasst.

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):
        """Build a customized dataset for classification standalone validation (no augmentation)."""
        return CustomizedDataset(root=img_path, args=self.args, augment=False, prefix=self.args.split)

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

Datensatzformat#

Das Format für YOLO-Klassifizierungsdatensätze findest du detailliert im Dataset Guide. Klassifizierungsdatensätze können auch mit Ultralytics Platform annotation tools verwaltet und mit Labels versehen werden.

Validieren#

Validiere die Genauigkeit des trainierten YOLO26n-cls-Modells auf dem MNIST160-Datensatz. Es sind keine Argumente erforderlich, da der model seine Trainings-data und Argumente als Modellattribute behält.

Beispiel
from ultralytics import YOLO

# Load a model
model = YOLO("yolo26n-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
Tipp

Wie im Training-Abschnitt erwähnt, kannst du extreme Seitenverhältnisse während des Trainings behandeln, indem du einen benutzerdefinierten ClassificationTrainer verwendest. Du musst denselben Ansatz für konsistente Validierungsergebnisse anwenden, indem du beim Aufrufen der val()-Methode einen benutzerdefinierten ClassificationValidator implementierst. Siehe das vollständige Codebeispiel im Training-Abschnitt für Implementierungsdetails.

Vorhersagen#

Verwende ein trainiertes YOLO26n-cls-Modell, um Vorhersagen auf Bildern auszuführen.

Beispiel
from ultralytics import YOLO

# Load a model
model = YOLO("yolo26n-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

# Access the results
for result in results:
    top1 = result.probs.top1  # top predicted class ID
    top1_conf = result.probs.top1conf  # top prediction confidence
    top1_name = result.names[top1]  # top predicted class name

Weitere Details zum predict-Modus findest du auf der Predict-Seite.

Ergebnisausgabe#

Die Bildklassifizierung liefert ein Results-Objekt pro Bild. Das primäre Vorhersagefeld ist result.probs, welches den Klassenwahrscheinlichkeitsvektor und Hilfsmittel für Top-Vorhersagen enthält.

AttributTypFormBeschreibung
result.probsProbs(C,)Klassenwahrscheinlichkeiten.
result.probs.datatorch.float32(C,)Wahrscheinlichkeit pro Klasse.
result.probs.top1int()Top-Klassen-ID.
result.probs.top1conftorch.float32()Top-Konfidenz.
result.probs.top5list[int](<=5)Top-5 Klassen-IDs.

Aufgabenspezifische Results-Felder für alle Aufgaben findest du im Abschnitt Predict Results by Task.

Exportieren#

Exportiere ein YOLO26n-cls-Modell in ein anderes Format wie ONNX, CoreML, etc.

Beispiel
from ultralytics import YOLO

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

# Export the model
model.export(format="onnx")

Verfügbare YOLO26-cls-Exportformate sind in der Tabelle unten aufgeführt. Du kannst mit dem Argument format in jedes Format exportieren, d. h. format='onnx' oder format='engine'. Du kannst direkt mit exportierten Modellen vorhersagen oder validieren, d. h. yolo predict model=yolo26n-cls.onnx. Anwendungsbeispiele werden nach Abschluss des Exports für dein Modell angezeigt.

Formatformat-ArgumentModellMetadatenArgumente
PyTorch-yolo26n-cls.pt-
TorchScripttorchscriptyolo26n-cls.torchscriptimgsz, quantize, dynamic, nms, batch, device
ONNXonnxyolo26n-cls.onnximgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device
OpenVINOopenvinoyolo26n-cls_openvino_model/imgsz, quantize, dynamic, nms, batch, data, fraction, device
TensorRTengineyolo26n-cls.engineimgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device
CoreMLcoremlyolo26n-cls.mlpackageimgsz, dynamic, quantize, nms, batch, device
TF SavedModelsaved_modelyolo26n-cls_saved_model/imgsz, keras, quantize, opset, nms, batch, data, fraction, device
TF GraphDefpbyolo26n-cls.pbimgsz, opset, batch, device
TF Edge TPUedgetpuyolo26n-cls_edgetpu.tfliteimgsz, quantize, opset, data, fraction, device
PaddlePaddlepaddleyolo26n-cls_paddle_model/imgsz, batch, device
MNNmnnyolo26n-cls.mnnimgsz, batch, dynamic, quantize, simplify, opset, nms, device
NCNNncnnyolo26n-cls_ncnn_model/imgsz, quantize, batch, device
IMX500imxyolo26n-cls_imx_model/imgsz, quantize, data, fraction, nms, device
RKNNrknnyolo26n-cls_rknn_model/imgsz, batch, name, quantize, simplify, opset, data, fraction, device
ExecuTorchexecutorchyolo26n-cls_executorch_model/imgsz, batch, device
Axeleraaxelerayolo26n-cls_axelera_model/imgsz, batch, quantize, data, fraction, device
DEEPXdeepxyolo26n-cls_deepx_model/imgsz, quantize, simplify, opset, data, optimize, device
Qualcomm QNNqnnyolo26n-cls_qnn.onnximgsz, batch, name, quantize, simplify, opset, data, fraction, device
LiteRTlitertyolo26n-cls.tfliteimgsz, quantize, batch, data, fraction, device
Hailohailoyolo26n-cls_hailo_model/imgsz, name, quantize, data, fraction, simplify, conf, iou
Huawei Ascendascendyolo26n-cls_ascend_model/imgsz, batch, name, quantize, opset, simplify, nms

Weitere Details zum export-Modus findest du auf der Export-Seite.

FAQ#

  • YOLO26-Modelle, wie yolo26n-cls.pt, sind für eine effiziente Bildklassifizierung konzipiert. Sie weisen einem gesamten Bild ein einzelnes Klassenlabel zusammen mit einem Konfidenzwert zu. Dies ist besonders nützlich für Anwendungen, bei denen es ausreicht, die spezifische Klasse eines Bildes zu kennen, anstatt den Ort oder die Form von Objekten innerhalb des Bildes zu identifizieren.

  • Um ein YOLO26-Modell zu trainieren, kannst du entweder Python- oder CLI-Befehle verwenden. Zum Beispiel, um ein yolo26n-cls-Modell auf dem MNIST160-Datensatz für 100 Epochen bei einer Bildgröße von 64 zu trainieren:

    Beispiel
    from ultralytics import YOLO
    
    # Load a model
    model = YOLO("yolo26n-cls.pt")  # load a pretrained model (recommended for training)
    
    # Train the model
    results = model.train(data="mnist160", epochs=100, imgsz=64)

    Für weitere Konfigurationsoptionen besuche die Configuration-Seite.

  • Vorab trainierte YOLO26-Klassifizierungsmodelle findest du im Models-Abschnitt. Modelle wie yolo26n-cls.pt, yolo26s-cls.pt, yolo26m-cls.pt usw. sind auf dem ImageNet-Datensatz vorab trainiert und können einfach heruntergeladen und für verschiedene Bildklassifizierungsaufgaben verwendet werden.

  • Du kannst ein trainiertes YOLO26-Modell mit Python- oder CLI-Befehlen in verschiedene Formate exportieren. Zum Beispiel, um ein Modell in das ONNX-Format zu exportieren:

    Beispiel
    from ultralytics import YOLO
    
    # Load a model
    model = YOLO("yolo26n-cls.pt")  # load the trained model
    
    # Export the model to ONNX
    model.export(format="onnx")

    Detaillierte Exportoptionen findest du auf der Export-Seite.

  • Um die Genauigkeit eines trainierten Modells auf einem Datensatz wie MNIST160 zu validieren, kannst du die folgenden Python- oder CLI-Befehle verwenden:

    Beispiel
    from ultralytics import YOLO
    
    # Load a model
    model = YOLO("yolo26n-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

    Weitere Informationen findest du im Validate-Abschnitt.

Kommentare