Link to this sectionPhân loại hình ảnh#
Phân loại hình ảnh là tác vụ đơn giản nhất trong số 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 vào một trong tập hợp các lớp đã 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, ví dụ: yolo26n-cls.pt và được huấn luyện trước trên ImageNet.
Link to this sectionModel#
Các model Classify đã được 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.
Model được tự động tải xuống từ bản phát hành mới nhất của Ultralytics khi sử dụng lần đầu.
| 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 kiểm chứng của tập dữ liệu ImageNet.
Tái lập bằngyolo 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 chứng của ImageNet bằng cách sử dụng instance Amazon EC2 P4d.
Tái lập bằngyolo 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(), giúp gộp các lớp Conv và BatchNorm. Các checkpoint đã được 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.
Link to this sectionHuấ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 hình ảnh là 64. Để xem danh sách đầy đủ các đối số khả dụng, hãy truy cập 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 YOLO của Ultralytics sử dụng torchvision.transforms.RandomResizedCrop để huấn luyện và torchvision.transforms.CenterCrop để kiểm chứng 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 là 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 mát thông tin hình ảnh quan trọng trong quá trình huấn luyện.
Để giữ nguyên 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á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 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="imagenet1000", trainer=CustomizedTrainer, epochs=10, imgsz=224, batch=64)
model.val(data="imagenet1000", validator=CustomizedValidator, imgsz=224, batch=64)Link to this sectionĐị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 về 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à dán nhãn trên Nền tảng Ultralytics.
Link to this sectionVal#
Kiểm chứng độ 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 vẫn giữ lại data huấn luyện và các đối số của nó dưới dạng thuộc tính 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 cực đoan trong khi 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 chứng 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.
Link to this sectionDự đ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 trong trang Dự đoán.
Link to this sectionĐầ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 vector xác suất lớp và các trình 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. |
Để biết các trường Results cụ thể cho từng tác vụ, hãy xem phần Dự đoán kết quả theo tác vụ.
Link to this sectionXuấ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 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 đối số 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.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 | Tham số format | Mô hình | Metadata | Tham số |
|---|---|---|---|---|
| PyTorch | - | yolo26n-cls.pt | ✅ | - |
| TorchScript | torchscript | yolo26n-cls.torchscript | ✅ | imgsz, half, dynamic, optimize, nms, batch, device |
| ONNX | onnx | yolo26n-cls.onnx | ✅ | imgsz, half, int8, dynamic, simplify, opset, nms, batch, data, fraction, device |
| OpenVINO | openvino | yolo26n-cls_openvino_model/ | ✅ | imgsz, half, dynamic, int8, nms, batch, data, fraction, device |
| TensorRT | engine | yolo26n-cls.engine | ✅ | imgsz, half, dynamic, simplify, workspace, int8, nms, batch, data, fraction, device |
| CoreML | coreml | yolo26n-cls.mlpackage | ✅ | imgsz, dynamic, half, int8, nms, batch, device |
| TF SavedModel | saved_model | yolo26n-cls_saved_model/ | ✅ | imgsz, keras, int8, nms, batch, data, fraction, device |
| TF GraphDef | pb | yolo26n-cls.pb | ❌ | imgsz, batch, device |
| TF Lite | tflite | yolo26n-cls.tflite | ✅ | imgsz, half, int8, nms, batch, data, fraction, device |
| TF Edge TPU | edgetpu | yolo26n-cls_edgetpu.tflite | ✅ | imgsz, int8, data, fraction, device |
| TF.js | tfjs | yolo26n-cls_web_model/ | ✅ | imgsz, half, int8, nms, batch, data, fraction, device |
| PaddlePaddle | paddle | yolo26n-cls_paddle_model/ | ✅ | imgsz, batch, device |
| MNN | mnn | yolo26n-cls.mnn | ✅ | imgsz, batch, int8, half, device |
| NCNN | ncnn | yolo26n-cls_ncnn_model/ | ✅ | imgsz, half, batch, device |
| IMX500 | imx | yolo26n-cls_imx_model/ | ✅ | imgsz, int8, data, fraction, nms, device |
| RKNN | rknn | yolo26n-cls_rknn_model/ | ✅ | imgsz, batch, name, int8, data, fraction, device |
| ExecuTorch | executorch | yolo26n-cls_executorch_model/ | ✅ | imgsz, batch, device |
| Axelera | axelera | yolo26n-cls_axelera_model/ | ✅ | imgsz, batch, int8, data, fraction, device |
| DEEPX | deepx | yolo26n-cls_deepx_model/ | ✅ | imgsz, int8, data, optimize, device |
| Qualcomm QNN | qnn | yolo26n-cls_qnn.onnx | ✅ | imgsz, batch, name, int8, data, fraction, device |
Xem chi tiết export đầy đủ trong trang Export.
Link to this sectionCâu hỏi thường gặp#
Link to this sectionMụ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 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.
Link to this sectionLàm cách nào để 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 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:
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.
Link to this sectionTôi có thể tìm các model phân loại YOLO26 đã huấn luyện trước ở đâu?#
Các model phân loại YOLO26 đã huấn luyện trước có thể được tìm thấy trong phần Model. 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 nhiều tác vụ phân loại hình ảnh khác nhau.
Link to this sectionLàm cách nào tôi có thể 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 lệnh CLI. Ví dụ: để xuất model sang định dạng ONNX:
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.
Link to this sectionLàm cách nào để kiểm chứng model phân loại YOLO26 đã huấn luyện?#
Để 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:
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 chứng.