Meet YOLO26: next-gen vision AI.

Link to this section이미지 분류#

YOLO image classification of objects and scenes

이미지 분류는 지원되는 작업 중 가장 간단하며, 전체 이미지를 미리 정의된 클래스 집합 중 하나로 분류하는 작업입니다.

이미지 분류기의 출력은 단일 클래스 레이블과 신뢰도 점수입니다. 이미지 분류는 이미지에 어떤 클래스가 속해 있는지 알기만 하면 되고, 해당 클래스의 객체가 어디에 위치하는지나 정확한 모양이 무엇인지 알 필요가 없을 때 유용합니다.



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-cls22471.490.15.0 ± 0.31.1 ± 0.02.80.5
YOLO26s-cls22476.092.97.9 ± 0.21.3 ± 0.06.71.6
YOLO26m-cls22478.194.217.2 ± 0.42.0 ± 0.011.64.9
YOLO26l-cls22479.094.623.2 ± 0.32.8 ± 0.014.16.2
YOLO26x-cls22479.995.041.4 ± 0.93.8 ± 0.029.613.6
  • acc 값은 ImageNet 데이터셋 검증 세트에서의 모델 정확도입니다.
    재현하려면 yolo val classify data=path/to/ImageNet device=0을 사용하십시오.
  • SpeedAmazon EC2 P4d 인스턴스를 사용하여 ImageNet val 이미지에서 평균을 낸 값입니다.
    재현하려면 yolo val classify data=path/to/ImageNet batch=1 device=0|cpu를 사용하십시오.
  • ParamsFLOPs 값은 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 사용을 고려하십시오.

사용자 지정 ClassificationDatasetClassificationTrainer를 통해 증강 파이프라인을 사용자 지정하여 이를 구현할 수 있습니다.

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 accuracy

As 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.probsProbs(C,)클래스 확률.
result.probs.datatorch.float32(C,)클래스별 확률.
result.probs.top1int()상위 클래스 ID.
result.probs.top1conftorch.float32()상위 신뢰도.
result.probs.top5list[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-
TorchScripttorchscriptyolo26n-cls.torchscriptimgsz, half, dynamic, optimize, nms, batch, device
ONNXonnxyolo26n-cls.onnximgsz, half, int8, dynamic, simplify, opset, nms, batch, data, fraction, device
OpenVINOopenvinoyolo26n-cls_openvino_model/imgsz, half, dynamic, int8, nms, batch, data, fraction, device
TensorRTengineyolo26n-cls.engineimgsz, half, dynamic, simplify, workspace, int8, nms, batch, data, fraction, device
CoreMLcoremlyolo26n-cls.mlpackageimgsz, dynamic, half, int8, nms, batch, device
TF SavedModelsaved_modelyolo26n-cls_saved_model/imgsz, keras, int8, nms, batch, data, fraction, device
TF GraphDefpbyolo26n-cls.pbimgsz, batch, device
TF Litetfliteyolo26n-cls.tfliteimgsz, half, int8, nms, batch, data, fraction, device
TF Edge TPUedgetpuyolo26n-cls_edgetpu.tfliteimgsz, int8, data, fraction, device
TF.jstfjsyolo26n-cls_web_model/imgsz, half, int8, nms, batch, data, fraction, device
PaddlePaddlepaddleyolo26n-cls_paddle_model/imgsz, batch, device
MNNmnnyolo26n-cls.mnnimgsz, batch, int8, half, device
NCNNncnnyolo26n-cls_ncnn_model/imgsz, half, batch, device
IMX500imxyolo26n-cls_imx_model/imgsz, int8, data, fraction, nms, device
RKNNrknnyolo26n-cls_rknn_model/imgsz, batch, name, int8, data, fraction, device
ExecuTorchexecutorchyolo26n-cls_executorch_model/imgsz, batch, device
Axeleraaxelerayolo26n-cls_axelera_model/imgsz, batch, int8, data, fraction, device
DEEPXdeepxyolo26n-cls_deepx_model/imgsz, int8, data, optimize, device
Qualcomm QNNqnnyolo26n-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

자세한 내용은 검증 섹션을 방문하십시오.

댓글