Phân loại ảnh với Ultralytics YOLO#
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
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ình | kí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-cls | 224 | 71.4 | 90.1 | 5.0 ± 0.3 | 1.1 ± 0.0 | 2.8 | 0.5 |
| YOLO26s-cls | 224 | 76.0 | 92.9 | 7.9 ± 0.2 | 1.3 ± 0.0 | 6.7 | 1.6 |
| YOLO26m-cls | 224 | 78.1 | 94.2 | 17.2 ± 0.4 | 2.0 ± 0.0 | 11.6 | 4.9 |
| YOLO26l-cls | 224 | 79.0 | 94.6 | 23.2 ± 0.3 | 2.8 ± 0.0 | 14.1 | 6.2 |
| YOLO26x-cls | 224 | 79.9 | 95.0 | 41.4 ± 0.9 | 3.8 ± 0.0 | 29.6 | 13.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áchyolo 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áchyolo val classify data=path/to/ImageNet batch=1 device=0|cpu - Các giá trị Params và FLOPs 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.
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)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 ClassificationDataset và ClassificationTrainer 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.
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 accuracyNhư đã đề 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.
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 nameXem 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ính | Loại | Kích thước | Mô tả |
|---|---|---|---|
result.probs | Probs | (C,) | Xác suất lớp. |
result.probs.data | torch.float32 | (C,) | Xác suất trên mỗi lớp. |
result.probs.top1 | int | () | ID lớp hàng đầu. |
result.probs.top1conf | torch.float32 | () | Độ tin cậy cao nhất. |
result.probs.top5 | list[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.
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ố format | Mô hình | Metadata | Tham số |
|---|---|---|---|---|
| PyTorch | - | yolo26n-cls.pt | ✅ | - |
| TorchScript | torchscript | yolo26n-cls.torchscript | ✅ | imgsz, quantize, dynamic, nms, batch, device |
| ONNX | onnx | yolo26n-cls.onnx | ✅ | imgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device |
| OpenVINO | openvino | yolo26n-cls_openvino_model/ | ✅ | imgsz, quantize, dynamic, nms, batch, data, fraction, device |
| TensorRT | engine | yolo26n-cls.engine | ✅ | imgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device |
| CoreML | coreml | yolo26n-cls.mlpackage | ✅ | imgsz, dynamic, quantize, nms, batch, device |
| TF SavedModel | saved_model | yolo26n-cls_saved_model/ | ✅ | imgsz, keras, quantize, opset, nms, batch, data, fraction, device |
| TF GraphDef | pb | yolo26n-cls.pb | ❌ | imgsz, opset, batch, device |
| TF Edge TPU | edgetpu | yolo26n-cls_edgetpu.tflite | ✅ | imgsz, quantize, opset, data, fraction, device |
| PaddlePaddle | paddle | yolo26n-cls_paddle_model/ | ✅ | imgsz, batch, device |
| MNN | mnn | yolo26n-cls.mnn | ✅ | imgsz, batch, dynamic, quantize, simplify, opset, nms, device |
| NCNN | ncnn | yolo26n-cls_ncnn_model/ | ✅ | imgsz, quantize, batch, device |
| IMX500 | imx | yolo26n-cls_imx_model/ | ✅ | imgsz, quantize, data, fraction, nms, device |
| RKNN | rknn | yolo26n-cls_rknn_model/ | ✅ | imgsz, batch, name, quantize, simplify, opset, data, fraction, device |
| ExecuTorch | executorch | yolo26n-cls_executorch_model/ | ✅ | imgsz, batch, device |
| Axelera | axelera | yolo26n-cls_axelera_model/ | ✅ | imgsz, batch, quantize, data, fraction, device |
| DEEPX | deepx | yolo26n-cls_deepx_model/ | ✅ | imgsz, quantize, simplify, opset, data, optimize, device |
| Qualcomm QNN | qnn | yolo26n-cls_qnn.onnx | ✅ | imgsz, batch, name, quantize, simplify, opset, data, fraction, device |
| LiteRT | litert | yolo26n-cls.tflite | ✅ | imgsz, quantize, batch, data, fraction, device |
| Hailo | hailo | yolo26n-cls_hailo_model/ | ✅ | imgsz, name, quantize, data, fraction, simplify, conf, iou |
| Huawei Ascend | ascend | yolo26n-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-clstrê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.
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.