Bildklassifizierung
Bildklassifizierung ist die einfachste der drei Aufgaben und beinhaltet die Klassifizierung eines gesamten Bildes in eine von mehreren vordefinierten Klassen.
Die Ausgabe eines Bildklassifikators ist eine einzelne Klassenbezeichnung und ein Konfidenzwert. Die Bildklassifizierung ist nützlich, wenn Sie nur wissen müssen, zu welcher Klasse ein Bild gehört, und nicht wissen müssen, wo sich Objekte dieser Klasse befinden oder wie ihre genaue Form ist.
Ansehen: Entdecken Sie Ultralytics YOLO Tasks: Bildklassifizierung mit Ultralytics HUB
Tipp
YOLO11 Classify Modelle verwenden das -cls
Suffix, d.h. yolo11n-cls.pt
und sind vortrainiert auf ImageNet.
Modelle
Vortrainierte YOLO11 Classify Modelle werden hier gezeigt. Detect-, Segment- und Pose-Modelle sind auf dem COCO-Datensatz vortrainiert, während Classify-Modelle auf dem ImageNet-Datensatz vortrainiert sind.
Modelle werden beim ersten Gebrauch automatisch von der neuesten Ultralytics Version heruntergeladen.
Modell | Größe (Pixel) |
acc top1 |
acc top5 |
Geschwindigkeit CPU ONNX (ms) |
Geschwindigkeit T4 TensorRT10 (ms) |
Parameter (M) |
FLOPs (B) bei 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 Werte sind die Modellgenauigkeiten auf dem ImageNet Validierungsdatensatz.
Reproduzieren durchyolo val classify data=path/to/ImageNet device=0
- Geschwindigkeit gemittelt über ImageNet val Bilder unter Verwendung einer Amazon EC2 P4d Instanz.
Reproduzieren durchyolo val classify data=path/to/ImageNet batch=1 device=0|cpu
Trainieren
Trainieren Sie YOLO11n-cls auf dem MNIST160-Datensatz für 100 Epochen bei einer Bildgröße von 64. Eine vollständige Liste der verfügbaren Argumente finden Sie auf der Seite Konfiguration.
Beispiel
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
Tipp
Die Ultralytics YOLO-Klassifizierung verwendet torchvision.transforms.RandomResizedCrop
für Training und torchvision.transforms.CenterCrop
für Validierung und Inferenz.
Diese auf dem Zuschneiden basierenden Transformationen setzen quadratische Eingaben voraus und können unbeabsichtigt wichtige Bereiche aus Bildern mit extremen Seitenverhältnissen ausschneiden, was möglicherweise zu einem Verlust kritischer visueller Informationen während des Trainings führt.
Um das vollständige Bild unter Beibehaltung seiner Proportionen zu erhalten, sollten Sie die Verwendung von torchvision.transforms.Resize
anstelle von Zuschneide-Transformationen.
Sie können dies implementieren, indem Sie Ihre Augmentierungspipeline durch eine benutzerdefinierte anpassen. ClassificationDataset
und 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)
Datensatzformat
Das YOLO-Klassifikationsdatensatzformat ist detailliert im Dataset Guide zu finden.
Validieren
Validieren Sie das trainierte YOLO11n-cls-Modell Genauigkeit auf dem MNIST160-Datensatz. Es werden keine Argumente benötigt, da das model
behält sein Training data
und Argumente als Modellattribute.
Beispiel
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
Tipp
Wie erwähnt in der Trainingsbereich, können Sie extreme Seitenverhältnisse während des Trainings verarbeiten, indem Sie ein benutzerdefiniertes ClassificationTrainer
Sie müssen denselben Ansatz für konsistente Validierungsergebnisse anwenden, indem Sie eine benutzerdefinierte ClassificationValidator
beim Aufruf der val()
Methode. Das vollständige Codebeispiel finden Sie im Trainingsbereich für Implementierungsdetails.
Vorhersagen
Verwenden Sie ein trainiertes YOLO11n-cls-Modell, um Vorhersagen auf Bildern auszuführen.
Beispiel
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
Vollständige predict
Details zum Modus finden Sie auf der Vorhersagen Seite.
Export
Exportieren Sie ein YOLO11n-cls-Modell in ein anderes Format wie ONNX, CoreML usw.
Beispiel
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
Die verfügbaren YOLO11-cls-Exportformate sind in der folgenden Tabelle aufgeführt. Sie können mit dem format
Argument in ein beliebiges Format exportieren, z. B. format='onnx'
oder format='engine'
. Sie können direkt mit exportierten Modellen Vorhersagen treffen oder diese validieren, z. B. yolo predict model=yolo11n-cls.onnx
. Anwendungsbeispiele werden nach Abschluss des Exports für Ihr Modell angezeigt.
Format | format Argument |
Modell | Metadaten | Argumente |
---|---|---|---|---|
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 |
Vollständige export
Details auf der Export Seite.
FAQ
Was ist der Zweck von YOLO11 bei der Bildklassifizierung?
YOLO11-Modelle, wie z. B. yolo11n-cls.pt
, sind für eine effiziente Bildklassifizierung konzipiert. Sie weisen einem gesamten Bild eine einzelne Klassenbezeichnung 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 die Position oder Form von Objekten innerhalb des Bildes zu identifizieren.
Wie trainiere ich ein YOLO11-Modell für die Bildklassifizierung?
Um ein YOLO11-Modell zu trainieren, können Sie entweder Python- oder CLI-Befehle verwenden. Um beispielsweise ein yolo11n-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("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
Weitere Konfigurationsoptionen finden Sie auf der Seite Konfiguration.
Wo finde ich vortrainierte YOLO11-Klassifizierungsmodelle?
Vorab trainierte YOLO11-Klassifizierungsmodelle finden Sie im Abschnitt Modelle Abschnitt. Modelle wie yolo11n-cls.pt
, yolo11s-cls.pt
, yolo11m-cls.pt
usw. sind auf dem ImageNet Datensatz und kann einfach heruntergeladen und für verschiedene Bildklassifizierungsaufgaben verwendet werden.
Wie kann ich ein trainiertes YOLO11-Modell in verschiedene Formate exportieren?
Sie können ein trainiertes YOLO11-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("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
Detaillierte Exportoptionen finden Sie auf der Seite Export.
Wie validiere ich ein trainiertes YOLO11-Klassifizierungsmodell?
Um die Genauigkeit eines trainierten Modells auf einem Datensatz wie MNIST160 zu validieren, können Sie die folgenden Python- oder CLI-Befehle verwenden:
Beispiel
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
Weitere Informationen finden Sie im Abschnitt Validieren.