YOLO Vision 2026:

Phân loại ảnh với Ultralytics YOLO#

Ultralytics YOLO image classification of objects and scenes

Phân loại hình ảnh là tác vụ đơn giản nhất trong các tác vụ được hỗ trợ và liên quan đến việc phân loại toàn bộ hình ảnh thành một trong số các lớp được xác định trước.

Đầu ra của một bộ phân loại hình ảnh là một nhãn lớp duy nhất và điểm tin cậy. Phân loại hình ảnh hữu ích khi bạn chỉ cần biết hình ảnh thuộc lớp nào và không cần biết các đối tượng thuộc lớp đó nằm ở đâu hoặc hình dạng chính xác của chúng là gì.



Watch: Explore Ultralytics YOLO Tasks: Image Classification using Ultralytics Platform
Mẹo

Các model YOLO26 Classify sử dụng hậu tố -cls, tức là yolo26n-cls.pt, và đã được huấn luyện trước trên ImageNet.

Models#

Các model YOLO26 Classify đã được huấn luyện trước được hiển thị ở đây. Các model Detect, Segment và Pose được huấn luyện trước trên tập dữ liệu COCO, các model Semantic được huấn luyện trước trên Cityscapes, và các model Classify được huấn luyện trước trên tập dữ liệu ImageNet.

Models được tải xuống tự động từ bản release mới nhất của Ultralytics trong lần sử dụng đầu tiên.

Mô hìnhkích thước
(pixel)
acc
top1
acc
top5
Tốc độ
CPU ONNX
(ms)
Tốc độ
T4 TensorRT10
(ms)
params
(M)
FLOPs
(B) tại 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
  • Các giá trị acc là độ chính xác của model trên tập dữ liệu xác thực ImageNet.
    Tái tạo bằng cách yolo val classify data=path/to/ImageNet device=0
  • Tốc độ tính trung bình trên các hình ảnh tập val của ImageNet sử dụng instance Amazon EC2 P4d.
    Tái tạo bằng cách yolo val classify data=path/to/ImageNet batch=1 device=0|cpu
  • Các giá trị ParamsFLOPs dành cho model đã được hợp nhất sau model.fuse(), thao tác hợp nhất các lớp Conv và BatchNorm. Các checkpoint huấn luyện trước giữ nguyên toàn bộ kiến trúc huấn luyện và có thể hiển thị số lượng lớn hơn.

Huấn luyện (Train)#

Huấn luyện YOLO26n-cls trên tập dữ liệu MNIST160 trong 100 epoch với kích thước ảnh 64. Để có danh sách đầy đủ các đối số có sẵn, hãy xem trang Cấu hình.

Ví dụ
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)
Mẹo

Phân loại Ultralytics YOLO sử dụng torchvision.transforms.RandomResizedCrop để huấn luyện và torchvision.transforms.CenterCrop để xác thực và suy luận. Các phép biến đổi dựa trên cắt xén này giả định đầu vào dạng hình vuông và có thể vô tình cắt bỏ các vùng quan trọng từ hình ảnh có tỷ lệ khung hình khắc nghiệt, có khả năng gây mất thông tin trực quan quan trọng trong quá trình huấn luyện. Để bảo toàn toàn bộ hình ảnh trong khi vẫn giữ nguyên tỷ lệ của nó, hãy cân nhắc sử dụng torchvision.transforms.Resize thay vì các phép biến đổi cắt xén.

Bạn có thể triển khai điều này bằng cách tùy chỉnh pipeline tăng cường dữ liệu của mình thông qua một ClassificationDatasetClassificationTrainer tùy chỉnh.

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)

Định dạng tập dữ liệu#

Định dạng tập dữ liệu phân loại YOLO có thể được tìm thấy chi tiết trong Hướng dẫn tập dữ liệu. Các tập dữ liệu phân loại cũng có thể được quản lý và gán nhãn bằng công cụ chú thích Ultralytics Platform.

Val#

Xác thực độ chính xác của model YOLO26n-cls đã huấn luyện trên tập dữ liệu MNIST160. Không cần đối số nào vì model giữ lại data huấn luyện và các đối số của nó dưới dạng các thuộc tính của model.

Ví dụ
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
Mẹo

Như đã đề cập trong phần huấn luyện, bạn có thể xử lý các tỷ lệ khung hình khắc nghiệt trong quá trình huấn luyện bằng cách sử dụng một ClassificationTrainer tùy chỉnh. Bạn cần áp dụng phương pháp tương tự để có kết quả xác thực nhất quán bằng cách triển khai một ClassificationValidator tùy chỉnh khi gọi phương thức val(). Tham khảo ví dụ mã nguồn hoàn chỉnh trong phần huấn luyện để biết chi tiết cách triển khai.

Dự đoán (Predict)#

Sử dụng model YOLO26n-cls đã huấn luyện để chạy dự đoán trên hình ảnh.

Ví dụ
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

Xem chi tiết đầy đủ về chế độ predict tại trang Predict.

Đầu ra kết quả#

Phân loại hình ảnh trả về một đối tượng Results cho mỗi hình ảnh. Trường dự đoán chính là result.probs, chứa vectơ xác suất lớp và các hàm hỗ trợ cho các dự đoán hàng đầu.

Thuộc tínhLoạiKích thướcMô tả
result.probsProbs(C,)Xác suất lớp.
result.probs.datatorch.float32(C,)Xác suất trên mỗi lớp.
result.probs.top1int()ID lớp hàng đầu.
result.probs.top1conftorch.float32()Độ tin cậy cao nhất.
result.probs.top5list[int](<=5)Top-5 ID lớp.

Đối với các trường Results dành riêng cho từng tác vụ trên mọi tác vụ, hãy xem phần Predict Results by Task.

Xuất (Export)#

Xuất model YOLO26n-cls sang định dạng khác như ONNX, CoreML, v.v.

Ví dụ
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")

Các định dạng xuất YOLO26-cls có sẵn nằm trong bảng bên dưới. Bạn có thể xuất sang bất kỳ định dạng nào bằng cách sử dụng đối số format, tức là format='onnx' hoặc format='engine'. Bạn có thể dự đoán hoặc xác thực trực tiếp trên các model đã xuất, tức là yolo predict model=yolo26n-cls.onnx. Các ví dụ sử dụng được hiển thị cho model của bạn sau khi quá trình xuất hoàn tất.

Định dạngĐối số formatMô hìnhMetadataTham số
PyTorch-yolo26n-cls.pt-
TorchScripttorchscriptyolo26n-cls.torchscriptimgsz, quantize, dynamic, nms, batch, device
ONNXonnxyolo26n-cls.onnximgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device
OpenVINOopenvinoyolo26n-cls_openvino_model/imgsz, quantize, dynamic, nms, batch, data, fraction, device
TensorRTengineyolo26n-cls.engineimgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device
CoreMLcoremlyolo26n-cls.mlpackageimgsz, dynamic, quantize, nms, batch, device
TF SavedModelsaved_modelyolo26n-cls_saved_model/imgsz, keras, quantize, opset, nms, batch, data, fraction, device
TF GraphDefpbyolo26n-cls.pbimgsz, opset, batch, device
TF Edge TPUedgetpuyolo26n-cls_edgetpu.tfliteimgsz, quantize, opset, data, fraction, device
PaddlePaddlepaddleyolo26n-cls_paddle_model/imgsz, batch, device
MNNmnnyolo26n-cls.mnnimgsz, batch, dynamic, quantize, simplify, opset, nms, device
NCNNncnnyolo26n-cls_ncnn_model/imgsz, quantize, batch, device
IMX500imxyolo26n-cls_imx_model/imgsz, quantize, data, fraction, nms, device
RKNNrknnyolo26n-cls_rknn_model/imgsz, batch, name, quantize, simplify, opset, data, fraction, device
ExecuTorchexecutorchyolo26n-cls_executorch_model/imgsz, batch, device
Axeleraaxelerayolo26n-cls_axelera_model/imgsz, batch, quantize, data, fraction, device
DEEPXdeepxyolo26n-cls_deepx_model/imgsz, quantize, simplify, opset, data, optimize, device
Qualcomm QNNqnnyolo26n-cls_qnn.onnximgsz, batch, name, quantize, simplify, opset, data, fraction, device
LiteRTlitertyolo26n-cls.tfliteimgsz, quantize, batch, data, fraction, device
Hailohailoyolo26n-cls_hailo_model/imgsz, name, quantize, data, fraction, simplify, conf, iou
Huawei Ascendascendyolo26n-cls_ascend_model/imgsz, batch, name, quantize, opset, simplify, nms

Xem chi tiết đầy đủ về export tại trang Export.

Câu hỏi thường gặp#

  • Các model YOLO26, chẳng hạn như yolo26n-cls.pt, được thiết kế để phân loại hình ảnh hiệu quả. Chúng gán một nhãn lớp duy nhất cho toàn bộ hình ảnh cùng với điểm độ tin cậy. Điều này đặc biệt hữu ích cho các ứng dụng mà việc biết lớp cụ thể của hình ảnh là đủ, thay vì xác định vị trí hoặc hình dạng của các đối tượng bên trong hình ảnh.

  • Để huấn luyện model YOLO26, bạn có thể sử dụng Python hoặc các lệnh CLI. Ví dụ, để huấn luyện model yolo26n-cls trên tập dữ liệu MNIST160 trong 100 epoch với kích thước ảnh là 64:

    Ví dụ
    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)

    Để biết thêm các tùy chọn cấu hình, hãy truy cập trang Cấu hình.

  • Các model phân loại YOLO26 đã được huấn luyện trước có thể được tìm thấy trong phần Model. Các model như yolo26n-cls.pt, yolo26s-cls.pt, yolo26m-cls.pt, v.v., đã được huấn luyện trước trên tập dữ liệu ImageNet và có thể được tải xuống dễ dàng và sử dụng cho các tác vụ phân loại hình ảnh khác nhau.

  • Bạn có thể xuất model YOLO26 đã huấn luyện sang nhiều định dạng khác nhau bằng cách sử dụng Python hoặc lệnh CLI. Ví dụ: để xuất model sang định dạng ONNX:

    Ví dụ
    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")

    Để biết các tùy chọn xuất chi tiết, hãy tham khảo trang Xuất.

  • Để kiểm chứng độ chính xác của model đã huấn luyện trên một tập dữ liệu như MNIST160, bạn có thể sử dụng các lệnh Python hoặc CLI sau:

    Ví dụ
    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

    Để biết thêm thông tin, hãy truy cập phần Xác thực.

Bình luận