图像分类
图像分类是这三项任务中最简单的,它涉及将整个图像归类为一组预定义类别中的一个。
图像分类器的输出是一个单一的类标签和一个置信度分数。当你只需要知道图像属于哪一类,而不需要知道该类对象的位置或确切形状时,图像分类就很有用。
Watch: Explore Ultralytics YOLO Tasks: Image Classification using Ultralytics Platform
YOLO26 Classify 模型使用 -cls 后缀,例如 yolo26n-cls.pt,并已在 ImageNet 上进行预训练。
模型
此处展示了 YOLO26 预训练的 Classify 模型。Detect、Segment 和 Pose 模型在 COCO 数据集上进行预训练,而 Classify 模型则在 ImageNet 数据集上进行预训练。
模型在首次使用时会自动从最新的 Ultralytics 发布版本中下载。
| 模型 | 尺寸 (像素) | 准确率 top1 | 准确率 top5 | 速度 CPU ONNX (ms) | 速度 T4 TensorRT10 (ms) | 参数 (M) | FLOPs (B) 在 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 值是模型在 ImageNet 数据集验证集上的准确率。
可通过yolo val classify data=path/to/ImageNet device=0进行复现 - 速度是在 Amazon EC2 P4d 实例上使用 ImageNet 验证集图像计算的平均值。
可通过yolo val classify data=path/to/ImageNet batch=1 device=0|cpu进行复现 - Params(参数量)和 FLOPs(浮点运算次数)值是
model.fuse()之后融合模型的数值,它合并了 Conv 和 BatchNorm 层。预训练的检查点保留了完整的训练架构,因此显示的数值可能更高。
训练
在 MNIST160 数据集上训练 YOLO26n-cls,设置 100 个 epoch,图像大小为 64。如需可用参数的完整列表,请参阅配置页面。
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)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("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)数据集格式
YOLO 分类数据集格式的详细信息可以在数据集指南中找到。分类数据集也可以在 Ultralytics Platform 上进行管理和标注。
验证
在 MNIST160 数据集上验证训练好的 YOLO26n-cls 模型准确率。不需要额外的参数,因为 model 会保留其训练时的 data 和参数作为模型属性。
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 accuracyAs mentioned in the training section, you can handle extreme aspect ratios during training by using a custom ClassificationTrainer. You need to apply the same approach for consistent validation results by implementing a custom ClassificationValidator when calling the val() method. Refer to the complete code example in the training section for implementation details.
预测
使用训练好的 YOLO26n-cls 模型对图像进行预测。
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 imageSee full predict mode details in the Predict page.
导出
将 YOLO26n-cls 模型导出为 ONNX、CoreML 等其他格式。
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")可用的 YOLO26-cls 导出格式如下表所示。你可以使用 format 参数导出为任何格式,例如 format='onnx' 或 format='engine'。你可以直接在导出的模型上进行预测或验证,例如 yolo predict model=yolo26n-cls.onnx。导出完成后,将显示模型的使用示例。
| 格式 | format 参数 | 模型 | 元数据 | 参数 |
|---|---|---|---|---|
| PyTorch | - | yolo26n-cls.pt | ✅ | - |
| TorchScript | torchscript | yolo26n-cls.torchscript | ✅ | imgsz, half, dynamic, optimize, nms, batch, device |
| ONNX | onnx | yolo26n-cls.onnx | ✅ | imgsz, half, dynamic, simplify, opset, nms, batch, 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, 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 |
See full export details in the Export page.
常见问题 (FAQ)
YOLO26 在图像分类中的用途是什么?
YOLO26 模型(如 yolo26n-cls.pt)专为高效的图像分类而设计。它们将单一的类标签和一个置信度分数分配给整个图像。这对于那些只需要知道图像所属具体类别的应用场景特别有用,而不需要识别图像中对象的位置或形状。
我该如何训练 YOLO26 模型进行图像分类?
你可以使用 Python 或 CLI 命令来训练 YOLO26 模型。例如,在 MNIST160 数据集上训练 yolo26n-cls 模型,设置 100 个 epoch,图像大小为 64:
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)如需更多配置选项,请访问配置页面。
我在哪里可以找到预训练的 YOLO26 分类模型?
可以在模型部分找到预训练的 YOLO26 分类模型。像 yolo26n-cls.pt、yolo26s-cls.pt、yolo26m-cls.pt 等模型都在 ImageNet 数据集上进行了预训练,可以轻松下载并用于各种图像分类任务。
我该如何将训练好的 YOLO26 模型导出为不同格式?
你可以使用 Python 或 CLI 命令将训练好的 YOLO26 模型导出为各种格式。例如,导出模型到 ONNX 格式:
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")有关详细的导出选项,请参阅导出页面。
我该如何验证训练好的 YOLO26 分类模型?
若要验证训练好的模型在 MNIST160 等数据集上的准确率,可以使用以下 Python 或 CLI 命令:
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如需更多信息,请访问验证部分。