Ultralytics YOLO를 사용한 이미지 분류

Ultralytics YOLO image classification of leaves as healthy, rust, or powdery mildew

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

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



시청: Ultralytics 작업 살펴보기: Ultralytics Platform을 사용한 이미지 분류
팁

YOLO26 Classify 모델은 -cls 접미사를 사용합니다(예: yolo26n-cls.pt). 이 모델은 ImageNet으로 사전 학습되었습니다.

모델#

ImageNet 데이터셋으로 사전 학습된 YOLO26 Classify 모델은 아래와 같습니다.

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

모델크기
(픽셀)
acc
top1
acc
top5
속도
CPU ONNX
(ms)
속도
T4 TensorRT10
(ms)
파라미터
(M)
FLOPs
(B), 224 기준
YOLO26n-cls22471.490.15.0 ± 0.31.1 ± 0.02.80.4
YOLO26s-cls22476.092.97.9 ± 0.21.3 ± 0.06.71.5
YOLO26m-cls22478.194.217.2 ± 0.42.0 ± 0.011.64.8
YOLO26l-cls22479.094.623.2 ± 0.32.8 ± 0.014.16.0
YOLO26x-cls22479.995.041.4 ± 0.93.8 ± 0.029.613.5
  • acc 값은 ImageNet 데이터셋 검증 세트에서 측정한 모델 정확도입니다.
    yolo classify val data=path/to/ImageNet device=0로 재현할 수 있습니다.
  • 속도는 CPU에서 ONNX를 사용하고 NVIDIA T4 GPU에서 TensorRT10을 사용하여 ImageNet 검증 이미지 전체의 평균을 측정한 값입니다.
    yolo classify val data=path/to/ImageNet batch=1 device=0|cpu로 재현할 수 있습니다.
  • Params 및 FLOPs 값은 Conv 및 BatchNorm 레이어를 병합하는 model.fuse() 이후의 융합 모델 기준입니다. 사전 학습된 체크포인트에는 전체 학습 아키텍처가 유지되므로 더 높은 값이 표시될 수 있습니다.

예비 분류 속도 및 모델 크기는 미공개 YOLO27 프리뷰를 참조하세요.

학습#

이미지 크기 64로 MNIST160 데이터셋에서 100 에포크 동안 YOLO26n-cls 모델을 학습합니다.

예제
from ultralytics import YOLO

# 모델 로드
model = YOLO("yolo26n-cls.yaml")  # YAML에서 새 모델을 생성합니다.
model = YOLO("yolo26n-cls.pt")  # 사전 학습된 모델을 불러옵니다(학습에 권장).
model = YOLO("yolo26n-cls.yaml").load("yolo26n-cls.pt")  # YAML에서 모델을 생성하고 가중치를 전이합니다.

# 모델 학습
results = model.train(data="mnist160", epochs=100, imgsz=64)

Train 페이지에서 전체 train 모드 세부 정보를 확인하세요. 분류 모델은 Ultralytics Platform 클라우드 학습으로도 학습할 수 있습니다.

데이터셋 형식#

YOLO 분류 데이터셋 형식에 대한 자세한 내용은 데이터셋 가이드를 참조하세요. 분류 데이터셋은 Ultralytics Platform 주석 도구로 관리하고 라벨링할 수도 있습니다.

사용자 지정 변환#

Ultralytics YOLO 분류에서는 학습에 torchvision.transforms.RandomResizedCrop을 사용하고 검증 및 추론에 torchvision.transforms.CenterCrop을 사용합니다. 이러한 크롭 기반 변환은 정사각형 입력을 가정하므로 종횡비가 매우 큰 이미지에서 중요한 영역이 잘릴 수 있습니다. 이미지를 늘이지 않고 전체를 유지하려면 크롭을 기존 ClassifyLetterBox 변환으로 대체합니다. 이 변환은 종횡비를 유지하면서 각 이미지의 크기를 imgsz × imgsz 영역에 맞게 조정하고 나머지 영역에 패딩을 추가합니다. 사용자 지정 ClassificationDataset, ClassificationTrainer, ClassificationValidator을 통해 PIL 기반 torchvision 파이프라인에서 사용합니다:

import numpy as np
import torch
import torchvision.transforms as T

from ultralytics import YOLO
from ultralytics.data.augment import ClassifyLetterBox
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 = "", names=None):
        """Initialize a customized classification dataset with enhanced data augmentation transforms."""
        super().__init__(root, args, augment, prefix, names)
        letterbox = T.Compose([np.asarray, ClassifyLetterBox(args.imgsz), T.ToPILImage()])

        # 여기에 사용자 지정 학습 변환을 추가합니다
        train_transforms = T.Compose(
            [
                letterbox,
                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),
            ]
        )

        # 여기에 사용자 지정 검증 변환을 추가합니다
        val_transforms = T.Compose(
            [
                letterbox,
                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="train" if mode == "train" else self.args.split,
            names=self.data["names"],
        )

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, names=self.names)

model = YOLO("yolo26n-cls.pt")
model.train(data="imagenet", trainer=CustomizedTrainer, epochs=10, imgsz=224, batch=64)
model.val(data="imagenet", validator=CustomizedValidator, imgsz=224, batch=64)

검증#

학습된 YOLO26n-cls 모델의 정확도를 검증합니다. model에 학습 data와 인수가 모델 속성으로 유지되므로 별도의 인수가 필요하지 않습니다. Train 예제의 path/to/best.pt은 MNIST160에서 검증을 수행합니다. 공식 가중치에는 사용자의 컴퓨터에 존재하지 않는 학습 데이터셋 경로가 기록되어 있으므로, 경고와 함께 작업 기본값인 imagenet10로 대체됩니다. 다른 데이터셋으로 검증하려면 data을 전달하세요.

예제
from ultralytics import YOLO

# 모델 로드
model = YOLO("yolo26n-cls.pt")  # 공식 모델을 불러옵니다
model = YOLO("path/to/best.pt")  # 사용자 지정 모델 로드

# 모델을 검증합니다
metrics = model.val()  # 데이터셋과 설정이 기억되므로 인수가 필요하지 않습니다
metrics.top1  # top1 accuracy
metrics.top5  # top5 accuracy
팁

사용자 지정 변환으로 학습된 모델은 해당하는 ClassificationValidator을 val()에 전달해야 합니다. 그렇지 않으면 학습 시 크기를 조정한 영역이 아니라 검증 중에 크롭됩니다.

예측#

학습된 YOLO26n-cls 모델을 사용해 이미지에 대한 예측을 수행합니다.

예제
from ultralytics import YOLO

# 모델 로드
model = YOLO("yolo26n-cls.pt")  # 공식 모델을 불러옵니다
model = YOLO("path/to/best.pt")  # 사용자 지정 모델 로드

# 모델로 예측을 수행합니다
results = model("https://ultralytics.com/images/bus.jpg")  # 이미지에 대해 예측을 수행합니다

# 결과에 액세스합니다
for result in results:
    top1 = result.probs.top1  # 가장 높은 예측 클래스 ID
    top1_conf = result.probs.top1conf  # 가장 높은 예측 신뢰도
    top1_name = result.names[top1]  # 가장 높은 예측 클래스 이름

Predict 페이지에서 predict 모드의 전체 세부 정보를 확인하세요.

결과 출력#

이미지 분류는 이미지당 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 필드를 확인하려면 작업별 예측 결과 섹션을 참조하세요.

내보내기#

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

예제
from ultralytics import YOLO

# 모델 로드
model = YOLO("yolo26n-cls.pt")  # 공식 모델을 불러옵니다
model = YOLO("path/to/best.pt")  # 사용자 지정 모델 로드

# 모델을 내보냅니다
model.export(format="onnx")

사용 가능한 YOLO26-cls 내보내기 형식은 아래 표에 나와 있습니다. format 인수를 사용하면 원하는 형식으로 내보낼 수 있습니다(예: format='onnx' 또는 format='engine'). 내보낸 모델에서 바로 예측하거나 검증할 수 있습니다(예: yolo predict model=yolo26n-cls.onnx). 내보내기가 완료되면 모델 사용 예제가 표시됩니다.

형식format 인수모델메타데이터인수
PyTorch-yolo26n-cls.pt✅-
TorchScripttorchscriptyolo26n-cls.torchscript✅imgsz, quantize, dynamic, nms, batch, device
ONNXonnxyolo26n-cls.onnx✅imgsz, quantize, dynamic, simplify, opset, nms, batch, data, fraction, device
OpenVINOopenvinoyolo26n-cls_openvino_model/✅imgsz, quantize, dynamic, nms, batch, data, fraction, device
TensorRTengineyolo26n-cls.engine✅imgsz, quantize, dynamic, simplify, opset, workspace, nms, batch, data, fraction, device
CoreMLcoremlyolo26n-cls.mlpackage✅imgsz, dynamic, quantize, nms, batch, device
Apple Core AIcoreaiyolo26n-cls.aimodel✅imgsz, batch, quantize
TF SavedModelsaved_modelyolo26n-cls_saved_model/✅imgsz, quantize, opset, nms, batch, data, fraction, device
TF GraphDefpbyolo26n-cls.pb❌imgsz, opset, batch, device
TF Edge TPUedgetpuyolo26n-cls_edgetpu.tflite✅imgsz, quantize, opset, data, fraction, device
LiteRTlitertyolo26n-cls.tflite✅imgsz, quantize, batch, data, fraction, device
PaddlePaddlepaddleyolo26n-cls_paddle_model/✅imgsz, batch, device
MNNmnnyolo26n-cls.mnn✅imgsz, batch, dynamic, quantize, simplify, opset, nms, device
NCNNncnnyolo26n-cls_ncnn_model/✅imgsz, quantize, device
IMX500imxyolo11n_imx_model/✅imgsz, quantize, data, fraction, nms, device
RKNNrknnyolo26n-cls_rknn_model/✅imgsz, batch, name, quantize, simplify, opset, data, fraction, device
ExecuTorchexecutorchyolo26n-cls_executorch_model/✅imgsz, quantize, batch, data, fraction, device
Axeleraaxelerayolo26n-cls_axelera_model/✅imgsz, batch, quantize, data, fraction, device
DEEPXdeepxyolo26n-cls_deepx_model/✅imgsz, quantize, simplify, opset, data, optimize, device
Qualcomm QNNqnnyolo26n-cls_qnn.onnx✅imgsz, batch, name, quantize, simplify, opset, data, fraction, device
Hailohailoyolo26n-cls_hailo_model/✅imgsz, name, quantize, data, fraction, simplify, conf, iou, device
Huawei Ascendascendyolo26n-cls_ascend_model/✅imgsz, batch, name, quantize, opset, simplify, nms, device
AMD Xilinxxilinxyolo26n-cls_xilinx_model/✅imgsz, name, quantize, data, fraction, opset, simplify, device
NXPnxpyolo26n-cls_nxp.tflite✅imgsz, quantize, data, fraction, device
ST Edge AIstedgeaiyolo26n-cls_stedgeai.onnx✅imgsz, quantize, data, fraction, opset, simplify, device

nms=None은 외부 NMS를 위해 기본적으로 원시 출력을 사용합니다(YOLO26은 Axelera에서 NMS가 필요 없는 헤드를 유지합니다). 사용 가능한 NMS가 필요 없는 헤드를 선택하려면 nms=False를 설정하세요. 지원되지 않는 형식은 해당 형식의 기본 출력 경로로 대체됩니다. 위의 nms 항목은 nms=True로 NMS를 포함할 수 있는 형식을 나타냅니다.

자세한 export 내용은 내보내기 페이지를 참조하세요.

자주 묻는 질문#

  • yolo26n-cls.pt과 같은 YOLO26 모델은 효율적인 이미지 분류를 수행하도록 설계되었습니다. 이미지 전체에 단일 클래스 레이블과 신뢰도 점수를 지정합니다. 이미지의 클래스만 알면 충분하고 이미지 내 객체의 위치나 모양은 알 필요가 없는 경우 유용합니다.

  • Python 또는 CLI 명령을 사용해 YOLO26 모델을 학습할 수 있습니다. 예를 들어 MNIST160 데이터셋에서 이미지 크기 64, 에포크 100회로 yolo26n-cls 모델을 학습하려면 다음과 같이 실행합니다.

    예제
    from ultralytics import YOLO
    
    # 모델 로드
    model = YOLO("yolo26n-cls.pt")  # 사전 학습된 모델을 불러옵니다(학습에 권장).
    
    # 모델 학습
    results = model.train(data="mnist160", epochs=100, imgsz=64)

    구성 옵션을 더 알아보려면 구성 페이지를 방문하세요.

  • Ultralytics Platform에서 사전 학습된 YOLO26 분류 모델을 찾아보고 테스트하고 다운로드할 수 있습니다. yolo26n-cls.pt, yolo26s-cls.pt, yolo26m-cls.pt과 같은 모델은 ImageNet 데이터셋으로 사전 학습되었으며, 처음 사용할 때 자동으로 다운로드됩니다.

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

    예제
    from ultralytics import YOLO
    
    # 모델 로드
    model = YOLO("path/to/best.pt")  # 학습된 모델 로드
    
    # 모델을 검증합니다
    metrics = model.val()  # 인수는 필요하지 않으며, 학습에 사용한 데이터셋과 설정을 사용합니다.
    metrics.top1  # top1 accuracy
    metrics.top5  # top5 accuracy

    자세한 내용은 검증 섹션을 참조하세요.

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

    예제
    from ultralytics import YOLO
    
    # 모델 로드
    model = YOLO("yolo26n-cls.pt")  # 학습된 모델 로드
    
    # 모델을 ONNX로 내보내기
    model.export(format="onnx")

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

댓글207

질문을 하거나 결과를 공유하거나 다른 사람을 도와주세요.

  1. hellotenetGitHub

    According to my observation, during the training of YOLO for classification tasks, it randomly selects a portion of data from the test set to evaluate the accuracy of this round. If I want to use all the data in the test set for testing in each epoch and provide top_acc1 and top_acc5, which parameter should I add in the yaml file?

    1
  2. eladoni1GitHub(수정됨)

    Hi there! Quick briefing - the images are of size Width = 1216, Height = 292.

    TL;DR - After debug into train.py & predict.py, realized the images are resized + cropped strangely from what I gathered in the docs/forums, even with specified imgsz and rect=True.

    Full explanation -

    Training was : model.train(data=..., imgsz=1216, rect=True)

    Expectations : Was expecting the dataset images to be resized BY THE LARGER side, so 1216 will remain 1216, and so is the smaller side.

    (Even when I tried to do imgsz as a tuple - (h,w) aka (292,1216), a warning showed up, telling me the imgsz will be automatically selected to 1216, as it should have been an integer.. not a tuple.)

    What actually happened : What happened is the smaller side (height, 292) resized to 1216, then the original, bigger side (width, 1216), was resized to 5063 (same scalar the smaller side was multiplied).

    Meaning, what previously was image of size 1216x292, turned into image of size 5063x1216 (This is due to Resize transformation of pytorch)

    And its not over - the data taken was only the INNER 1216x1216 - less than 1/4 of the actual data.. (This is due to CenterCrop transformation of pytorch)

    So, basically, I am asking - Is there a quote from the docs I have missed that said classify must be square sized? Or is there another way (except from padding to 1216x1216 - adding 924 black pixels to the height), to make classify work with rectangular images?

    Thank you so much, and sorry if I wasnt clear.. hopefully it was.

    1
    1. Glenn JocherUltralytics

      Hey there! 🙌 Thanks for the detailed message.

      It seems like you've encountered an interesting scenario with image sizes and the rect=True parameter. In YOLOv8, when using rectangular training (rect=True), the model does expect square input sizes for simplicity and efficiency. The behavior you've noticed, where the smaller dimension gets resized to match the specified imgsz, and then the image is center-cropped, is by design for handling non-square inputs.

      For your specific case with rectangular images (1216x292), instead of resizing or padding the images manually to make them square, a recommended approach is to work with the default behavior but ensure your imgsz is set to the dimension that avoids data loss. If further customization is necessary, it might involve custom modifications to the data preprocessing pipeline.

      Unfortunately, there isn't a built-in switch for direct handling of non-square images without cropping or resizing as you described. This is an area for potential improvement in future updates!

      For now, perhaps consider either adjusting your pipeline to accommodate this behavior or implementing a custom preprocessing step that ensures your images maintain their aspect ratio without significant data loss. Padding might be an unavoidable step for cases like these.

      If there's anything else we can help with or if you have suggestions, feel free to reach out. Thanks for diving deep into this, and we're here to support your projects! 🚀

  3. lixjohnGitHub

    If I can train Yolo-cls mode to identify the level of object moisture content? Such as coal? Thanks.

    1. Glenn JocherUltralytics

      Yes, Ultralytics YOLO26 classification can work for coal moisture levels if you label them as discrete classes like dry, medium, and wet and train with the standard classification dataset format; if you need an exact moisture percentage rather than bins, that’s a regression problem, and if the visual differences are subtle you may need NIR/thermal imaging instead of RGB alone.

    2. lixjohnGitHub

      Thanks, I think classification is enough because we just need high level of coal moisture not exact percentage.

    3. Glenn JocherUltralytics

      Yes, that should be a good fit for classify; use a few clear bins like low, medium, and high, keep lighting/camera distance as consistent as possible, and start from a pretrained yolo26n-cls.pt model—if you’d like, share a sample class layout or training command here and we can sanity-check it.

    4. lixjohnGitHub

      Thank you very much, that makes sense. I just start project and not go to training phase yet, but I am happy to share sample and training command once I have to get more help on this.

    5. lixjohnGitHub

      Thank you! I got another question related to segment, hopefully I can get your suggestion as well, it is a little bit tricky :-). The coal is very small ( around 10mm one piece), but we have identify them in a truck (10m*3m) in order to ensure the truck carry right size of coal, one picture for one truck, it means there are huge member of small coal in one picture, I don't have image resolution yet, but I suppose it is clear enough to show details for each coal, my questions are

      1. how to label data before training, I can use SAM to label each coal but I have to say it is impossible to label all coal in picture because the coal member is huge, if I can just label some of them in pictures? I think we can use around 300 pictures to start training, but not all coal labeled in one picture. Does it will impact accuracy of model?
      2. Is it possible for Yolo26-segment to identify each coal in this situation from algorithm and performance point of view? In one picture, the truck is big but carry large member of similar small objects (10mm vs. 10m). Any solution we can take for this situation?

      Apricate for any suggestions...

    6. Glenn JocherUltralytics

      Yes, but you should not leave visible coals unlabeled in training images because the model will treat them as background and recall will drop; for this kind of dense small-object problem, the practical approach is to split each truck image into smaller overlapping tiles, fully annotate every visible coal inside the selected tiles, and train on those crops rather than the full frame. If each coal is still only a few pixels after tiling, segment will struggle and detect or even patch-level classify may be a better fit, and our data collection and annotation guide is a good reference—feel free to post one sample image here when you have it and we can suggest the best labeling strategy.

    1. Glenn JocherUltralytics

      分类任务里类别索引顺序是从你的数据集目录结构推断出来的(通常按 train/ 下各类别子文件夹名称排序生成),如果你想“指定顺序”,最稳妥的方法是把类别文件夹命名成可排序的形式(例如 00_cat/、01_dog/);训练完成后直接读取模型里的 model.names 就能看到标签到索引的对应关系,参考 图像分类文档。

      from ultralytics import YOLO
      
      model = YOLO("runs/classify/train/weights/best.pt")
      print(model.names)  # {0: '00_cat', 1: '01_dog', ...}
  4. serenamansurGitHub

    hello, hope all is well. @glenn-jocher i would like to ask you few questions

    1- in classification task , when finetuning YOLOv11m-cls, is it enough to set "autoaugment" for data augmentation or i can use it with other augmentation args such as scale, hsv_v, hsv_s ??


    2- i will give you an example on this one, lets say i am training with epoch = 50 with patience = 8 and close_mosaic i set to = 5 and early stopping occured at epoch 20/50.

    Is close_mosaic applied here or is it set from the start that it should be disabled at epoch 45? and if it was disabled before epoch 20, how does this affect the result and validation?

    Thank you in advance!!

    1. Glenn JocherUltralytics

      For classify, auto_augment can be used together with other augmentation args like scale and hsv_h/hsv_s/hsv_v (they target different parts of the classification transform pipeline), but since policies like randaugment are already quite strong you’ll usually want to keep extra color jitter mild and tune one knob at a time; see the Image Classification docs and the classification transforms/augmentations reference.

      Also note close_mosaic is a mosaic-specific setting for detection-style tasks and isn’t used for *-cls training, so it won’t affect YOLO classification; if you meant detection, close_mosaic=5 disables mosaic only for the last 5 scheduled epochs (i.e., starting at epochs - close_mosaic), so if early stopping ends at epoch 20/50 that “close mosaic” switch never occurs.

    2. serenamansurGitHub

      Hello @glenn-jocher, Thank you for your previous reply, it was very helpful. I have another question related to class imbalance in computer vision tasks. In many ML setups, when classes are imbalanced, we apply per-class loss weights so that rare classes contribute more to the overall training loss and are not ignored during optimization.

      For example, if I have 3 detection classes with instance counts like:

      class0 = 30 instances class1 = 500 instances class2 = 700 instances

      By default, all classes contribute equally (weight = 1), but ideally I’d like to assign a higher weight to the rare class (class0).


      My question: Is there a supported way in Ultralytics YOLO to apply per-class weights for the detection classification loss or bounding boxes loss (cls loss component)? If yes, where can I access and modify those weights?? Thank you in advance!

    3. Glenn JocherUltralytics

      At the moment Ultralytics YOLO doesn’t have a supported “per-class loss weight” hook for detection via data.yaml/CLI (for cls_loss or box losses); the only built-in knobs are the overall loss term weights like cls, box, and dfl in the configuration settings. If you need true per-class weighting you’ll have to implement it in a custom trainer/loss (the core detection loss lives in the loss implementation and can be swapped via the advanced customization guide); otherwise the practical workaround is to rebalance the dataset by oversampling/adding/augmenting the rare-class examples.

    4. maxexplorerGitHub

      Hi Ultralytics team, YOLO-classify always outputs class probabilities (probs) that sum to 1, even for completely unknown or out-of-distribution (OOD) inputs. As a result, unknown objects can be classified with high confidence (e.g., 0.8), and using a threshold does not always filter them. Are there any recommended strategies, best practices, or built-in options to reduce false high-confidence predictions on unknown data?
      Would combining classify with detect help in such cases? Thanks!

    5. Glenn JocherUltralytics

      You’re right: *-cls uses a softmax-style head, so the returned probs are normalized to sum to 1 by design, which means “unknown/OOD” will still get forced into a known class with some confidence; there isn’t a built-in OOD/reject option in Ultralytics YOLO classification today (beyond simple thresholding). A practical approach is to (a) add an explicit unknown (or “background”) class with diverse negative examples and train for rejection, and/or (b) run a detection model first and only classify detected crops—if nothing is detected you can safely treat the frame as unknown; see the Ultralytics YOLO image classification docs for the standard classify pipeline.

      If you want a lightweight post-process, you can gate predictions using max-softmax and an uncertainty score like entropy (often works better than max-prob alone):

      from ultralytics import YOLO
      import torch
      
      model = YOLO("yolo26n-cls.pt")
      results = model("path/to/img.jpg")
      
      r = results[0]
      p = r.probs.data  # class probabilities (tensor)
      max_p = float(p.max())
      entropy = float(-(p * (p + 1e-12).log()).sum())
      
      is_unknown = (max_p < 0.6) or (entropy > 2.5)  # tune on a held-out OOD set
  5. theoderickdayGitHub

    Hi I have a simple bit of code based on your example above and using a model I created myself. It works fine at identifying birds and I get output of the form:-

    0: 640x640 nut_hatch 0.30, house_sparrow 0.18, bluetit 0.17, cat 0.13, robin 0.12, 273.5ms Speed: 29.8ms preprocess, 273.5ms inference, 0.1ms postprocess per image at shape (1, 3, 640, 640) 2025-10-27.jpg

    I use the following lines to pass data from the Raspberry PI camera to the model:-

    frame = picam2.capture_array() results = model(frame)

    what I want to do is extract the probabilities from the results structure so I can save specific images when the prediction is over say 80%

    Any ideas?

  6. wdcs-fenilpatelGitHub

    @glenn-jocher

    I'm encountering a strange and seemingly unpredictable issue during inference with a YOLO classification model (using ultralytics package). The confidence score for every prediction is always exactly 0.5, regardless of the input image.

    All inference results return confidence = 0.5.

    The predicted class index might vary, but the confidence is always 0.5.

    This issue starts unpredictably—everything works fine for a while, then suddenly this behavior appears.

    Sometimes, simply rebooting the system resolves the issue temporarily, but it may reappear.

  7. Ranjith3436GitHub

    I am trying to train classification model. why you prefer you architecture. why don't you move transformer architecture? is it capable than ViT.

  8. wowosoGitHub

    What if we can't obtain metrics such as F1 score, mAP, recall, and precision in image classification tasks?