Link to this section图像分类#
图像分类 是所支持的任务中最简单的一种,它涉及将整张图像分类为预定义类别集合中的某一个类别。
图像分类器的输出是一个单一的类别标签和一个置信度分数。当你只需要知道图像属于哪个类别,而不需要知道该类别的对象位于何处或其确切形状时,图像分类非常有用。
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-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进行复现。 - 速度 (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 而不是裁剪变换。
你可以通过自定义 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):
"""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 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.
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 nameSee full predict mode details in the Predict page.
Link to this section结果输出#
图像分类会为每张图像返回一个 Results 对象。主要的预测字段是 result.probs,其中包含类别概率向量以及用于获取顶级预测结果的辅助函数。
| 属性 | 类型 | 形状 (Shape) | 描述 |
|---|---|---|---|
result.probs | Probs | (C,) | 类别概率。 |
result.probs.data | torch.float32 | (C,) | 每个类别的概率。 |
result.probs.top1 | int | () | Top-1 类别 ID。 |
result.probs.top1conf | torch.float32 | () | Top-1 置信度。 |
result.probs.top5 | list[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 | ✅ | - |
| 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 |
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.pt、yolo26s-cls.pt、yolo26m-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) 部分。