Skip to main content

Phân loại hình ảnh

YOLO image classification of objects and scenes

Phân loại ảnh là tác vụ đơn giản nhất trong ba tác vụ và bao gồm 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 số 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 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-clsyolo26n-cls.pt, ví dụ: ImageNet.

Model

Các model Classify YOLO26 được huấn luyện trước đượ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 COCOCOCOImageNet, trong khi các model Classify được huấn luyện trước trên tập dữ liệu

ModelImageNet. Các model được tải xuống tự động từ phiên bản Ultralytics

Modelsize
(pixels)
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.076.492.97.9 ± 0.21.3 ± 0.06.7
1.6224YOLO26m-cls78.194.217.2 ± 0.42.0 ± 0.011.6
4.9224YOLO26l-cls79.094.623.2 ± 0.32.8 ± 0.014.1
6.2224YOLO26x-cls79.995.041.4 ± 0.93.8 ± 0.029.6
  • acc13.6ImageNetCác giá trị acc@1 và acc@5 là độ chính xác của model trên tập kiểm chứng ImageNet.
    Tái tạo bằng yolo val classify data=path/to/ImageNet device=0
  • Tốc độyolo val classify data=imagenet model=yolo26n-cls.pt device=0 được tính trung bình trên các hình ảnh ImageNet val bằng 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ị Params là dành cho model đã được hợp nhất sau FLOPsmodel fusingmodel.fuse(), giúp gộp các lớp Conv và BatchNorm. Các checkpoint đã huấn luyện trước giữ nguyên kiến trúc huấn luyện đầy đủ và có thể hiển thị số lượng tham số cao hơn.

Train

Huấn luyện YOLO26n-cls trên tập dữ liệu MNIST160 trong 100 epochepochsCấu hình của chúng tôi.

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

tại kích thước ảnh 64. Để xem danh sách đầy đủ các tham số khả dụng, hãy xem torchvision.transforms.RandomResizedCropcấu hìnhtorchvision.transforms.CenterCropUltralytics YOLO classification sử dụng torchvision.transforms.ResizeCenterCrop

để huấn luyện và ClassificationDatasetClassificationTrainer.

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)

Resize

cho kiểm chứng và suy luận. Các biến đổi dựa trên cắt ảnh này giả định đầu vào là hình vuông và có thể vô tình cắt mất các vùng quan trọng từ 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. Để giữ nguyên hình ảnh đầy đủ trong khi duy trì tỷ lệ của nó, hãy cân nhắc sử dụng LetterBox thay vì các biến đổi cắt ảnh. 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 Ultralytics Platform.

Val

Dataset tùy chỉnh.accuracyĐịnh dạng tập dữ liệu phân loại YOLO có thể được tìm thấy chi tiết trong model giữ lại các data và các đối số huấn luyệ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

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 RoboflowClassificationTrainer. Kiểm chứng model YOLO26n-cls đã huấn luyện ClassificationValidator khi gọi phương thức val()yolo val classify model=yolo26n-cls.pt data=mnist160. 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 trên tập dữ liệu MNIST160. Không cần tham số nào vì

Dự đoán

model giữ lại các thiết lập huấn luyện của nó

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

Xem chi tiết đầy đủ về predict. Như đã đề cập trong Dự đoán của chúng tôi.

Export

phần huấn luyện

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")

, 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 một format, ví dụ: format='onnx' hoặc format='engine'. Bạn có thể dự đoán hoặc kiểm chứng trực tiếp trên các model đã xuất, ví dụ: yolo predict model=yolo26n-cls.onnxLetterBox transform tùy chỉnh

Định dạngformat Đối sốModelMetadataĐố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

Xem chi tiết đầy đủ về export trong trang Export của chúng tôi.

Câu hỏi thường gặp (FAQ)

. Bạn cần áp dụng phương pháp tương tự để có kết quả kiểm chứng nhất quán bằng cách triển khai một phương thức

tùy chỉnhyolo26n-cls.pt. Tham khảo ví dụ mã đầy đủ trong

tài liệu

để biết chi tiết triển khai.yolo26n-clsSử 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 a pretrained model (recommended for training)

# Train the model
results = model.train(data="mnist160", epochs=100, imgsz=64)

chi tiết chế độ Cấu hình của chúng tôi.

trong

tài liệu dự đoánModel. Xuất model YOLO26n-cls sang định dạng khác như ONNX, CoreML, v.v.yolo26n-cls.pt, yolo26s-cls.pt, yolo26m-cls.ptCác định dạng xuất khả dụng của YOLO26-cls có 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 tham số ImageNetformat

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

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

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")

Các model YOLO26, chẳng hạn như Export của chúng tôi.

YOLO26n-cls

, đượ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 số 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 trong hình ảnh.

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

Làm thế nào để tôi huấn luyện một model YOLO26 cho phân loại hình ảnh?Để huấn luyện một model YOLO26, bạn có thể sử dụng Python hoặc lệnh CLI. Ví dụ, để huấn luyện một model của chúng tôi.

Bình luận