Link to this section이미지 분류#
이미지 분류는 지원되는 작업 중 가장 간단하며, 전체 이미지를 미리 정의된 클래스 집합 중 하나로 분류하는 작업입니다.
이미지 분류기의 출력은 단일 클래스 레이블과 신뢰도 점수입니다. 이미지 분류는 이미지에 어떤 클래스가 속해 있는지 알기만 하면 되고, 해당 클래스의 객체가 어디에 위치하는지나 정확한 모양이 무엇인지 알 필요가 없을 때 유용합니다.
Watch: Explore Ultralytics YOLO Tasks: Image Classification using Ultralytics Platform
YOLO26 Classify 모델은 -cls 접미사를 사용하며(예: yolo26n-cls.pt), ImageNet에서 사전 훈련되었습니다.
Link to this section모델#
YOLO26 사전 훈련된 Classify 모델은 여기에 나와 있습니다. Detect, Segment, Pose 모델은 COCO 데이터셋으로 사전 훈련되었고, Semantic 모델은 Cityscapes로 사전 훈련되었으며, Classify 모델은 ImageNet 데이터셋으로 사전 훈련되었습니다.
모델은 처음 사용할 때 최신 Ultralytics 릴리스에서 자동으로 다운로드됩니다.
| 모델 | 크기 (픽셀) | acc top1 | acc 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 val 이미지에서 평균을 낸 값입니다.
재현하려면yolo val classify data=path/to/ImageNet batch=1 device=0|cpu를 사용하십시오. - Params 및 FLOPs 값은 Conv 및 BatchNorm 레이어를 병합하는
model.fuse()후의 융합된 모델에 대한 값입니다. 사전 훈련된 체크포인트는 전체 훈련 아키텍처를 유지하므로 더 높은 수치를 보일 수 있습니다.
Link to this section학습(Train)#
MNIST160 데이터셋에서 이미지 크기 64로 100 에포크 동안 YOLO26n-cls를 훈련합니다. 사용 가능한 전체 인수 목록은 구성 페이지를 참조하십시오.
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):
"""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데이터셋 형식#
YOLO 분류 데이터셋 형식에 대한 자세한 내용은 데이터셋 가이드에서 확인할 수 있습니다. 분류 데이터셋은 Ultralytics 플랫폼에서도 관리 및 라벨링할 수 있습니다.
Link to this section검증(Val)#
MNIST160 데이터셋에서 훈련된 YOLO26n-cls 모델 정확도를 검증합니다. 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.
Link to this section추론(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 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 name전체 predict 모드 세부 정보는 Predict 페이지를 확인하십시오.
Link to this section결과 출력#
이미지 분류는 이미지당 하나의 Results 객체를 반환합니다. 주요 예측 필드는 result.probs이며, 여기에는 클래스 확률 벡터와 상위 예측을 위한 도우미가 포함되어 있습니다.
| 속성 | 유형 | 모양 | 설명 |
|---|---|---|---|
result.probs | Probs | (C,) | 클래스 확률. |
result.probs.data | torch.float32 | (C,) | 클래스별 확률. |
result.probs.top1 | int | () | 상위 클래스 ID. |
result.probs.top1conf | torch.float32 | () | 상위 신뢰도. |
result.probs.top5 | list[int] | (<=5) | 상위 5개 클래스 ID. |
모든 작업에 걸친 작업별 Results 필드는 작업별 예측 결과 섹션을 참조하십시오.
Link to this section내보내기(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, 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_model/ | ✅ | imgsz, batch, name, int8, data, fraction, device |
전체 export 세부 사항은 Export 페이지에서 확인하십시오.
Link to this sectionFAQ#
Link to this section이미지 분류에서 YOLO26의 목적은 무엇입니까?#
yolo26n-cls.pt와 같은 YOLO26 모델은 효율적인 이미지 분류를 위해 설계되었습니다. 전체 이미지에 신뢰도 점수와 함께 단일 클래스 레이블을 할당합니다. 이는 이미지 내 객체의 위치나 모양을 식별하는 것보다 이미지의 특정 클래스를 아는 것으로 충분한 응용 프로그램에 특히 유용합니다.
Link to this section이미지 분류를 위해 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)더 많은 구성 옵션을 보려면 구성 페이지를 방문하십시오.
Link to this section사전 훈련된 YOLO26 분류 모델은 어디서 찾을 수 있습니까?#
사전 훈련된 YOLO26 분류 모델은 모델 섹션에서 찾을 수 있습니다. yolo26n-cls.pt, yolo26s-cls.pt, yolo26m-cls.pt 등과 같은 모델은 ImageNet 데이터셋으로 사전 훈련되어 있으며, 다양한 이미지 분류 작업을 위해 쉽게 다운로드하고 사용할 수 있습니다.
Link to this section훈련된 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")자세한 내보내기 옵션은 내보내기 페이지를 참조하십시오.
Link to this section훈련된 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자세한 내용은 검증 섹션을 방문하십시오.