Link to this sectionBildklassifizierung#
Bildklassifizierung 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
YOLO26 Classify-Modelle verwenden das Suffix -cls, d. h. yolo26n-cls.pt, und sind auf ImageNet vortrainiert.
Link to this sectionModelle#
Hier sind die vortrainierten YOLO26 Classify-Modelle aufgeführt. Detect-, Segment- und Pose-Modelle sind auf dem COCO-Datensatz vortrainiert, Semantic-Modelle sind auf Cityscapes vortrainiert und Classify-Modelle sind auf dem ImageNet-Datensatz vortrainiert.
Modelle werden bei der ersten Verwendung automatisch von der neuesten Ultralytics Release 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.5 |
| YOLO26s-cls | 224 | 76.0 | 92.9 | 7.9 ± 0.2 | 1.3 ± 0.0 | 6.7 | 1.6 |
| YOLO26m-cls | 224 | 78.1 | 94.2 | 17.2 ± 0.4 | 2.0 ± 0.0 | 11.6 | 4.9 |
| YOLO26l-cls | 224 | 79.0 | 94.6 | 23.2 ± 0.3 | 2.8 ± 0.0 | 14.1 | 6.2 |
| YOLO26x-cls | 224 | 79,9 | 95,0 | 41,4 ± 0,9 | 3,8 ± 0,0 | 29,6 | 13,6 |
- acc-Werte sind Modellgenauigkeiten auf dem ImageNet-Validierungsdatensatz.
Reproduziere dies mityolo val classify data=path/to/ImageNet device=0 - Speed wurde über ImageNet-Validierungsbilder unter Verwendung einer Amazon EC2 P4d-Instanz gemittelt.
Reproduziere dies mityolo val classify data=path/to/ImageNet batch=1 device=0|cpu - Params und FLOPs-Werte gelten für das gefuste Modell nach
model.fuse(), welches Conv- und BatchNorm-Layer zusammenführt. Vortrainierte Checkpoints behalten die vollständige Trainingsarchitektur bei und können höhere Anzahlen aufweisen.
Link to this sectionTrainieren#
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 Konfigurationsseite.
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 Ultralytics YOLO-Klassifizierung verwendet torchvision.transforms.RandomResizedCrop für das Training und torchvision.transforms.CenterCrop für die Validierung und Inferenz.
Diese auf Zuschneiden basierenden Transformationen setzen quadratische Eingaben voraus und können unbeabsichtigt wichtige Bereiche von Bildern mit extremen Seitenverhältnissen abschneiden, was während des Trainings potenziell zum Verlust kritischer visueller Informationen führen kann.
Um das vollständige Bild unter Beibehaltung der Proportionen zu bewahren, erwäge die Verwendung von torchvision.transforms.Resize anstelle von Zuschneide-Transformationen.
Du kannst dies umsetzen, indem du deine Augmentierungs-Pipeline durch 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="imagenet1000", trainer=CustomizedTrainer, epochs=10, imgsz=224, batch=64)
model.val(data="imagenet1000", validator=CustomizedValidator, imgsz=224, batch=64)Link to this sectionDatensatzformat#
Das YOLO-Klassifizierungs-Datensatzformat findest du im Detail im Datensatz-Leitfaden. Klassifizierungsdatensätze können auch auf der Ultralytics Plattform verwaltet und gelabelt werden.
Link to this sectionValidieren#
Validiere die Genauigkeit des trainierten YOLO26n-cls-Modells auf dem MNIST160-Datensatz. Es sind keine Argumente erforderlich, da das model seine Trainings-data und Argumente als Modellattribute 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 extreme Seitenverhältnisse während des Trainings handhaben, indem du einen benutzerdefinierten ClassificationTrainer verwendest. Du musst denselben Ansatz für konsistente Validierungsergebnisse anwenden, indem du einen benutzerdefinierten ClassificationValidator beim Aufruf der val()-Methode implementierst. Siehe das vollständige Codebeispiel im Trainingsabschnitt für Implementierungsdetails.
Link to this sectionVorhersagen#
Verwende ein trainiertes YOLO26n-cls-Modell, um Vorhersagen auf Bildern 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 nameSiehe vollständige Details zum predict-Modus auf der Predict-Seite.
Link to this sectionErgebnisausgabe#
Die Bildklassifizierung liefert ein Results-Objekt pro Bild. Das primäre Vorhersagefeld ist result.probs, das den Klassen-Wahrscheinlichkeitsvektor und Hilfsprogramme für Top-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 | () | Top-Klassen-ID. |
result.probs.top1conf | torch.float32 | () | Top-Konfidenz. |
result.probs.top5 | list[int] | (<=5) | Top-5 Klassen-IDs. |
Für aufgaben-spezifische Results-Felder für jede Aufgabe siehe den Abschnitt Vorhersageergebnisse nach Aufgabe.
Link to this sectionExportieren#
Exportiere ein YOLO26n-cls-Modell in ein anderes Format wie ONNX, CoreML, etc.
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 in jedes Format unter Verwendung des format-Arguments exportieren, d. h. format='onnx' oder format='engine'. Du kannst direkt auf exportierten Modellen vorhersagen oder validieren, d. h. yolo predict model=yolo26n-cls.onnx. Anwendungsbeispiele werden für dein Modell nach Abschluss des Exports angezeigt.
| Format | format-Argument | Modell | Metadaten | Argumente |
|---|---|---|---|---|
| PyTorch | - | yolo26n-cls.pt | ✅ | - |
| TorchScript | torchscript | yolo26n-cls.torchscript | ✅ | imgsz, half, dynamic, optimize, nms, batch, device |
| ONNX | onnx | yolo26n-cls.onnx | ✅ | imgsz, half, int8, dynamic, simplify, opset, nms, batch, data, fraction, device |
| OpenVINO | openvino | yolo26n-cls_openvino_model/ | ✅ | imgsz, half, dynamic, int8, nms, batch, data, fraction, device |
| TensorRT | engine | yolo26n-cls.engine | ✅ | imgsz, half, dynamic, simplify, workspace, int8, nms, batch, data, fraction, device |
| CoreML | coreml | yolo26n-cls.mlpackage | ✅ | imgsz, dynamic, half, int8, nms, batch, device |
| TF SavedModel | saved_model | yolo26n-cls_saved_model/ | ✅ | imgsz, keras, int8, nms, batch, data, fraction, device |
| TF GraphDef | pb | yolo26n-cls.pb | ❌ | imgsz, batch, device |
| TF Lite | tflite | yolo26n-cls.tflite | ✅ | imgsz, half, int8, nms, batch, data, fraction, device |
| TF Edge TPU | edgetpu | yolo26n-cls_edgetpu.tflite | ✅ | imgsz, int8, data, fraction, device |
| TF.js | tfjs | yolo26n-cls_web_model/ | ✅ | imgsz, half, int8, nms, batch, data, fraction, device |
| PaddlePaddle | paddle | yolo26n-cls_paddle_model/ | ✅ | imgsz, batch, device |
| MNN | mnn | yolo26n-cls.mnn | ✅ | imgsz, batch, int8, half, device |
| NCNN | ncnn | yolo26n-cls_ncnn_model/ | ✅ | imgsz, half, batch, device |
| IMX500 | imx | yolo26n-cls_imx_model/ | ✅ | imgsz, int8, data, fraction, nms, device |
| RKNN | rknn | yolo26n-cls_rknn_model/ | ✅ | imgsz, batch, name, int8, data, fraction, device |
| ExecuTorch | executorch | yolo26n-cls_executorch_model/ | ✅ | imgsz, batch, device |
| Axelera | axelera | yolo26n-cls_axelera_model/ | ✅ | imgsz, batch, int8, data, fraction, device |
| DEEPX | deepx | yolo26n-cls_deepx_model/ | ✅ | imgsz, int8, data, optimize, device |
| Qualcomm QNN | qnn | yolo26n-cls_qnn_model/ | ✅ | imgsz, batch, name, int8, data, fraction, device |
Siehe vollständige export Details auf der Export Seite.
Link to this sectionFAQ#
Link to this sectionWas ist der Zweck von YOLO26 bei der Bildklassifizierung?#
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 das Wissen über die spezifische Klasse eines Bildes ausreicht, anstatt den Ort oder die Form von Objekten innerhalb des Bildes zu identifizieren.
Link to this sectionWie trainiere ich ein YOLO26-Modell für die Bildklassifizierung?#
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:
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 Konfigurationsseite.
Link to this sectionWo finde ich vortrainierte YOLO26-Klassifizierungsmodelle?#
Vortrainierte YOLO26-Klassifizierungsmodelle findest du im Bereich Modelle. Modelle wie yolo26n-cls.pt, yolo26s-cls.pt, yolo26m-cls.pt usw. sind auf dem ImageNet-Datensatz vortrainiert und können einfach heruntergeladen und für verschiedene Bildklassifizierungsaufgaben verwendet werden.
Link to this sectionWie kann ich ein trainiertes YOLO26-Modell in verschiedene Formate exportieren?#
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:
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")Für detaillierte Exportoptionen siehe die Export-Seite.
Link to this sectionWie validiere ich ein trainiertes YOLO26-Klassifizierungsmodell?#
Um die Genauigkeit eines trainierten Modells auf einem Datensatz wie MNIST160 zu validieren, kannst du die folgenden Python- oder CLI-Befehle verwenden:
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 accuracyFür weitere Informationen besuche den Abschnitt Validieren.