Chuyển đến nội dung

Phân loại hình ảnh

Ví dụ về phân loại ảnh

Phân loại hình ảnh là tác vụ đơn giản nhất trong ba tác vụ và liên quan đến việc phân loại toàn bộ hình ảnh vào một trong một tập hợp 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à một điểm tin cậy. Phân loại hình ảnh rất 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 của lớp đó nằm ở đâu hoặc hình dạng chính xác của chúng là gì.



Xem: Khám phá các Tác vụ Ultralytics YOLO: Phân loại Hình ảnh bằng Ultralytics HUB

Mẹo

Các mô hình Phân loại YOLO11 sử dụng -cls hậu tố, ví dụ: yolo11n-cls.pt và được huấn luyện trước trên ImageNet.

Mô hình

Các mô hình Phân loại YOLO11 được huấn luyện trước được hiển thị ở đây. Các mô hình Phát hiện, Phân đoạn và Tư thế được huấn luyện trước trên bộ dữ liệu COCO, trong khi các mô hình Phân loại được huấn luyện trước trên bộ dữ liệu ImageNet.

Các mô hình sẽ tự động tải xuống từ phiên bản phát hành Ultralytics mới nhất khi sử dụng lần đầu.

Mô hình Kích thước
(pixels)
acc
top1
acc
top5
Tốc độ
CPU ONNX
(ms)
Tốc độ
T4 TensorRT10
(ms)
Tham số
(M)
FLOPs
(B) ở 224
YOLO11n-cls 224 70.0 89.4 5.0 ± 0.3 1.1 ± 0.0 1.6 0.5
YOLO11s-cls 224 75.4 92.7 7.9 ± 0.2 1.3 ± 0.0 5.5 1.6
YOLO11m-cls 224 77.3 93.9 17.2 ± 0.4 2.0 ± 0.0 10.4 5.0
YOLO11l-cls 224 78.3 94.3 23.2 ± 0.3 2.8 ± 0.0 12.9 6.2
YOLO11x-cls 224 79.5 94.9 41.4 ± 0.9 3.8 ± 0.0 28.4 13.7
  • acc là các giá trị độ chính xác của mô hình trên ImageNet tập dữ liệu xác thực.
    Tái tạo bằng cách yolo val classify data=path/to/ImageNet device=0
  • Tốc độ được tính trung bình trên các ảnh val ImageNet bằng cách sử dụng Amazon EC2 P4d instance.
    Tái tạo bằng cách yolo val classify data=path/to/ImageNet batch=1 device=0|cpu

Huấn luyện

Huấn luyện YOLO11n-cls trên bộ dữ liệu MNIST160 trong 100 epochs ở 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("yolo11n-cls.yaml")  # build a new model from YAML
model = YOLO("yolo11n-cls.pt")  # load a pretrained model (recommended for training)
model = YOLO("yolo11n-cls.yaml").load("yolo11n-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=yolo11n-cls.yaml epochs=100 imgsz=64

# Start training from a pretrained *.pt model
yolo classify train data=mnist160 model=yolo11n-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=yolo11n-cls.yaml pretrained=yolo11n-cls.pt epochs=100 imgsz=64

Mẹo

Phân loại Ultralytics YOLO sử dụng torchvision.transforms.RandomResizedCrop cho việc huấn luyện và torchvision.transforms.CenterCrop cho việc 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 hình vuông và có thể vô tình cắt bỏ các vùng quan trọng khỏi hình ảnh có tỷ lệ khung hình cực cao, 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. Để giữ lại toàn bộ hình ảnh trong khi vẫn duy trì tỷ lệ của nó, hãy cân nhắc sử dụng torchvision.transforms.Resize thay vì cắt các phép biến đổi.

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 thông qua một 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("yolo11n-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 bộ dữ liệu

Bạn có thể tìm thấy định dạng bộ dữ liệu phân loại YOLO chi tiết trong Hướng dẫn về Bộ dữ liệu.

Val

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

Ví dụ

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-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=yolo11n-cls.pt  # val official model
yolo classify val model=path/to/best.pt # val custom model

Mẹo

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

Dự đoán

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

Ví dụ

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-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=yolo11n-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

Xem đầy đủ predict chi tiết chế độ trong Dự đoán trang.

Xuất

Xuất mô hình YOLO11n-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("yolo11n-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=yolo11n-cls.pt format=onnx  # export official model
yolo export model=path/to/best.pt format=onnx # export custom trained model

Các định dạng xuất YOLO11-cls có sẵn được liệt kê 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 format đối số, ví dụ: 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 mô hình đã xuất, ví dụ: yolo predict model=yolo11n-cls.onnx. Các ví dụ sử dụng được hiển thị cho mô hình của bạn sau khi quá trình xuất hoàn tất.

Định dạng format Đối số Mô hình Metadata (Siêu dữ liệu) Các đối số
PyTorch - yolo11n-cls.pt -
TorchScript torchscript yolo11n-cls.torchscript imgsz, half, dynamic, optimize, nms, batch, device
ONNX onnx yolo11n-cls.onnx imgsz, half, dynamic, simplify, opset, nms, batch, device
OpenVINO openvino yolo11n-cls_openvino_model/ imgsz, half, dynamic, int8, nms, batch, data, fraction, device
TensorRT engine yolo11n-cls.engine imgsz, half, dynamic, simplify, workspace, int8, nms, batch, data, fraction, device
CoreML coreml yolo11n-cls.mlpackage imgsz, half, int8, nms, batch, device
TF SavedModel saved_model yolo11n-cls_saved_model/ imgsz, keras, int8, nms, batch, device
TF GraphDef pb yolo11n-cls.pb imgsz, batch, device
TF Lite tflite yolo11n-cls.tflite imgsz, half, int8, nms, batch, data, fraction, device
TF Edge TPU edgetpu yolo11n-cls_edgetpu.tflite imgsz, device
TF.js tfjs yolo11n-cls_web_model/ imgsz, half, int8, nms, batch, device
PaddlePaddle paddle yolo11n-cls_paddle_model/ imgsz, batch, device
MNN mnn yolo11n-cls.mnn imgsz, batch, int8, half, device
NCNN ncnn yolo11n-cls_ncnn_model/ imgsz, half, batch, device
IMX500 imx yolo11n-cls_imx_model/ imgsz, int8, data, fraction, device
RKNN rknn yolo11n-cls_rknn_model/ imgsz, batch, name, device

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

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

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

Các mô hình YOLO11, chẳng hạn như yolo11n-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 đ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 một ảnh là đủ, thay vì xác định vị trí hoặc hình dạng của các đối tượng trong ảnh.

Làm cách nào để huấn luyện mô hình YOLO11 cho phân loại hình ảnh?

Để huấn luyện mô hình YOLO11, bạn có thể sử dụng lệnh Python hoặc CLI. Ví dụ: để huấn luyện một yolo11n-cls mô hình trên bộ dữ liệu MNIST160 trong 100 epochs ở kích thước ảnh là 64:

Ví dụ

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-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=yolo11n-cls.pt 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 mô hình phân loại YOLO11 được huấn luyện trước ở đâu?

Bạn có thể tìm thấy các mô hình phân loại YOLO11 được huấn luyện trước trong Mô hình mục. Các mô hình như yolo11n-cls.pt, yolo11s-cls.pt, yolo11m-cls.pt, v.v., được huấn luyện trước trên ImageNet bộ dữ liệu 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 để xuất mô hình YOLO11 đã huấn luyện sang các định dạng khác nhau?

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

Ví dụ

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load the trained model

# Export the model to ONNX
model.export(format="onnx")
yolo export model=yolo11n-cls.pt format=onnx # export the trained model to ONNX format

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

Làm cách nào để xác thực mô hình phân loại YOLO11 đã huấn luyện?

Để xác thực độ chính xác của mô hình đã 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("yolo11n-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=yolo11n-cls.pt # validate the trained model

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



📅 Đã tạo 1 năm trước ✏️ Cập nhật 6 ngày trước

Bình luận