콘텐츠로 건너뛰기

K-폴드 교차 검증을 통한 Ultralytics

소개

This comprehensive guide illustrates the implementation of K-Fold Cross Validation for object detection datasets within the Ultralytics ecosystem. We'll leverage the YOLO detection format and key Python libraries such as sklearn, pandas, and PyYaml to guide you through the necessary setup, the process of generating feature vectors, and the execution of a K-Fold dataset split.

K-폴드 크로스 검증 개요

Whether your project involves the Fruit Detection dataset or a custom data source, this tutorial aims to help you comprehend and apply K-Fold Cross Validation to bolster the reliability and robustness of your machine learning models. While we're applying k=5 접기를 사용했지만, 최적의 접기 수는 데이터 세트와 프로젝트의 특성에 따라 달라질 수 있다는 점을 기억하세요.

더 이상 고민할 필요 없이 바로 시작하겠습니다!

설정

  • 주석은 YOLO 감지 형식으로 작성해야 합니다.

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

  • 데모에서는 과일 감지 데이터 세트를 사용합니다.

    • 이 데이터 세트에는 총 8479개의 이미지가 포함되어 있습니다.
    • 여기에는 6개의 클래스 레이블이 포함되며, 각 레이블의 총 인스턴스 수는 아래에 나열되어 있습니다.
클래스 레이블인스턴스 수
Apple7049
포도7202
파인애플1613
오렌지15549
바나나3536
수박1976
  • 필요한 Python 패키지가 포함됩니다:

    • ultralytics
    • sklearn
    • pandas
    • pyyaml
  • 이 튜토리얼은 다음에서 작동합니다. k=5 접습니다. 그러나 특정 데이터 집합에 가장 적합한 접기 수를 결정해야 합니다.

  • 새로운 Python 가상 환경(venv)를 프로젝트에 추가하고 활성화합니다. 사용 pip (또는 선호하는 패키지 관리자)를 클릭하여 설치합니다:

    • Ultralytics 라이브러리: pip install -U ultralytics. 또는 공식 repo.
    • Scikit-learn, 판다, PyYAML: pip install -U scikit-learn pandas pyyaml.
  • 주석이 YOLO 감지 형식인지 확인합니다.

    • 이 튜토리얼의 경우 모든 주석 파일은 Fruit-Detection/labels 디렉터리로 이동합니다.

객체 감지 데이터세트를 위한 특징 벡터 생성하기

  1. 먼저 새 example.py Python 파일로 이동하여 아래 단계를 수행하세요.

  2. 데이터 세트에 대한 모든 라벨 파일을 검색합니다.

    from pathlib import Path
    
    dataset_path = Path("./Fruit-detection")  # replace with 'path/to/dataset' for your custom data
    labels = sorted(dataset_path.rglob("*labels/*.txt"))  # all data in 'labels'
    
  3. 이제 데이터 세트 YAML 파일의 내용을 읽고 클래스 레이블의 인덱스를 추출합니다.

    yaml_file = "path/to/data.yaml"  # your data YAML with data directories and names dictionary
    with open(yaml_file, "r", encoding="utf8") as y:
        classes = yaml.safe_load(y)["names"]
    cls_idx = sorted(classes.keys())
    
  4. 비어 있는 pandas DataFrame.

    import pandas as pd
    
    indx = [label.stem for label in labels]  # uses base filename as ID (no extension)
    labels_df = pd.DataFrame([], columns=cls_idx, index=indx)
    
  5. 주석 파일에 있는 각 클래스 레이블의 인스턴스를 계산합니다.

    from collections import Counter
    
    for label in labels:
        lbl_counter = Counter()
    
        with open(label, "r") as lf:
            lines = lf.readlines()
    
        for line in lines:
            # classes for YOLO label uses integer at first position of each line
            lbl_counter[int(line.split(" ")[0])] += 1
    
        labels_df.loc[label.stem] = lbl_counter
    
    labels_df = labels_df.fillna(0.0)  # replace `nan` values with `0.0`
    
  6. 다음은 채워진 데이터프레임의 샘플 보기입니다:

                                                           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
    

행은 각각 데이터 세트의 이미지에 해당하는 라벨 파일의 색인을 생성하고 열은 클래스 라벨 인덱스에 해당합니다. 각 행은 데이터 세트에 존재하는 각 클래스 라벨의 개수가 포함된 의사 특징 벡터를 나타냅니다. 이 데이터 구조를 사용하면 객체 감지 데이터 세트에 K-Fold 교차 검증을 적용할 수 있습니다.

K-폴드 데이터 세트 분할

  1. 이제 우리는 KFold 클래스에서 sklearn.model_selection 를 생성하려면 k 데이터 집합을 분할합니다.

    • 중요:
      • 설정 shuffle=True 를 사용하면 스플릿에 클래스를 무작위로 분배할 수 있습니다.
      • 설정으로 random_state=M 어디 M 를 정수로 선택하면 반복 가능한 결과를 얻을 수 있습니다.
    from sklearn.model_selection import KFold
    
    ksplit = 5
    kf = KFold(n_splits=ksplit, shuffle=True, random_state=20)  # setting random_state for repeatable results
    
    kfolds = list(kf.split(labels_df))
    
  2. 이제 데이터 세트가 다음과 같이 분할되었습니다. k 폴드에는 각각 train 그리고 val 인덱스. 이러한 결과를 보다 명확하게 표시하기 위해 데이터 프레임을 구성합니다.

    folds = [f"split_{n}" for n in range(1, ksplit + 1)]
    folds_df = pd.DataFrame(index=indx, columns=folds)
    
    for idx, (train, val) in enumerate(kfolds, start=1):
        folds_df[f"split_{idx}"].loc[labels_df.iloc[train].index] = "train"
        folds_df[f"split_{idx}"].loc[labels_df.iloc[val].index] = "val"
    
  3. 이제 각 폴드에 대한 클래스 레이블의 분포를 다음에 존재하는 클래스의 비율로 계산합니다. 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 파일을 생성합니다.

    import datetime
    
    supported_extensions = [".jpg", ".jpeg", ".png"]
    
    # Initialize an empty list to store image file paths
    images = []
    
    # Loop through supported extensions and gather image files
    for ext in supported_extensions:
        images.extend(sorted((dataset_path / "images").rglob(f"*{ext}")))
    
    # Create the necessary directories and dataset YAML files (unchanged)
    save_path = Path(dataset_path / f"{datetime.date.today().isoformat()}_{ksplit}-Fold_Cross-val")
    save_path.mkdir(parents=True, exist_ok=True)
    ds_yamls = []
    
    for split in folds_df.columns:
        # Create directories
        split_dir = save_path / split
        split_dir.mkdir(parents=True, exist_ok=True)
        (split_dir / "train" / "images").mkdir(parents=True, exist_ok=True)
        (split_dir / "train" / "labels").mkdir(parents=True, exist_ok=True)
        (split_dir / "val" / "images").mkdir(parents=True, exist_ok=True)
        (split_dir / "val" / "labels").mkdir(parents=True, exist_ok=True)
    
        # Create dataset YAML files
        dataset_yaml = split_dir / f"{split}_dataset.yaml"
        ds_yamls.append(dataset_yaml)
    
        with open(dataset_yaml, "w") as ds_y:
            yaml.safe_dump(
                {
                    "path": split_dir.as_posix(),
                    "train": "train",
                    "val": "val",
                    "names": classes,
                },
                ds_y,
            )
    
  5. 마지막으로 이미지와 레이블을 각 분할의 해당 디렉토리('train' 또는 'val')에 복사합니다.

    • 참고: 이 코드 부분에 필요한 시간은 데이터 세트의 크기와 시스템 하드웨어에 따라 달라집니다.
    import shutil
    
    for image, label in zip(images, labels):
        for split, k_split in folds_df.loc[image.stem].items():
            # Destination directory
            img_to_path = save_path / split / k_split / "images"
            lbl_to_path = save_path / split / k_split / "labels"
    
            # Copy image and label files to new directory (SamefileError if file already exists)
            shutil.copy(image, img_to_path / image.name)
            shutil.copy(label, lbl_to_path / label.name)
    

기록 저장(선택 사항)

선택 사항으로 K-Fold 분할 및 라벨 배포 데이터프레임의 레코드를 나중에 참조할 수 있도록 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"
    model = YOLO(weights_path, task="detect")
    
  2. 그런 다음 데이터 세트 YAML 파일을 반복하여 학습을 실행합니다. 결과는 지정된 디렉터리에 저장됩니다. project 그리고 name 인수를 사용할 수 있습니다. 기본적으로 이 디렉터리는 'exp/runs#'이며, 여기서 #은 정수 인덱스입니다.

    results = {}
    
    # Define your additional arguments here
    batch = 16
    project = "kfold_demo"
    epochs = 100
    
    for k in range(ksplit):
        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
    

결론

이 가이드에서는 YOLO 객체 감지 모델을 훈련하기 위해 K-Fold 교차 검증을 사용하는 프로세스를 살펴봤습니다. 데이터 세트를 K개의 파티션으로 분할하여 여러 폴드에 걸쳐 균형 잡힌 클래스 분포를 보장하는 방법을 배웠습니다.

또한 데이터 분할과 이러한 분할에 대한 레이블 분포를 시각화하기 위해 보고서 데이터프레임을 만드는 절차를 살펴봄으로써 학습 및 검증 세트의 구조에 대한 명확한 인사이트를 얻을 수 있었습니다.

선택 사항으로 나중에 참조할 수 있도록 기록을 저장했는데, 이는 대규모 프로젝트나 모델 성능 문제를 해결할 때 특히 유용할 수 있습니다.

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

이 K-Fold 교차 검증 기술은 사용 가능한 데이터를 최대한 활용하는 강력한 방법이며, 다양한 데이터 하위 집합에서 모델 성능을 신뢰할 수 있고 일관성 있게 유지하는 데 도움이 됩니다. 그 결과 특정 데이터 패턴에 과도하게 맞출 가능성이 적은 보다 일반화 가능하고 신뢰할 수 있는 모델을 만들 수 있습니다.

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

자주 묻는 질문

K-Fold 교차 검증이란 무엇이며 객체 감지에 유용한 이유는 무엇인가요?

K-Fold Cross Validation is a technique where the dataset is divided into 'k' subsets (folds) to evaluate model performance more reliably. Each fold serves as both training and validation data. In the context of object detection, using K-Fold Cross Validation helps to ensure your Ultralytics YOLO model's performance is robust and generalizable across different data splits, enhancing its reliability. For detailed instructions on setting up K-Fold Cross Validation with Ultralytics YOLO, refer to K-Fold Cross Validation with Ultralytics.

Ultralytics YOLO 을 사용하여 K-Fold 교차 유효성 검사를 구현하려면 어떻게 해야 하나요?

K-Fold 교차 유효성 검사를 구현하려면 Ultralytics YOLO , 다음 단계를 따라야 합니다:

  1. 주석이 YOLO 감지 형식인지 확인합니다.
  2. 다음과 같은 Python 라이브러리 사용 sklearn, pandaspyyaml.
  3. 데이터 세트에서 특징 벡터를 생성합니다.
  4. 다음을 사용하여 데이터 집합을 분할합니다. KFold 에서 sklearn.model_selection.
  5. 각 분할에 대해 YOLO 모델을 학습시킵니다.

종합적인 가이드는 문서에서 K-Fold 데이터세트 분할 섹션을 참조하세요.

물체 감지에 Ultralytics YOLO 을 사용해야 하는 이유는 무엇인가요?

Ultralytics YOLO offers state-of-the-art, real-time object detection with high accuracy and efficiency. It's versatile, supporting multiple computer vision tasks such as detection, segmentation, and classification. Additionally, it integrates seamlessly with tools like Ultralytics HUB for no-code model training and deployment. For more details, explore the benefits and features on our Ultralytics YOLO page.

내 주석이 Ultralytics YOLO 에 올바른 형식인지 확인하려면 어떻게 해야 하나요?

Your annotations should follow the YOLO detection format. Each annotation file must list the object class, alongside its bounding box coordinates in the image. The YOLO format ensures streamlined and standardized data processing for training object detection models. For more information on proper annotation formatting, visit the YOLO detection format guide.

과일 감지 이외의 사용자 지정 데이터 세트에 K-Fold 교차 검증을 사용할 수 있나요?

예, 주석이 YOLO 감지 형식인 경우 모든 사용자 지정 데이터 세트에 K-Fold 교차 유효성 검사를 사용할 수 있습니다. 데이터 세트 경로와 클래스 레이블을 사용자 정의 데이터 세트에 맞는 것으로 바꾸면 됩니다. 이러한 유연성 덕분에 모든 객체 감지 프로젝트에서 K-Fold 교차 검증을 사용한 강력한 모델 평가의 이점을 누릴 수 있습니다. 실제 예시를 보려면 특징 벡터 생성하기 섹션을 참조하세요.

📅 Created 11 months ago ✏️ Updated 29 days ago

댓글