Phân loại hình ảnh

YOLO image classification of objects and scenes

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

Đầu ra của bộ phân loại hình ảnh là một nhãn lớp đơn lẻ 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 mà không cần biết vị trí của các đối tượng thuộc lớp đó hoặc hình dạng chính xác của chúng.



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

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

Models

Các model Classify huấn luyện trước của YOLO26 được hiển thị tại đâ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 phát hành mới nhất của Ultralytics 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.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 kiểm tra của tập dữ liệu ImageNet.
    Tái lập bằng yolo val classify data=path/to/ImageNet device=0
  • Tốc độ được tính trung bình trên các hình ảnh kiểm tra ImageNet sử dụng instance Amazon EC2 P4d.
    Tái lập bằng yolo val classify data=path/to/ImageNet batch=1 device=0|cpu
  • Các giá trị Tham sốFLOPs dành cho model đã hợp nhất sau khi chạy model.fuse(), giúp gộp các lớp Conv và BatchNorm. Các checkpoint đã huấn luyện trước vẫn giữ nguyên kiến trúc huấn luyện đầy đủ và có thể hiển thị số lượng cao hơn.

Huấn luyện

Huấn luyện YOLO26n-cls trên tập dữ liệu MNIST160 trong 100 epochs với kích thước hình ảnh là 64. Để biết danh sách đầy đủ các đối số khả dụng, 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 để kiểm tra và suy luận. Các phép biến đổi dựa trên cắt này giả định đầu vào hình vuông và có thể vô tình cắt mất các vùng quan trọng khỏi hình ảnh có tỷ lệ khung hình cực đoan, có khả năng gây mất thông tin hình ảnh 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ữ 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.

Bạn có thể thực hiện việc này bằng cách tùy chỉnh đường ống tăng cường (augmentation pipeline) của mình 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, 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)

Đị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 trên Ultralytics Platform.

Val

Kiểm tra độ 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 lưu giữ data huấn luyện và các đối số của nó như là các thuộc tính 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 cực đoan trong quá trình huấn luyện bằng cách sử dụng ClassificationTrainer tùy chỉnh. Bạn cần áp dụng phương pháp tương tự để có kết quả kiểm tra nhất quán bằng cách triển khai ClassificationValidator tùy chỉnh khi gọi phương thức val(). Tham khảo ví dụ mã đầy đủ trong phần huấn luyện để biết chi tiết triển khai.

Dự đoán

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 chế độ predict đầy đủ trong trang Predict.

Kết quả đầu ra

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 vector xác suất lớp và các công cụ hỗ trợ cho các dự đoán hàng đầu.

Thuộc tínhLoạiHình dạng (Shape)Mô tả
result.probsProbs(C,)Xác suất các lớp.
result.probs.datatorch.float32(C,)Xác suất theo từng lớp.
result.probs.top1int()ID lớp cao nhất.
result.probs.top1conftorch.float32()Độ tin cậy cao nhất.
result.probs.top5list[int](<=5)ID 5 lớp cao nhất.

Đối với các trường Results cụ thể theo từng tác vụ cho mọi tác vụ, xem phần Kết quả dự đoán theo tác vụ.

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 khả dụng nằm trong bảng dưới đây. 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, ví dụ: format='onnx' hoặc format='engine'. Bạn có thể dự đoán hoặc kiểm tra trực tiếp trên các model đã xuất, ví dụ: 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ố formatModelMetadataCác đối số
PyTorch-yolo26n-cls.pt-
TorchScripttorchscriptyolo26n-cls.torchscriptimgsz, half, dynamic, optimize, nms, batch, device
ONNXonnxyolo26n-cls.onnximgsz, half, dynamic, simplify, opset, nms, batch, 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, 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

Xem chi tiết export đầy đủ trong trang Export.

FAQ

Mục đích của YOLO26 trong phân loại hình ảnh là gì?

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 đơn lẻ 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.

Làm thế nào để tôi huấn luyện model YOLO26 cho phân loại 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 hình ả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.

Tôi có thể tìm các model phân loại YOLO26 được huấn luyện trước ở đâu?

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 Models. 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ể dễ dàng tải xuống và sử dụng cho các tác vụ phân loại hình ảnh khác nhau.

Làm cách nào để tôi xuất model YOLO26 đã huấn luyện sang các định dạng khác?

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 cá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.

Làm thế nào để tôi kiểm tra (validate) model phân loại YOLO26 đã huấn luyện?

Để kiểm tra độ chính xác của model đã huấn luyện trên 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 Kiểm tra.

Bình luận