Ultralytics를 사용한 K-Fold 교차 검증

소개#

이 가이드에서는 Ultralytics 생태계의 객체 탐지 데이터셋에 K-겹 교차 검증을 구현하는 방법을 설명합니다. YOLO 탐지 형식과 scikit-learn, pandas, PyYAML 등의 Python 라이브러리를 사용하여 설정, 특징 벡터 생성, K-겹 데이터셋 분할 과정을 안내합니다.

K-fold cross validation data splitting

Fruit Detection 데이터셋이나 사용자 지정 데이터 소스를 사용하는 프로젝트 모두 이 튜토리얼을 통해 머신러닝 모델의 신뢰성과 견고성을 높이는 K-겹 교차 검증의 원리를 이해하고 적용할 수 있습니다. 이 튜토리얼에서는 k=5개의 폴드를 사용하지만, 최적의 폴드 수는 데이터셋과 프로젝트의 세부 조건에 따라 달라질 수 있습니다. K-겹 교차 검증은 데이터셋이 작거나 노이즈가 많거나 변동성이 큰 경우 가장 효과적이며, 규모가 크고 다양한 데이터셋에는 일반적으로 잘 구성된 학습/검증/테스트 분할만으로 충분합니다.

설정#

  • 어노테이션은 YOLO 탐지 형식이어야 합니다.

  • 이 가이드에서는 어노테이션 파일을 로컬에서 사용할 수 있다고 가정합니다.

  • 시연에는 Fruit Detection 데이터셋을 사용합니다.

    • 이 데이터셋에는 총 8479개의 이미지가 포함되어 있습니다.
    • 이 데이터셋에는 6개의 클래스 레이블이 있으며, 각 클래스의 전체 인스턴스 수는 아래에 나와 있습니다.
클래스 레이블인스턴스 수
사과7049
포도7202
파인애플1613
오렌지15549
바나나3536
수박1976
  • 필요한 Python 패키지는 다음과 같습니다:

    • ultralytics
    • sklearn
    • pandas
    • pyyaml
  • 이 튜토리얼에서는 k=5개의 fold를 사용합니다. 하지만 사용자의 데이터셋에 가장 적합한 fold 수를 직접 결정해야 합니다.

  1. 프로젝트용 새 Python 가상 환경(venv)을 만들고 활성화하세요. pip(또는 선호하는 패키지 관리자)을 사용하여 다음을 설치합니다.

    • Ultralytics 라이브러리: pip install -U ultralytics. 또는 공식 저장소를 clone할 수 있습니다.
    • Scikit-learn, pandas, PyYAML: pip install -U scikit-learn pandas pyyaml.
  2. 어노테이션이 YOLO 탐지 형식인지 확인합니다.

    • 이 튜토리얼에서는 모든 어노테이션 파일이 Fruit-Detection/labels 디렉터리에 있다고 가정합니다.

객체 탐지 데이터셋의 feature vector 생성#

  1. 먼저 아래 단계를 위한 새 Python 파일 example.py을 만듭니다.

  2. Ultralytics YOLODataset 클래스를 사용하여 데이터셋 YAML에 나열된 학습 및 검증 이미지를 불러오고 테스트 분할은 변경하지 않습니다.

    from pathlib import Path
    
    from ultralytics.data.dataset import YOLODataset
    from ultralytics.data.utils import check_det_dataset
    
    yaml_file = "path/to/data.yaml"
    data = check_det_dataset(yaml_file)
    dataset_path = Path(data["path"])
    sources = []
    for split in ("train", "val"):
        source = data.get(split)
        if source:
            sources.extend(source if isinstance(source, list) else [source])
    dataset = YOLODataset(sources, data=data, augment=False)
    images = [Path(p) for p in dataset.im_files]
  3. 이제 데이터셋 YAML 파일의 내용을 읽고 클래스 레이블의 인덱스를 추출합니다.

    classes = data["names"]
    cls_idx = sorted(classes.keys())
  4. 빈 pandas DataFrame을 초기화합니다.

    import pandas as pd
    
    labels_df = pd.DataFrame(0.0, columns=cls_idx, index=images)
  5. 어노테이션 파일에 포함된 각 클래스 레이블의 인스턴스 수를 계산합니다.

    from collections import Counter
    
    for image, label in zip(images, dataset.labels):
        lbl_counter = Counter(label["cls"].flatten().astype(int))
        labels_df.loc[image, list(lbl_counter)] = list(lbl_counter.values())
  6. 값을 채운 DataFrame의 예시는 다음과 같습니다:

                                                           0    1    2    3    4    5
    '0000a16e4b057580_jpg.rf.00ab48988370f64f5ca8ea4...'  0.0  0.0  0.0  0.0  0.0  7.0
    '0000a16e4b057580_jpg.rf.7e6dce029fb67f01eb19aa7...'  0.0  0.0  0.0  0.0  0.0  7.0
    '0000a16e4b057580_jpg.rf.bc4d31cdcbe229dd022957a...'  0.0  0.0  0.0  0.0  0.0  7.0
    '00020ebf74c4881c_jpg.rf.508192a0a97aa6c4a3b6882...'  0.0  0.0  0.0  1.0  0.0  0.0
    '00020ebf74c4881c_jpg.rf.5af192a2254c8ecc4188a25...'  0.0  0.0  0.0  1.0  0.0  0.0
     ...                                                  ...  ...  ...  ...  ...  ...
    'ff4cd45896de38be_jpg.rf.c4b5e967ca10c7ced3b9e97...'  0.0  0.0  0.0  0.0  0.0  2.0
    'ff4cd45896de38be_jpg.rf.ea4c1d37d2884b3e3cbce08...'  0.0  0.0  0.0  0.0  0.0  2.0
    'ff5fd9c3c624b7dc_jpg.rf.bb519feaa36fc4bf630a033...'  1.0  0.0  0.0  0.0  0.0  0.0
    'ff5fd9c3c624b7dc_jpg.rf.f0751c9c3aa4519ea3c9d6a...'  1.0  0.0  0.0  0.0  0.0  0.0
    'fffe28b31f2a70d4_jpg.rf.7ea16bd637ba0711c53b540...'  0.0  6.0  0.0  0.0  0.0  0.0

행에는 절대 이미지 경로를 사용하고, 열은 클래스 레이블 인덱스에 대응합니다. 누락된 레이블은 모두 0인 배경 행으로 유지됩니다. 이러한 데이터 구조를 통해 객체 탐지 데이터셋에 K-겹 교차 검증을 적용할 수 있습니다.

K-Fold 데이터셋 분할#

  1. 이제 sklearn.model_selection의 KFold 클래스를 사용하여 데이터셋을 k개로 분할하겠습니다.

    • 중요:
      • shuffle=True을 설정하면 분할별 클래스 분포를 무작위로 구성할 수 있습니다.
      • M이 선택한 정수인 상태에서 random_state=M을 설정하면 반복 가능한 결과를 얻을 수 있습니다.
    from sklearn.model_selection import KFold
    
    ksplit = 5
    kf = KFold(n_splits=ksplit, shuffle=True, random_state=20)  # 반복 가능한 결과를 위해 random_state 설정
    
    kfolds = list(kf.split(labels_df))
  2. 이제 데이터셋이 k개의 fold로 분할되었으며, 각 fold에는 train 및 val 인덱스 목록이 있습니다. 이 결과를 더 명확하게 표시하기 위해 DataFrame을 구성하겠습니다.

    folds = [f"split_{n}" for n in range(1, ksplit + 1)]
    folds_df = pd.DataFrame(index=labels_df.index, columns=folds)
    
    for i, (train, val) in enumerate(kfolds, start=1):
        folds_df.loc[labels_df.index[train], f"split_{i}"] = "train"
        folds_df.loc[labels_df.index[val], f"split_{i}"] = "val"
  3. 이제 각 fold의 클래스 레이블 분포를 val에 포함된 클래스 수와 train에 포함된 클래스 수의 비율로 계산하겠습니다.

    fold_lbl_distrb = pd.DataFrame(index=folds, columns=cls_idx)
    
    for n, (train_indices, val_indices) in enumerate(kfolds, start=1):
        train_totals = labels_df.iloc[train_indices].sum()
        val_totals = labels_df.iloc[val_indices].sum()
    
        # To avoid division by zero, we add a small value (1E-7) to the denominator
        ratio = val_totals / (train_totals + 1e-7)
        fold_lbl_distrb.loc[f"split_{n}"] = ratio

    이상적인 상황은 각 분할과 클래스에서 모든 클래스 비율이 대체로 비슷한 것입니다. 다만 이는 데이터셋의 구체적인 특성에 따라 달라집니다.

  4. 각 분할의 이미지 목록과 데이터셋 YAML을 작성합니다. 텍스트 목록을 사용하면 데이터셋을 k회 복사하지 않아도 됩니다.

    import yaml
    
    save_path = dataset_path.parent / f"{ksplit}-Fold_Cross-val"
    save_path.mkdir(parents=True, exist_ok=True)
    ds_yamls = []
    
    for split in folds_df.columns:
        for partition in ("train", "val"):
            split_images = folds_df.index[folds_df[split] == partition]
            paths = "\n".join(map(str, split_images))
            (save_path / f"{split}_{partition}.txt").write_text(f"{paths}\n")
    
        dataset_yaml = save_path / f"{split}.yaml"
        ds_yamls.append(dataset_yaml)
        with open(dataset_yaml, "w") as ds_y:
            yaml.safe_dump(
                {
                    "path": save_path.as_posix(),
                    "train": f"{split}_train.txt",
                    "val": f"{split}_val.txt",
                    "names": classes,
                },
                ds_y,
            )

레코드 저장(선택 사항)#

선택적으로 K-Fold 분할 및 레이블 분포 DataFrame의 레코드를 CSV 파일로 저장해 나중에 참고할 수 있습니다.

folds_df.to_csv(save_path / "kfold_datasplit.csv")
fold_lbl_distrb.to_csv(save_path / "kfold_label_distribution.csv")

K-Fold 데이터 분할을 사용한 YOLO 학습#

  1. 먼저 YOLO 모델을 불러옵니다.

    from ultralytics import YOLO
    
    weights_path = "path/to/weights.pt"  # 작은 모델에는 yolo26n.pt를 사용합니다
    model = YOLO(weights_path, task="detect")
  2. 다음으로 데이터셋 YAML 파일을 반복하며 학습을 실행합니다. 결과는 project 및 name 인수로 지정한 디렉터리에 저장됩니다. 기본 디렉터리는 runs/detect/train#이며, 여기서 #은 정수 인덱스입니다.

    results = {}
    
    # Define your additional arguments here
    batch = 16
    project = "kfold_demo"
    epochs = 100
    
    for k, dataset_yaml in enumerate(ds_yamls):
        model = YOLO(weights_path, task="detect")
        results[k] = model.train(
            data=dataset_yaml, epochs=epochs, batch=batch, project=project, name=f"fold_{k + 1}"
        )  # include any additional train arguments
  3. Ultralytics의 autosplit 함수를 사용하여 데이터셋을 자동으로 분할할 수도 있습니다.

    from ultralytics.data.split import autosplit
    
    # 데이터셋을 train/val/test로 자동 분할
    autosplit(path="path/to/images", weights=(0.8, 0.2, 0.0), annotated_only=True)

결론#

이 가이드에서는 YOLO 객체 탐지 모델을 학습할 때 K-Fold 교차 검증을 사용하는 방법을 살펴보았습니다. 학습 및 검증 데이터 풀을 K개의 파티션으로 나누고, 무작위 분할 후 생성된 비율 표를 사용해 클래스 균형을 확인하는 방법을 알아보았습니다.

또한 데이터 분할과 분할별 레이블 분포를 시각화하는 보고서 DataFrame을 만드는 절차를 살펴보았습니다. 이를 통해 학습 및 검증 세트의 구조를 명확하게 파악할 수 있습니다.

선택적으로 나중에 참고할 수 있도록 레코드를 저장했습니다. 이는 대규모 프로젝트나 모델 성능 문제를 해결할 때 특히 유용할 수 있습니다.

마지막으로 각 분할을 반복해 실제 모델 학습을 수행하고, 추가 분석과 비교를 위해 학습 결과를 저장했습니다.

K-Fold 교차 검증은 사용 가능한 데이터를 최대한 활용하는 견고한 방법이며, 서로 다른 데이터 하위 집합에서도 모델 성능의 신뢰성과 일관성을 확보하는 데 도움이 됩니다. 이를 통해 특정 데이터 패턴에 과적합할 가능성이 낮고 일반화 성능과 신뢰성이 더 높은 모델을 얻을 수 있습니다.

이 가이드에서는 YOLO를 사용했지만, 이러한 단계는 대부분 다른 머신러닝 모델에도 적용할 수 있습니다. 각 단계를 이해하면 자체 머신러닝 프로젝트에서 교차 검증을 효과적으로 적용할 수 있습니다.

자주 묻는 질문#

  • K-Fold 교차 검증은 데이터셋을 'k'개의 하위 집합(fold)으로 나누어 모델 성능을 더 신뢰성 있게 평가하는 기법입니다. 각 fold는 학습 데이터이자 검증 데이터로 사용됩니다. 객체 탐지에서 K-Fold 교차 검증을 사용하면 다양한 데이터 분할에서 Ultralytics YOLO 모델의 성능이 견고하고 일반화 가능한지 확인하여 신뢰성을 높일 수 있습니다. Ultralytics YOLO에서 K-Fold 교차 검증을 설정하는 자세한 방법은 Ultralytics를 사용한 K-Fold 교차 검증을 참조하세요.

  • Ultralytics YOLO에서 K-Fold 교차 검증을 구현하려면 다음 단계를 따르세요:

    1. 어노테이션이 YOLO 탐지 형식인지 확인합니다.
    2. sklearn, pandas, pyyaml와 같은 Python 라이브러리를 사용합니다.
    3. 데이터셋에서 feature vector를 생성합니다.
    4. sklearn.model_selection의 KFold을 사용해 데이터셋을 분할합니다.
    5. 각 분할에서 YOLO 모델을 학습합니다.

    자세한 내용은 문서의 K-Fold 데이터셋 분할 섹션을 참조하세요.

  • 이 가이드의 워크플로는 YOLO 탐지 형식을 대상으로 하지만, 같은 접근 방식을 모든 YOLO 작업에 적용할 수 있습니다. 작업에 따라 fold 구성 방식은 달라지지만, 교차 검증의 효과 여부는 달라지지 않습니다:

    작업Fold 설계
    detect이미지 단위로 분할하면서 fold 간 객체 및 클래스 분포의 균형을 맞춥니다. 관련 이미지(같은 환자, 비디오 시퀀스, 카메라 또는 사이트)는 하나의 fold에 함께 배치합니다.
    segment탐지와 같은 이미지 단위 전략을 사용하되, 모든 fold에서 마스크와 클래스가 충분히 포함되도록 합니다.
    classify학습과 검증 간 클래스 빈도의 균형을 유지할 수 있도록 계층화된 fold를 우선적으로 사용합니다.
    pose동일한 사람이나 동물이 fold의 양쪽에 나타나지 않도록 개체 또는 시퀀스 단위로 분할합니다.
    obb이미지 단위로 분할하되, 특히 항공 이미지에서는 같은 장면에서 추출한 타일이나 crop을 함께 배치합니다.

    작업 유형과 관계없이 거의 중복되는 샘플과 서로 관련된 샘플이 서로 다른 폴드에 들어가지 않도록 하세요. 이런 종류의 누출은 검증 지표를 모델의 실제 배포 성능보다 훨씬 높게 부풀립니다.

  • Ultralytics YOLO는 높은 정확도와 효율성을 갖춘 최첨단 실시간 객체 감지 기능을 제공합니다. 활용 범위가 넓으며 객체 감지, 인스턴스 분할, 시맨틱 분할, 분류 등 다양한 컴퓨터 비전 작업을 지원합니다. 또한 코드 작성 없이 모델을 학습하고 배포할 수 있는 Ultralytics Platform과 같은 도구와 통합됩니다.

  • 어노테이션은 YOLO 탐지 형식을 따라야 합니다. 각 어노테이션 파일에는 객체 클래스와 이미지 내 바운딩 박스 좌표가 함께 기록되어야 합니다. YOLO 형식을 사용하면 객체 탐지 모델 학습을 위한 데이터 처리를 효율적이고 표준화된 방식으로 수행할 수 있습니다. 올바른 어노테이션 형식에 관한 자세한 내용은 YOLO 탐지 형식 가이드를 참조하세요.

  • 예, 어노테이션이 YOLO 탐지 형식이라면 모든 사용자 지정 데이터셋에 K-Fold 교차 검증을 사용할 수 있습니다. 데이터셋 경로와 클래스 레이블을 사용자 지정 데이터셋에 맞게 바꾸면 됩니다. 이러한 유연성 덕분에 모든 객체 탐지 프로젝트에서 K-Fold 교차 검증을 활용해 견고하게 모델을 평가할 수 있습니다. 실제 예시는 Feature Vector 생성 섹션을 참조하세요.

댓글21

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

  1. jingieboyGitHub

    does this work with yolov8-cls? if so how would the folder structure look like? how are the data splits

    1. Glenn JocherUltralytics(수정됨)

      Yes—K‑Fold works the same for classification; use the standard ImageNet-style layout per fold, and train each fold separately (YOLO infers classes from folder names). For YOLO26 (recommended) you can do:

      dataset/
        split_1/
          train/
            class_a/ ...
            class_b/ ...
          val/
            class_a/ ...
            class_b/ ...
        split_2/
          train/...
          val/...
        ...
      from ultralytics import YOLO
      
      weights = "yolo26n-cls.pt"  # swap to 'yolov8n-cls.pt' if you prefer YOLOv8
      splits = ["dataset/split_1", "dataset/split_2", "dataset/split_3"]
      
      for d in splits:
          model = YOLO(weights)
          model.train(data=d, epochs=20, batch=16)  # d must contain 'train/' and 'val/' subfolders

      For building folds, use StratifiedKFold on image-level labels derived from parent folder names to keep class balance, or use the random splitter shown in the autosplit reference if stratification isn’t required. Classification usage details are in the classification task docs.

    2. jingieboyGitHub

      thank you for this! I have also notice that everytime I run model.val(), the accuracies and confusion matrix values are slightly different this time. Is this normal or during evaluation, there is a small randomness when calling the function.

    3. Glenn JocherUltralytics

      @jingieboy minor variations can occur from non-deterministic CUDA ops or multi-threading; validation itself doesn’t add randomness by default—set seeds and force deterministic ops to lock results:

      import random, numpy as np, torch
      
      seed = 0
      random.seed(seed); np.random.seed(seed); torch.manual_seed(seed)
      torch.backends.cudnn.deterministic = True
      torch.backends.cudnn.benchmark = False
      
      model.val()  # run evaluation

      If differences are still large, double-check your eval args in the validation mode docs.

  2. NehasqGitHub

    Hi, I am applying K-fold validation using the leave-one-out technique. My dataset consists of a single class and includes 21 images in total. For each split, I use 20 images for training and 1 image for testing. I am implementing the leave-one-out technique with the code above, setting ksplit=21.

    I am not using a separate validation dataset, only training and testing data. Here is the code I am using:

    results = {}

    Define additional arguments here

    batch = 16 project = "kfold_demo" epochs = 100

    for k in range(ksplit): dataset_yaml = ds_yamls[k] model = YOLO(weights_path, task="detect") model.train(data=dataset_yaml, epochs=epochs, batch=batch, project=project) # Include any train arguments results[k] = model.metrics # Save output metrics for further analysis

    In my data.yaml file, I have provided the validation path as the test set. When it trains and validates on the "1 test data," does this mean the model is being tested on data it has never seen during training? This is my first point of confusion.

    my data.yaml file for each split looks like this: names:

    • pothole path: ../ 2024-12-10_21-Fold_Cross-val/split_1 train: train val: test

    My second question is about calculating the final performance. When I ran the above code, it calculated scores for each individual split. Do I need to calculate the final performance metrics manually, or is there any functionality in YOLOv8 to compute the aggregated performance automatically?

    1. Glenn JocherUltralytics

      @Nehasq to address your first question, yes, the model is being tested on unseen data during each split, as the test set (1 image) is excluded from training and only used for validation. Regarding your second question, YOLO does not automatically aggregate metrics across splits. You need to compute the final performance metrics manually by averaging the results from all splits. For reference, you can review the K-Fold Cross Validation guide.

    2. NehasqGitHub

      Thanks for your reply. I understand your point. So, are you saying that, for example, in my case, where I have 21 scores (precision, recall, etc.), I should simply add all the precision values together and divide the sum by 21 to get the final precision of the model? Is that correct?

      Also, in y case of 20 images( training) and 1 images for test, what batch size would you suggest?

    3. Glenn JocherUltralytics

      Yes, to calculate the final precision (or any metric), you average the values across all splits, i.e., sum all precision scores and divide by the number of splits (21 in your case). As for the batch size, given your small dataset, you could keep it low (e.g., 1 or 2) to ensure efficient utilization of the data while avoiding overfitting.

    4. NehasqGitHub

      Thanks, that really helps! With a batch size of 1, I am keeping the epochs at 10. Should it be fewer? Also, to check for overfitting, I need to review the result graphs for each split. However, I can't definitively determine if it is overfitting since each split is separate, right?

    5. Glenn JocherUltralytics

      Keeping epochs at 10 with a batch size of 1 is reasonable given your small dataset size. To check for overfitting, reviewing result graphs from each split can help, but overfitting may be harder to detect since each split involves different training and test data. Consider comparing trends across splits for consistent insights. For further details, you can reference the K-Fold Cross Validation guide.

  3. semyon-v-dotGitHub

    After the loop:

    for ext in supported_extensions:
        images.extend(sorted((dataset_path / "images").rglob(f"*{ext}")))

    Should be this line of code: images = sorted(images)

    For images matching with labels list: labels = sorted(dataset_path.rglob("*labels/*.txt"))

    Otherwise the script creates background images because some images missing their labels.

    1. Glenn JocherUltralytics

      @semyon-v-dot thank you for your suggestion. Sorting the images list after extending it with supported extensions is a good practice to ensure alignment with the labels list. This helps prevent issues with missing labels.

      1
  4. sangeun jo

    K-폴드 데이터 세트 분할 4번에서 images.extend(sorted((dataset_path / "images").rglob(f"*{ext}"))) 이 코드를 images.extend(sorted(dataset_path.rglob(f"*images/*{ext}"))) 로 변환해야 작동했습니다.

    1. Glenn JocherUltralytics

      @sangeun-jo thank you for pointing that out. Your modification to images.extend(sorted(dataset_path.rglob(f"*images/*{ext}"))) is indeed correct and ensures the code works as intended. If you have any further questions or need additional assistance, feel free to ask!

  5. kh-diabGitHub

    is it usefult to use this k fold approach when I just have one class only but my issue is the class is detected as background or vice versa as per the attached Confusion matrix

    1. Glenn JocherUltralytics

      @kh-diab using K-Fold Cross Validation can still be beneficial even with a single class. It helps ensure that your model's performance is robust and not overly dependent on a particular subset of the data. This can be particularly useful if you're experiencing issues with class detection accuracy, as it allows you to validate the model's performance across multiple splits and identify any inconsistencies. If your class is being detected as background or vice versa, K-Fold Cross Validation can help diagnose whether this issue is consistent across different data splits or specific to certain subsets. For more details, you can refer to our guide on K-Fold Cross Validation: https://docs.ultralytics.com/guides/kfold-cross-validation/.

  6. alexander-sonyGitHub

    Good guide, consider adding it in a colab notebook.

    In section "Train YOLO using K-Fold Data Splits", model should be re-initialized foe every k, i.e. it should be inside the for-loop: for k in range(ksplit).

    1. Glenn JocherUltralytics

      @alexander-sony thank you for your feedback and suggestion! 😊

      You're absolutely right about re-initializing the model within the loop for each fold to ensure a fresh start for every training iteration. This can help avoid any potential carryover effects from previous folds. Here's the corrected code snippet for the training section:

      from ultralytics import YOLO
      
      weights_path = "path/to/weights.pt"
      results = {}
      
      # Define your additional arguments here
      batch = 16
      project = "kfold_demo"
      epochs = 100
      
      for k in range(ksplit):
          model = YOLO(weights_path, task="detect")  # Re-initialize the model inside the loop
          dataset_yaml = ds_yamls[k]
          model.train(data=dataset_yaml, epochs=epochs, batch=batch, project=project)  # include any train arguments
          results[k] = model.metrics  # save output metrics for further analysis

      Regarding your suggestion to add this guide to a Colab notebook, that's a fantastic idea! It would make the process more interactive and accessible for users. We'll consider creating a Colab version of this guide in the future.

      For more details on K-Fold Cross Validation, you can refer to our comprehensive guide.

      Thanks again for your valuable input! If you have any more suggestions or questions, feel free to share. Happy coding! 🚀

    1. Paula DerrengerUltralytics

      Yes, you can implement Stratified K-Fold Cross Validation with YOLOv8! Stratified K-Fold ensures that each fold has a similar distribution of class labels, which can be particularly useful for imbalanced datasets.

      To achieve this, you can use StratifiedKFold from sklearn.model_selection instead of KFold. Here's a brief example of how to modify the K-Fold implementation:

      from sklearn.model_selection import StratifiedKFold
      
      # Assuming labels_df is your DataFrame with class counts
      ksplit = 5
      skf = StratifiedKFold(n_splits=ksplit, shuffle=True, random_state=20)
      
      # Generate stratified splits
      kfolds = list(skf.split(labels_df, labels_df.idxmax(axis=1)))
      
      # The rest of the process remains the same

      For a detailed guide on K-Fold Cross Validation, please refer to the Ultralytics documentation. If you have any more questions, feel free to ask! 😊

      1