图像分类

图像分类是三个任务中最简单的,它涉及将整个图像分类到一组预定义的类别中。
图像分类器的输出是单个类别标签和一个置信度分数。当您只需要知道图像属于哪个类别,而不需要知道该类别的对象位于何处或其确切形状时,图像分类非常有用。
观看: 探索 Ultralytics YOLO 任务:使用 Ultralytics 平台进行图像分类
提示
YOLO26 classify 模型使用 -cls 后缀,即 yolo26n-cls.pt,并在...上进行预训练 ImageNet.
模型
此处显示了 YOLO26 预训练的 classify 模型。detect、segment 和 姿势估计 模型在 COCO 数据集上进行了预训练,而 classify 模型则在 ImageNet 数据集上进行了预训练。
模型首次使用时会自动从最新的 Ultralytics release 下载。
| 模型 | 尺寸 (像素) | acc top1 | acc top5 | 速度 CPU ONNX (毫秒) | 速度 T4 TensorRT10 (毫秒) | 参数 (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 - 速度 在 ImageNet 验证图像上平均,使用一个 Amazon EC2 P4d 实例进行平均计算得出的。
如需重现结果,请通过yolo val classify data=path/to/ImageNet batch=1 device=0|cpu
训练
在图像大小为 64 的情况下,在 MNIST160 数据集上训练 YOLO26n-cls 100 个 epoch。有关可用参数的完整列表,请参阅配置页面。
示例
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)
# Build a new model from YAML and start training from scratch
yolo classify train data=mnist160 model=yolo26n-cls.yaml epochs=100 imgsz=64
# Start training from a pretrained *.pt model
yolo classify train data=mnist160 model=yolo26n-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=yolo26n-cls.yaml pretrained=yolo26n-cls.pt 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 分类数据集格式的详细信息可以在数据集指南中找到。
验证
验证训练好的 YOLO26n-cls 模型 准确性 在 MNIST160 数据集上。由于 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
yolo classify val model=yolo26n-cls.pt # val official model
yolo classify val model=path/to/best.pt # val custom model
提示
正如在以下内容中提到的 训练部分,您可以通过使用自定义的 ClassificationTrainer。您需要应用相同的方法,通过实施自定义的 ClassificationValidator 在调用 val() 方法。请参阅中的完整代码示例 训练部分 有关实施细节。
预测
使用训练好的 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
yolo classify predict model=yolo26n-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
查看完整 predict 模式的详细信息,请参阅 预测 页面。
导出
将 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")
yolo export model=yolo26n-cls.pt format=onnx # export official model
yolo export model=path/to/best.pt format=onnx # export custom-trained model
可用的 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, 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, device |
| TF.js | tfjs | yolo26n-cls_web_model/ | ✅ | imgsz, half, int8, nms, batch, 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, device |
| RKNN | rknn | yolo26n-cls_rknn_model/ | ✅ | imgsz, batch, name, device |
| ExecuTorch | executorch | yolo26n-cls_executorch_model/ | ✅ | imgsz, device |
| Axelera | axelera | yolo26n-cls_axelera_model/ | ✅ | imgsz, int8, data, fraction, device |
查看完整 export 详情请参见 导出 页面。
常见问题
YOLO26 在图像分类中的作用是什么?
YOLO26 模型,例如 yolo26n-cls.pt,专为高效图像分类而设计。它们为整个图像分配单个类别标签以及置信度分数。这对于知道图像的特定类别就足够的应用特别有用,而不是识别图像中物体的具体位置或形状。
如何训练 YOLO26 模型进行图像分类?
要训练 YOLO26 模型,您可以使用 Python 或 CLI 命令。例如,要训练一个 yolo26n-cls 模型在 MNIST160 数据集上进行 100 个 epochs,图像大小为 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)
yolo classify train data=mnist160 model=yolo26n-cls.pt 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")
yolo export model=yolo26n-cls.pt format=onnx # export the trained model to ONNX format
有关详细的导出选项,请参阅导出页面。
如何验证训练好的 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
yolo classify val model=yolo26n-cls.pt # validate the trained model
有关更多信息,请访问验证部分。