Bildklassifizierung mit Ultralytics YOLO#
Bildklassifizierung ist die einfachste der unterstützten Aufgaben und umfasst die Klassifizierung eines gesamten Bildes in eine von mehreren vordefinierten Klassen.
Die Ausgabe eines Bildklassifizierers besteht aus einem einzelnen Klassenlabel und einem Konfidenzwert. Die Bildklassifizierung ist nützlich, wenn du nur wissen musst, zu welcher Klasse ein Bild gehört, und nicht, wo sich Objekte dieser Klasse befinden oder welche genaue Form sie haben.
Watch: Explore Ultralytics YOLO Tasks: Image Classification using Ultralytics Platform
YOLO26-Classify-Modelle verwenden das Suffix -cls, also yolo26n-cls.pt, und sind auf ImageNet vortrainiert.
Modelle#
Hier werden vortrainierte YOLO26-Classify-Modelle gezeigt. Detect-, Segment- und Pose-Modelle sind auf dem Datensatz COCO vortrainiert, Semantic-Modelle auf Cityscapes und Classify-Modelle auf dem Datensatz ImageNet.
Modelle werden bei der ersten Verwendung automatisch aus dem neuesten Release von Ultralytics heruntergeladen.
| Modell | Größe (Pixel) | acc top1 | acc top5 | Geschwindigkeit CPU ONNX (ms) | Geschwindigkeit T4 TensorRT10 (ms) | Parameter (M) | FLOPs (B) bei 224 |
|---|---|---|---|---|---|---|---|
| YOLO26n-cls | 224 | 71.4 | 90.1 | 5.0 ± 0.3 | 1.1 ± 0.0 | 2.8 | 0.4 |
| YOLO26s-cls | 224 | 76.0 | 92.9 | 7.9 ± 0.2 | 1.3 ± 0.0 | 6.7 | 1.5 |
| YOLO26m-cls | 224 | 78.1 | 94.2 | 17.2 ± 0.4 | 2.0 ± 0.0 | 11.6 | 4.8 |
| YOLO26l-cls | 224 | 79.0 | 94.6 | 23.2 ± 0.3 | 2.8 ± 0.0 | 14.1 | 6.0 |
| YOLO26x-cls | 224 | 79.9 | 95.0 | 41.4 ± 0.9 | 3.8 ± 0.0 | 29.6 | 13.5 |
- Die acc-Werte sind die Modellgenauigkeiten auf dem Validierungssatz des Datensatzes ImageNet.
Reproduzieren mityolo val classify data=path/to/ImageNet device=0 - Speed wurde über ImageNet-Validierungsbilder auf einer Amazon-EC2-P4d-Instanz gemittelt.
Reproduzieren mityolo val classify data=path/to/ImageNet batch=1 device=0|cpu - Die Werte für Params und FLOPs gelten für das fusionierte Modell nach
model.fuse(), das Conv- und BatchNorm-Schichten zusammenführt. Vortrainierte Checkpoints enthalten weiterhin die vollständige Trainingsarchitektur und können daher höhere Werte aufweisen.
Sieh dir die unreleased YOLO27 preview an, um vorläufige Klassifizierungsgeschwindigkeiten und Modellgrößen zu erfahren.
Trainieren#
Trainiere YOLO26n-cls 100 Epochen lang mit einer Bildgröße von 64 auf dem Datensatz MNIST160. Eine vollständige Liste der verfügbaren Argumente findest du auf der Seite Configuration.
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)Die Klassifizierung mit Ultralytics YOLO 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 bei Bildern mit extremen Seitenverhältnissen unbeabsichtigt wichtige Bereiche abschneiden, wodurch während des Trainings möglicherweise kritische visuelle Informationen verloren gehen.
Um das vollständige Bild unter Beibehaltung seiner Proportionen zu erhalten, solltest du stattdessen torchvision.transforms.Resize anstelle von Transformationen zum Zuschneiden verwenden.
Du kannst dies umsetzen, indem du deine Augmentierungspipeline über ein benutzerdefiniertes 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="imagenet", trainer=CustomizedTrainer, epochs=10, imgsz=224, batch=64)
model.val(data="imagenet", validator=CustomizedValidator, imgsz=224, batch=64)Datensatzformat#
Das Format von YOLO-Klassifizierungsdatensätzen wird ausführlich im Datensatzleitfaden beschrieben. Klassifizierungsdatensätze können außerdem mit den Annotationstools der Ultralytics Platform verwaltet und beschriftet werden.
Validierung#
Validiere die Genauigkeit des trainierten YOLO26n-cls-Modells auf dem Datensatz MNIST160. Es sind keine Argumente erforderlich, da model seine Trainings-data und Argumente als Modelleigenschaften beibehält.
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 accuracyWie im Trainingsabschnitt erwähnt, kannst du während des Trainings mit einem benutzerdefinierten ClassificationTrainer mit extremen Seitenverhältnissen umgehen. Für konsistente Validierungsergebnisse musst du denselben Ansatz anwenden, indem du beim Aufruf der Methode val() ein benutzerdefiniertes ClassificationValidator implementierst. Einzelheiten zur Implementierung findest du im vollständigen Codebeispiel im Trainingsabschnitt.
Vorhersage#
Verwende ein trainiertes YOLO26n-cls-Modell, um Vorhersagen für Bilder auszuführen.
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 nameAusführliche Informationen zum Modus predict findest du auf der Seite Predict.
Ausgabe der Ergebnisse#
Die Bildklassifizierung gibt pro Bild ein Results-Objekt zurück. Das wichtigste Vorhersagefeld ist result.probs, das den Klassenwahrscheinlichkeitsvektor und Hilfsfunktionen für die besten Vorhersagen enthält.
| Attribut | Typ | Form | Beschreibung |
|---|---|---|---|
result.probs | Probs | (C,) | Klassenwahrscheinlichkeiten. |
result.probs.data | torch.float32 | (C,) | Wahrscheinlichkeit pro Klasse. |
result.probs.top1 | int | () | ID der obersten Klasse. |
result.probs.top1conf | torch.float32 | () | Höchster Konfidenzwert. |
result.probs.top5 | list[int] | (<=5) | Top-5-Klassen-IDs. |
Task-spezifische Felder Results für alle Tasks findest du im Abschnitt Vorhersageergebnisse nach Task.
Export#
Exportiere ein YOLO26n-cls-Modell in ein anderes Format wie ONNX, CoreML usw.
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")Die verfügbaren Exportformate für YOLO26-cls findest du in der folgenden Tabelle. Du kannst mit dem Argument format in jedes Format exportieren, also beispielsweise mit format='onnx' oder format='engine'. Du kannst direkt auf exportierten Modellen Vorhersagen ausführen oder sie validieren, beispielsweise mit yolo predict model=yolo26n-cls.onnx. Nach Abschluss des Exports werden Nutzungsbeispiele für dein Modell angezeigt.
| Format | Argument format | Modell | Metadaten | Argumente |
|---|---|---|---|---|
| PyTorch | - | yolo26n-cls.pt | ✅ | - |
| TorchScript | torchscript | yolo26n-cls.torchscript | ✅ | imgsz, quantize, dynamic, nms, batch, device |
| ONNX | onnx | yolo26n-cls.onnx | ✅ | imgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device |
| OpenVINO | openvino | yolo26n-cls_openvino_model/ | ✅ | imgsz, quantize, dynamic, nms, batch, data, fraction, device |
| TensorRT | engine | yolo26n-cls.engine | ✅ | imgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device |
| CoreML | coreml | yolo26n-cls.mlpackage | ✅ | imgsz, dynamic, quantize, nms, batch, device |
| TF SavedModel | saved_model | yolo26n-cls_saved_model/ | ✅ | imgsz, keras, quantize, opset, nms, batch, data, fraction, device |
| TF GraphDef | pb | yolo26n-cls.pb | ❌ | imgsz, opset, batch, device |
| TF Edge TPU | edgetpu | yolo26n-cls_edgetpu.tflite | ✅ | imgsz, quantize, opset, data, fraction, device |
| PaddlePaddle | paddle | yolo26n-cls_paddle_model/ | ✅ | imgsz, batch, device |
| MNN | mnn | yolo26n-cls.mnn | ✅ | imgsz, batch, dynamic, quantize, simplify, opset, nms, device |
| NCNN | ncnn | yolo26n-cls_ncnn_model/ | ✅ | imgsz, quantize, batch, device |
| IMX500 | imx | yolo26n-cls_imx_model/ | ✅ | imgsz, quantize, data, fraction, nms, device |
| RKNN | rknn | yolo26n-cls_rknn_model/ | ✅ | imgsz, batch, name, quantize, simplify, opset, data, fraction, device |
| ExecuTorch | executorch | yolo26n-cls_executorch_model/ | ✅ | imgsz, batch, device |
| Axelera | axelera | yolo26n-cls_axelera_model/ | ✅ | imgsz, batch, quantize, data, fraction, device |
| DEEPX | deepx | yolo26n-cls_deepx_model/ | ✅ | imgsz, quantize, simplify, opset, data, optimize, device |
| Qualcomm QNN | qnn | yolo26n-cls_qnn.onnx | ✅ | imgsz, batch, name, quantize, simplify, opset, data, fraction, device |
| LiteRT | litert | yolo26n-cls.tflite | ✅ | imgsz, quantize, batch, data, fraction, device |
| Hailo | hailo | yolo26n-cls_hailo_model/ | ✅ | imgsz, name, quantize, data, fraction, simplify, conf, iou |
| Huawei Ascend | ascend | yolo26n-cls_ascend_model/ | ✅ | imgsz, batch, name, quantize, opset, simplify, nms |
| Apple Core AI | coreai | yolo26n-cls.aimodel | ✅ | imgsz, batch, quantize |
nms=None verwendet standardmäßig Rohausgaben für externes NMS. Setze nms=False, um einen verfügbaren NMS-freien Kopf auszuwählen; nicht unterstützte Formate greifen auf ihren nativen Ausgabepfad zurück. Die Einträge nms oben identifizieren Formate, die NMS mit nms=True einbetten können.
Ausführliche Informationen zu export findest du auf der Seite Export.
FAQ#
YOLO26-Modelle wie
yolo26n-cls.ptsind 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 die Kenntnis der spezifischen Bildklasse ausreicht, anstatt die Position oder Form von Objekten im Bild zu bestimmen.Zum Trainieren eines YOLO26-Modells kannst du entweder Python oder CLI-Befehle verwenden. Um beispielsweise ein
yolo26n-cls-Modell 100 Epochen lang mit einer Bildgröße von 64 auf dem Datensatz MNIST160 zu trainieren:Beispielfrom 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)Weitere Konfigurationsoptionen findest du auf der Seite Configuration.
Du kannst ein trainiertes YOLO26-Modell mit Python oder CLI-Befehlen in verschiedene Formate exportieren. Um beispielsweise ein Modell in das ONNX-Format zu exportieren:
Beispielfrom 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 Seite Export.
Um die Genauigkeit eines trainierten Modells auf einem Datensatz wie MNIST160 zu validieren, kannst du die folgenden Python- oder CLI-Befehle verwenden:
Beispielfrom 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 accuracyWeitere Informationen findest du im Abschnitt Validate.