콘텐츠로 건너뛰기

이미지 분류

이미지 분류 예제

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

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



참고: Ultralytics HUB를 사용하여 Ultralytics YOLO 작업: 이미지 분류를 살펴보세요.

YOLO11 Classify 모델은 다음을 사용합니다. -cls 접미사(예: yolo11n-cls.pt 에 대해 사전 훈련되었습니다. ImageNet.

모델

YOLO11 사전 훈련된 Classify 모델이 여기에 표시되어 있습니다. Detect, Segment 및 Pose 모델은 COCO 데이터 세트에서 사전 훈련되었으며, Classify 모델은 ImageNet 데이터 세트에서 사전 훈련되었습니다.

모델은 처음 사용할 때 최신 Ultralytics 릴리스에서 자동으로 다운로드됩니다.

모델 크기
(픽셀)
acc
top1
acc
top5
속도
CPU ONNX
(ms)
속도
T4 TensorRT10
(ms)
파라미터
(M)
FLOPs
(B) at 224
YOLO11n-cls 224 70.0 89.4 5.0 ± 0.3 1.1 ± 0.0 1.6 0.5
YOLO11s-cls 224 75.4 92.7 7.9 ± 0.2 1.3 ± 0.0 5.5 1.6
YOLO11m-cls 224 77.3 93.9 17.2 ± 0.4 2.0 ± 0.0 10.4 5.0
YOLO11l-cls 224 78.3 94.3 23.2 ± 0.3 2.8 ± 0.0 12.9 6.2
YOLO11x-cls 224 79.5 94.9 41.4 ± 0.9 3.8 ± 0.0 28.4 13.7
  • 정확도 (acc) 값은 다음 모델 정확도입니다. ImageNet 데이터 세트 유효성 검사 세트입니다.
    다음으로 재현합니다. yolo val classify data=path/to/ImageNet device=0
  • 속도 다음을 사용하여 ImageNet val 이미지에서 평균화되었습니다. 인스턴스를 사용하여 COCO val 이미지에서 평균을 냈습니다. 인스턴스.
    다음으로 재현합니다. yolo val classify data=path/to/ImageNet batch=1 device=0|cpu

Train

이미지 크기 64에서 100 epoch 동안 MNIST160 데이터 세트에서 YOLO11n-cls를 훈련합니다. 사용 가능한 전체 인수 목록은 구성 페이지를 참조하십시오.

예시

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.yaml")  # build a new model from YAML
model = YOLO("yolo11n-cls.pt")  # load a pretrained model (recommended for training)
model = YOLO("yolo11n-cls.yaml").load("yolo11n-cls.pt")  # build from YAML and transfer weights

# Train the model
results = model.train(data="mnist160", epochs=100, imgsz=64)
# Build a new model from YAML and start training from scratch
yolo classify train data=mnist160 model=yolo11n-cls.yaml epochs=100 imgsz=64

# Start training from a pretrained *.pt model
yolo classify train data=mnist160 model=yolo11n-cls.pt epochs=100 imgsz=64

# Build a new model from YAML, transfer pretrained weights to it and start training
yolo classify train data=mnist160 model=yolo11n-cls.yaml pretrained=yolo11n-cls.pt 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, 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("yolo11n-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 분류 데이터 세트 형식에 대한 자세한 내용은 데이터 세트 가이드에서 확인할 수 있습니다.

Val

훈련된 YOLO11n-cls 모델의 유효성을 검사합니다. 정확도 MNIST160 데이터 세트에서. 구성 파일에 결과가 저장되므로 인수가 필요하지 않습니다. model 훈련을 유지 data 하고 인수를 모델 속성으로 사용합니다.

예시

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-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
yolo classify val model=yolo11n-cls.pt  # val official model
yolo classify val model=path/to/best.pt # val custom model

에서 언급했듯이 학습 섹션, 사용자 정의를 사용하여 학습 중에 극단적인 가로 세로 비율을 처리할 수 있습니다. ClassificationTrainer일관된 유효성 검사 결과를 얻으려면 사용자 지정 항목을 구현하여 동일한 접근 방식을 적용해야 합니다. ClassificationValidator 호출할 때 val() 메서드. 전체 코드 예제는 다음에서 참조하십시오. 학습 섹션 구현 세부 정보는 다음을 참조하십시오.

예측

훈련된 YOLO11n-cls 모델을 사용하여 이미지에 대한 예측을 실행합니다.

예시

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-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
yolo classify predict model=yolo11n-cls.pt source='https://ultralytics.com/images/bus.jpg'  # predict with official model
yolo classify predict model=path/to/best.pt source='https://ultralytics.com/images/bus.jpg' # predict with custom model

전체 predict 모드에 대한 자세한 내용은 예측 페이지를 참조하세요.

내보내기

YOLO11n-cls 모델을 ONNX, CoreML 등과 같은 다른 형식으로 내보냅니다.

예시

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load an official model
model = YOLO("path/to/best.pt")  # load a custom trained model

# Export the model
model.export(format="onnx")
yolo export model=yolo11n-cls.pt format=onnx  # export official model
yolo export model=path/to/best.pt format=onnx # export custom trained model

사용 가능한 YOLO11-cls 내보내기 형식은 아래 표에 있습니다. 다음을 사용하여 모든 형식으로 내보낼 수 있습니다. format 인수, 즉 format='onnx' 또는 format='engine'입니다. 내보낸 모델에서 직접 예측하거나 유효성을 검사할 수 있습니다(예: yolo predict model=yolo11n-cls.onnx). 사용 예시는 내보내기가 완료된 후 모델에 대해 표시됩니다.

형식 format 인수 모델 메타데이터 인수
PyTorch - yolo11n-cls.pt -
TorchScript torchscript yolo11n-cls.torchscript imgsz, half, dynamic, optimize, nms, batch, device
ONNX onnx yolo11n-cls.onnx imgsz, half, dynamic, simplify, opset, nms, batch, device
OpenVINO openvino yolo11n-cls_openvino_model/ imgsz, half, dynamic, int8, nms, batch, data, fraction, device
TensorRT engine yolo11n-cls.engine imgsz, half, dynamic, simplify, workspace, int8, nms, batch, data, fraction, device
CoreML coreml yolo11n-cls.mlpackage imgsz, half, int8, nms, batch, device
TF SavedModel saved_model yolo11n-cls_saved_model/ imgsz, keras, int8, nms, batch, device
TF GraphDef pb yolo11n-cls.pb imgsz, batch, device
TF Lite tflite yolo11n-cls.tflite imgsz, half, int8, nms, batch, data, fraction, device
TF Edge TPU edgetpu yolo11n-cls_edgetpu.tflite imgsz, device
TF.js tfjs yolo11n-cls_web_model/ imgsz, half, int8, nms, batch, device
PaddlePaddle paddle yolo11n-cls_paddle_model/ imgsz, batch, device
MNN mnn yolo11n-cls.mnn imgsz, batch, int8, half, device
NCNN ncnn yolo11n-cls_ncnn_model/ imgsz, half, batch, device
IMX500 imx yolo11n-cls_imx_model/ imgsz, int8, data, fraction, device
RKNN rknn yolo11n-cls_rknn_model/ imgsz, batch, name, device

전체 export 세부 정보는 내보내기 페이지를 참조하세요.

FAQ

이미지 분류에서 YOLO11의 목적은 무엇입니까?

YOLO11 모델(예: yolo11n-cls.pt)은 효율적인 이미지 분류를 위해 설계되었습니다. 이러한 모델은 신뢰도 점수와 함께 전체 이미지에 단일 클래스 레이블을 할당합니다. 이는 이미지 내 객체의 위치나 모양을 식별하는 것보다 이미지의 특정 클래스를 아는 것으로 충분한 애플리케이션에 특히 유용합니다.

이미지 분류를 위해 YOLO11 모델을 어떻게 훈련합니까?

YOLO11 모델을 훈련하려면 python 또는 CLI 명령을 사용할 수 있습니다. 예를 들어, 다음을 훈련하려면 yolo11n-cls 이미지 크기 64에서 100 epoch 동안 MNIST160 데이터 세트에서 모델:

예시

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load a pretrained model (recommended for training)

# Train the model
results = model.train(data="mnist160", epochs=100, imgsz=64)
yolo classify train data=mnist160 model=yolo11n-cls.pt epochs=100 imgsz=64

자세한 구성 옵션은 구성 페이지를 참조하십시오.

사전 훈련된 YOLO11 분류 모델은 어디에서 찾을 수 있습니까?

사전 훈련된 YOLO11 분류 모델은 다음에서 찾을 수 있습니다. 모델 섹션. 다음과 같은 모델 yolo11n-cls.pt, yolo11s-cls.pt, yolo11m-cls.pt등은 다음에서 사전 훈련되었습니다. ImageNet 데이터 세트이며 다양한 이미지 분류 작업에 쉽게 다운로드하여 사용할 수 있습니다.

훈련된 YOLO11 모델을 다른 형식으로 어떻게 내보낼 수 있습니까?

학습된 YOLO11 모델을 Python 또는 CLI 명령어를 사용하여 다양한 형식으로 내보낼 수 있습니다. 예를 들어, 모델을 ONNX 형식으로 내보내려면 다음과 같이 하십시오.

예시

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-cls.pt")  # load the trained model

# Export the model to ONNX
model.export(format="onnx")
yolo export model=yolo11n-cls.pt format=onnx # export the trained model to ONNX format

자세한 내보내기 옵션은 내보내기 페이지를 참조하십시오.

훈련된 YOLO11 분류 모델을 어떻게 검증합니까?

MNIST160과 같은 데이터 세트에서 학습된 모델의 정확성을 검증하려면 다음 Python 또는 CLI 명령어를 사용할 수 있습니다.

예시

from ultralytics import YOLO

# Load a model
model = YOLO("yolo11n-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
yolo classify val model=yolo11n-cls.pt # validate the trained model

자세한 내용은 유효성 검사 섹션을 참조하십시오.



📅 1년 전에 생성됨 ✏️ 6일 전에 업데이트됨

댓글