시작하기무료로 시작하기

Stratified K-fold

방금 본 것처럼, 무작위 분할로 인해 폴드마다 타깃 변수 분포가 꽤 다르게 나올 수 있어요. 이 대회에서는 치명적이지 않지만, 타깃 불균형이 큰 분류 대회에서는 문제가 될 수 있습니다.

이를 해결하기 위해, 타깃 변수 기준으로 계층화하는 stratified K-fold 전략을 구현해 보겠습니다. train DataFrame은 워크스페이스에 이미 준비되어 있습니다.

이 연습은 강의의 일부입니다

Python으로 Kaggle 대회 공략하기

강의 보기

연습 안내

  • 3개 폴드와 셔플링을 사용하는 StratifiedKFold 객체를 생성하세요.
  • str_kf 객체를 사용해 각 분할을 순회하세요. 계층화 기준은 "interest_level" 열입니다.
  • 각 분할마다 train_indextest_index를 사용해 학습 폴드와 테스트 폴드를 선택하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Import StratifiedKFold
from sklearn.model_selection import StratifiedKFold

# Create a StratifiedKFold object
str_kf = ____(n_splits=____, shuffle=____, random_state=123)

# Loop through each split
fold = 0
for train_index, test_index in ____.____(train, train['interest_level']):
    # Obtain training and testing folds
    cv_train, cv_test = ____.iloc[____], ____.iloc[____]
    print('Fold: {}'.format(fold))
    print('CV train shape: {}'.format(cv_train.shape))
    print('Medium interest listings in CV train: {}\n'.format(sum(cv_train.interest_level == 'medium')))
    fold += 1
코드 편집 및 실행