Phân loại ảnh với Ultralytics YOLO#
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
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.
| Model | kí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-cls | 224 | 71.4 | 90.1 | 5.0 ± 0.3 | 1.1 ± 0.0 | 2.8 | 0.4 |
| YOLO26s-cls | 224 | 76.0 | 92.9 | 7.9 ± 0.2 | 1.3 ± 0.0 | 6.7 | 1.5 |
| YOLO26m-cls | 224 | 78.1 | 94.2 | 17.2 ± 0.4 | 2.0 ± 0.0 | 11.6 | 4.8 |
| YOLO26l-cls | 224 | 79.0 | 94.6 | 23.2 ± 0.3 | 2.8 ± 0.0 | 14.1 | 6.0 |
| YOLO26x-cls | 224 | 79.9 | 95.0 | 41.4 ± 0.9 | 3.8 ± 0.0 | 29.6 | 13.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ằngyolo 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ằngyolo val classify data=path/to/ImageNet batch=1 device=0|cpu - Các giá trị Params và FLOPs á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.
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 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 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="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.
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 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.
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 đầ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ính | Kiểu | Shape | Mô tả |
|---|---|---|---|
result.probs | Probs | (C,) | Xác suất class. |
result.probs.data | torch.float32 | (C,) | Xác suất của từng class. |
result.probs.top1 | int | () | ID class đứng đầu. |
result.probs.top1conf | torch.float32 | () | Độ tin cậy đứng đầu. |
result.probs.top5 | list[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.
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ạng | Argument format | Model | Metadata | Arguments |
|---|---|---|---|---|
| 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 |
| Apple Core AI | coreai | yolo26n-cls.aimodel | ✅ | imgsz, 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-clstrê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.
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.