Ultralytics YOLO27:

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

Ultralytics YOLO image classification of objects and scenes

Phân loại ảnh là tác vụ đơn giản nhất trong các tác vụ được hỗ trợ và bao gồm việc phân loại toàn bộ ảnh vào một trong các lớp được xác định trước.

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



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

Các model Classify của YOLO26 sử dụng hậu tố -cls, tức là yolo26n-cls.pt, và được pretrained trên ImageNet.

Models#

Các model Classify pretrained của YOLO26 được hiển thị tại đây. Các model Detect, Segment và Pose được pretrained trên dataset COCO, các model Semantic được pretrained trên Cityscapes, còn các model Classify được pretrained trên dataset ImageNet.

Các model được tự động tải xuống từ bản phát hành Ultralytics mới nhất trong lần sử dụng đầu tiên.

Modelkích thước
(pixel)
acc
top1
acc
top5
Tốc độ
CPU ONNX
(ms)
Tốc độ
T4 TensorRT10
(ms)
tham số
(M)
FLOPs
(B) tại 224
YOLO26n-cls22471.490.15.0 ± 0.31.1 ± 0.02.80.4
YOLO26s-cls22476.092.97.9 ± 0.21.3 ± 0.06.71.5
YOLO26m-cls22478.194.217.2 ± 0.42.0 ± 0.011.64.8
YOLO26l-cls22479.094.623.2 ± 0.32.8 ± 0.014.16.0
YOLO26x-cls22479.995.041.4 ± 0.93.8 ± 0.029.613.5
  • Các giá trị acc là độ chính xác của model trên tập validation của dataset ImageNet.
    Tái tạo bằng yolo val classify data=path/to/ImageNet device=0
  • Speed là giá trị trung bình trên các ảnh validation của ImageNet bằng một instance Amazon EC2 P4d.
    Tái tạo bằng yolo val classify data=path/to/ImageNet batch=1 device=0|cpu
  • Các giá trị ParamsFLOPs áp dụng cho model đã fuse sau model.fuse(), trong đó các layer Conv và BatchNorm được hợp nhất. Các checkpoint pretrained giữ nguyên kiến trúc training đầy đủ và có thể hiển thị số lượng cao hơn.

Xem bản xem trước YOLO27 chưa phát hành để biết tốc độ phân loại sơ bộ và kích thước model.

Huấn luyện#

Train YOLO26n-cls trên dataset MNIST160 trong 100 epoch với kích thước ảnh là 64. Để xem danh sách đầy đủ các tham số khả dụng, hãy xem trang Configuration.

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 bằng Ultralytics YOLO sử dụng torchvision.transforms.RandomResizedCrop cho training và torchvision.transforms.CenterCrop cho validation và inference. Các phép biến đổi dựa trên crop này giả định đầu vào hình vuông và có thể vô tình crop mất các vùng quan trọng trong những ảnh có tỷ lệ khung hình cực đoan, có khả năng làm mất thông tin hình ảnh then chốt trong quá trình training. Để giữ nguyên toàn bộ ảnh mà vẫn duy trì tỷ lệ của ảnh, hãy cân nhắc sử dụng torchvision.transforms.Resize thay cho các phép biến đổi crop.

Bạn có thể triển khai việc này bằng cách tùy chỉnh pipeline augmentation thông qua 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="imagenet", trainer=CustomizedTrainer, epochs=10, imgsz=224, batch=64)
model.val(data="imagenet", validator=CustomizedValidator, imgsz=224, batch=64)

Định dạng dataset#

Định dạng dataset cho YOLO classification được trình bày chi tiết trong Dataset Guide. Các dataset classification cũng có thể được quản lý và gán nhãn bằng các công cụ annotation của Ultralytics Platform.

Val#

Đánh giá độ chính xác của model YOLO26n-cls đã train trên dataset MNIST160. Không cần tham số nào vì model giữ lại data dùng trong training và các tham số dưới dạng 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 training, bạn có thể xử lý các tỷ lệ khung hình cực đoan trong quá trình training bằng cách sử dụng ClassificationTrainer tùy chỉnh. Để có kết quả validation nhất quán, bạn cần áp dụng cùng phương pháp bằng cách triển khai ClassificationValidator tùy chỉnh khi gọi method val(). Hãy tham khảo ví dụ code đầy đủ trong phần training để biết chi tiết triển khai.

Predict#

Sử dụng model YOLO26n-cls đã train để chạy dự đoán trên các ả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 đầy đủ chi tiết về mode predict trên trang Predict.

Output kết quả#

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

Thuộc tínhKiểuShapeMô tả
result.probsProbs(C,)Xác suất class.
result.probs.datatorch.float32(C,)Xác suất của từng class.
result.probs.top1int()ID class đứng đầu.
result.probs.top1conftorch.float32()Độ tin cậy đứng đầu.
result.probs.top5list[int](<=5)ID của 5 class đứng đầu.

Để xem các field Results dành riêng cho từng task trên mọi task, hãy xem phần Predict Results by Task.

Export#

Export model YOLO26n-cls sang một đị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 export khả dụng của YOLO26-cls được liệt kê trong bảng dưới đây. Bạn có thể export sang bất kỳ định dạng nào bằng tham số format, tức là format='onnx' hoặc format='engine'. Bạn có thể dự đoán hoặc validation trực tiếp trên các model đã export, tức là yolo predict model=yolo26n-cls.onnx. Các ví dụ sử dụng cho model của bạn sẽ được hiển thị sau khi quá trình export hoàn tất.

Định dạngArgument formatModelMetadataArguments
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
Apple Core AIcoreaiyolo26n-cls.aimodelimgsz, batch, quantize

nms=None mặc định sử dụng đầu ra thô cho NMS bên ngoài. Thiết lập nms=False để chọn phần đầu không có NMS khả dụng; các định dạng không được hỗ trợ sẽ quay lại đường dẫn đầu ra gốc của chúng. Các mục nms ở trên xác định các định dạng có thể nhúng NMS bằng nms=True.

Xem đầy đủ chi tiết về export trên trang Export.

FAQ#

  • Các model YOLO26, chẳng hạn như yolo26n-cls.pt, được thiết kế để phân loại ảnh hiệu quả. Chúng gán một nhãn lớp duy nhất cho toàn bộ ảnh cùng với một đ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 ảnh là đủ, thay vì phải xác định vị trí hoặc hình dạng của các đối tượng trong ảnh.

  • Để train model YOLO26, bạn có thể sử dụng các lệnh Python hoặc CLI. Ví dụ, để train model yolo26n-cls trên dataset 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)

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

  • Các model classification YOLO26 pretrained có thể được tìm thấy trong phần Models. Các model như yolo26n-cls.pt, yolo26s-cls.pt, yolo26m-cls.pt, v.v. được pretrained trên dataset ImageNet và có thể dễ dàng được tải xuống để sử dụng cho nhiều tác vụ phân loại ảnh khác nhau.

  • Bạn có thể export model YOLO26 đã train sang nhiều định dạng bằng các lệnh Python hoặc CLI. Ví dụ, để export mộ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 thông tin chi tiết về các tùy chọn export, hãy tham khảo trang Export.

  • Để validation độ chính xác của một model đã train trên dataset 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 Validate.

Bình luận