Meet YOLO26: next-gen vision AI.

Link to this section图像分类#

YOLO image classification of objects and scenes

图像分类 是所支持的任务中最简单的一种,它涉及将整张图像分类为预定义类别集合中的某一个类别。

图像分类器的输出是一个单一的类别标签和一个置信度分数。当你只需要知道图像属于哪个类别,而不需要知道该类别的对象位于何处或其确切形状时,图像分类非常有用。



Watch: Explore Ultralytics YOLO Tasks: Image Classification using Ultralytics Platform
提示

YOLO26 Classify 模型使用 -cls 后缀(例如 yolo26n-cls.pt),并且是在 ImageNet 上进行预训练的。

Link to this section模型#

此处展示了 YOLO26 预训练的 Classify 模型。Detect、Segment 和 Pose 模型是在 COCO 数据集上预训练的,Semantic 模型是在 Cityscapes 上预训练的,而 Classify 模型是在 ImageNet 数据集上预训练的。

模型 会在首次使用时自动从最新的 Ultralytics 发布版本 中下载。

模型尺寸
(像素)
准确率
top1
准确率
top5
速度
CPU ONNX
(ms)
速度
T4 TensorRT10
(ms)
参数量
(M)
FLOPs
(B) at 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 数值是模型在 ImageNet 数据集验证集上的准确率。
    可通过 yolo val classify data=path/to/ImageNet device=0 进行复现。
  • 速度 (Speed) 是使用 Amazon EC2 P4d 实例在 ImageNet 验证图像上平均得出的。
    可通过 yolo val classify data=path/to/ImageNet batch=1 device=0|cpu 进行复现。
  • 参数 (Params)FLOPs 数值是模型经过 model.fuse()(合并卷积层和批量归一化层)之后的融合模型数据。预训练检查点保留了完整的训练架构,因此可能会显示更高的数值。

Link to this section训练#

在 MNIST160 数据集上以 64 的图像尺寸训练 YOLO26n-cls 100 个 轮次 (epochs)。有关可用参数的完整列表,请参阅配置 (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)
提示

Ultralytics YOLO 分类在训练时使用 torchvision.transforms.RandomResizedCrop,在验证和推理时使用 torchvision.transforms.CenterCrop。这些基于裁剪的变换假设输入是正方形的,可能会无意中裁剪掉长宽比极端的图像中的重要区域,从而可能导致在训练过程中丢失关键的视觉信息。为了在保持比例的同时保留完整图像,请考虑使用 torchvision.transforms.Resize 而不是裁剪变换。

你可以通过自定义 ClassificationDatasetClassificationTrainer 来定制你的增强流水线,从而实现这一点。

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 section数据集格式#

YOLO 分类数据集格式的详细信息可以在 数据集指南 (Dataset Guide) 中找到。分类数据集也可以在 Ultralytics Platform 上进行管理和标注。

Link to this section验证#

在 MNIST160 数据集上验证已训练的 YOLO26n-cls 模型的准确率 (accuracy)。由于 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 accuracy
提示

As 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.

Link to this section预测#

使用已训练的 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 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

See full predict mode details in the Predict page.

Link to this section结果输出#

图像分类会为每张图像返回一个 Results 对象。主要的预测字段是 result.probs,其中包含类别概率向量以及用于获取顶级预测结果的辅助函数。

属性类型形状 (Shape)描述
result.probsProbs(C,)类别概率。
result.probs.datatorch.float32(C,)每个类别的概率。
result.probs.top1int()Top-1 类别 ID。
result.probs.top1conftorch.float32()Top-1 置信度。
result.probs.top5list[int](<=5)Top-5 类别 IDs。

关于各项任务中特定于任务的 Results 字段,请参阅按任务划分的预测结果 (Predict Results by Task) 部分。

Link to this section导出#

将 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-
TorchScripttorchscriptyolo26n-cls.torchscriptimgsz, half, dynamic, optimize, nms, batch, device
ONNXonnxyolo26n-cls.onnximgsz, half, int8, dynamic, simplify, opset, nms, batch, data, fraction, device
OpenVINOopenvinoyolo26n-cls_openvino_model/imgsz, half, dynamic, int8, nms, batch, data, fraction, device
TensorRTengineyolo26n-cls.engineimgsz, half, dynamic, simplify, workspace, int8, nms, batch, data, fraction, device
CoreMLcoremlyolo26n-cls.mlpackageimgsz, dynamic, half, int8, nms, batch, device
TF SavedModelsaved_modelyolo26n-cls_saved_model/imgsz, keras, int8, nms, batch, data, fraction, device
TF GraphDefpbyolo26n-cls.pbimgsz, batch, device
TF Litetfliteyolo26n-cls.tfliteimgsz, half, int8, nms, batch, data, fraction, device
TF Edge TPUedgetpuyolo26n-cls_edgetpu.tfliteimgsz, int8, data, fraction, device
TF.jstfjsyolo26n-cls_web_model/imgsz, half, int8, nms, batch, data, fraction, device
PaddlePaddlepaddleyolo26n-cls_paddle_model/imgsz, batch, device
MNNmnnyolo26n-cls.mnnimgsz, batch, int8, half, device
NCNNncnnyolo26n-cls_ncnn_model/imgsz, half, batch, device
IMX500imxyolo26n-cls_imx_model/imgsz, int8, data, fraction, nms, device
RKNNrknnyolo26n-cls_rknn_model/imgsz, batch, name, int8, data, fraction, device
ExecuTorchexecutorchyolo26n-cls_executorch_model/imgsz, batch, device
Axeleraaxelerayolo26n-cls_axelera_model/imgsz, batch, int8, data, fraction, device
DEEPXdeepxyolo26n-cls_deepx_model/imgsz, int8, data, optimize, device
Qualcomm QNNqnnyolo26n-cls_qnn_model/imgsz, batch, name, int8, data, fraction, device

See full export details in the Export page.

Link to this section常见问题解答#

Link to this sectionYOLO26 在图像分类中的目的是什么?#

YOLO26 模型(例如 yolo26n-cls.pt)专为高效的图像分类而设计。它们将单一的类别标签连同置信度分数分配给整张图像。这对于那些只需要知道图像的具体类别,而不需要识别图像内对象的位置或形状的应用场景特别有用。

Link to this section我该如何训练 YOLO26 模型进行图像分类?#

要训练 YOLO26 模型,你可以使用 Python 或 CLI 命令。例如,要在 MNIST160 数据集上以 64 的图像尺寸训练 yolo26n-cls 模型 100 个轮次:

示例
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)

有关更多配置选项,请访问配置 (Configuration) 页面。

Link to this section我在哪里可以找到预训练的 YOLO26 分类模型?#

预训练的 YOLO26 分类模型可以在模型 (Models) 部分找到。像 yolo26n-cls.ptyolo26s-cls.ptyolo26m-cls.pt 等模型都在 ImageNet 数据集上进行了预训练,可以轻松下载并用于各种图像分类任务。

Link to this section我该如何将已训练的 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")

有关详细的导出选项,请参阅导出 (Export) 页面。

Link to this section我该如何验证已训练的 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

有关更多信息,请访问验证 (Validate) 部分。

评论