이미지 분류
이미지 분류는 세 가지 작업 중 가장 간단하며, 전체 이미지를 사전 정의된 클래스 집합 중 하나로 분류하는 작업입니다.
이미지 분류기의 출력은 단일 클래스 레이블과 신뢰도 점수입니다. 이미지 분류는 이미지에 어떤 클래스가 속해 있는지만 알면 되며, 해당 클래스의 객체가 어디에 위치하는지나 정확한 모양이 무엇인지 알 필요가 없을 때 유용합니다.
Watch: Explore Ultralytics YOLO Tasks: Image Classification using Ultralytics Platform
YOLO26 Classify 모델은 -cls 접미사를 사용하며(예: yolo26n-cls.pt), ImageNet 데이터셋으로 사전 학습되었습니다.
모델
YOLO26 사전 학습된 Classify 모델은 여기에 표시되어 있습니다. Detect, Segment 및 Pose 모델은 COCO 데이터셋으로 사전 학습되며, Classify 모델은 ImageNet 데이터셋으로 사전 학습됩니다.
모델은 처음 사용할 때 최신 Ultralytics 릴리스에서 자동으로 다운로드됩니다.
| 모델 | 크기 (픽셀) | 정확도 top1 | 정확도 top5 | 속도 CPU ONNX (ms) | 속도 T4 TensorRT10 (ms) | 파라미터 (M) | FLOPs (B) at 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 |
- acc 값은 ImageNet 데이터셋 검증 세트에서의 모델 정확도입니다.
재현 방법:yolo val classify data=path/to/ImageNet device=0 - **속도(Speed)**는 Amazon EC2 P4d 인스턴스를 사용하여 ImageNet 검증 이미지에 대해 평균을 낸 것입니다.
재현 방법:yolo val classify data=path/to/ImageNet batch=1 device=0|cpu - Params 및 FLOPs 값은 Conv와 BatchNorm 레이어를 병합하는
model.fuse()이후의 융합된 모델에 대한 것입니다. 사전 학습된 체크포인트는 전체 학습 아키텍처를 유지하므로 더 높은 수치를 보일 수 있습니다.
학습 (Train)
MNIST160 데이터셋에서 이미지 크기 64로 100 에포크(epochs) 동안 YOLO26n-cls를 학습시킵니다. 사용 가능한 인수의 전체 목록은 구성(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)Ultralytics YOLO 분류는 학습을 위해 torchvision.transforms.RandomResizedCrop을 사용하고, 검증 및 추론을 위해 torchvision.transforms.CenterCrop을 사용합니다.
이 크롭 기반 변환은 정사각형 입력을 가정하므로 극단적인 가로세로비를 가진 이미지에서 중요한 영역을 의도치 않게 잘라내어 학습 중 중요한 시각적 정보가 손실될 수 있습니다.
비율을 유지하면서 전체 이미지를 보존하려면 크롭 변환 대신 torchvision.transforms.Resize를 사용하는 것을 고려하십시오.
사용자 지정 ClassificationDataset 및 ClassificationTrainer를 통해 증강 파이프라인을 사용자 지정하여 이를 구현할 수 있습니다.
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)데이터셋 형식
YOLO 분류 데이터셋 형식에 대한 자세한 내용은 데이터셋 가이드에서 확인할 수 있습니다. 분류 데이터셋은 Ultralytics Platform에서도 관리 및 라벨링이 가능합니다.
검증 (Val)
MNIST160 데이터셋에서 학습된 YOLO26n-cls 모델 정확도(accuracy)를 검증합니다. model이 학습 data와 인수를 모델 속성으로 유지하므로 별도의 인수가 필요하지 않습니다.
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 accuracyAs mentioned in the training section, you can handle extreme aspect ratios during training by using a custom ClassificationTrainer. You need to apply the same approach for consistent validation results by implementing a custom ClassificationValidator when calling the val() method. Refer to the complete code example in the training section for implementation details.
예측(Predict)
학습된 YOLO26n-cls 모델을 사용하여 이미지에 대한 예측을 실행합니다.
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 imagepredict 모드에 대한 자세한 내용은 Predict 페이지를 참조하십시오.
내보내기 (Export)
YOLO26n-cls 모델을 ONNX, CoreML 등과 같은 다른 형식으로 내보냅니다.
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")사용 가능한 YOLO26-cls 내보내기 형식은 아래 표와 같습니다. format 인수를 사용하여 모든 형식으로 내보낼 수 있습니다(예: format='onnx' 또는 format='engine'). 내보낸 모델에 대해 직접 예측하거나 검증할 수 있습니다(예: yolo predict model=yolo26n-cls.onnx). 모델 내보내기가 완료된 후 사용 예시가 표시됩니다.
| 형식 | format 인수 | 모델 | 메타데이터 | 인수 |
|---|---|---|---|---|
| PyTorch | - | yolo26n-cls.pt | ✅ | - |
| TorchScript | torchscript | yolo26n-cls.torchscript | ✅ | imgsz, half, dynamic, optimize, nms, batch, device |
| ONNX | onnx | yolo26n-cls.onnx | ✅ | imgsz, half, dynamic, simplify, opset, nms, batch, 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, 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 |
전체 export 세부 정보는 내보내기 페이지를 참조하십시오.
FAQ
이미지 분류에서 YOLO26의 목적은 무엇입니까?
yolo26n-cls.pt와 같은 YOLO26 모델은 효율적인 이미지 분류를 위해 설계되었습니다. 이 모델은 신뢰도 점수와 함께 전체 이미지에 단일 클래스 레이블을 할당합니다. 이는 이미지 내 객체의 위치나 모양을 식별하는 대신 이미지의 특정 클래스를 아는 것으로 충분한 응용 분야에 특히 유용합니다.
이미지 분류를 위해 YOLO26 모델을 어떻게 학습시킵니까?
YOLO26 모델을 학습시키려면 Python 또는 CLI 명령을 사용할 수 있습니다. 예를 들어, MNIST160 데이터셋에서 이미지 크기 64로 100 에포크 동안 yolo26n-cls 모델을 학습시키려면 다음과 같이 합니다:
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)더 많은 구성 옵션은 구성(Configuration) 페이지를 방문하십시오.
사전 학습된 YOLO26 분류 모델은 어디에서 찾을 수 있습니까?
사전 학습된 YOLO26 분류 모델은 모델(Models) 섹션에서 찾을 수 있습니다. yolo26n-cls.pt, yolo26s-cls.pt, yolo26m-cls.pt 등과 같은 모델은 ImageNet 데이터셋으로 사전 학습되어 있으며 쉽게 다운로드하여 다양한 이미지 분류 작업에 사용할 수 있습니다.
학습된 YOLO26 모델을 다른 형식으로 어떻게 내보낼 수 있습니까?
Python 또는 CLI 명령을 사용하여 학습된 YOLO26 모델을 다양한 형식으로 내보낼 수 있습니다. 예를 들어, 모델을 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")자세한 내보내기 옵션은 내보내기(Export) 페이지를 참조하십시오.
학습된 YOLO26 분류 모델을 어떻게 검증합니까?
MNIST160과 같은 데이터셋에서 학습된 모델의 정확도를 검증하려면 다음 Python 또는 CLI 명령을 사용할 수 있습니다:
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더 자세한 정보는 검증(Validate) 섹션을 방문하십시오.