← 문제 목록/Stratified Train-Test Split [medium]
문제 해설

Stratified Train-Test Split [medium]

데이터 분할 · medium

preview

Stratified Train-Test Split [medium]

v1 분할 은 전체를 섞어 자르기만 함 → 클래스 불균형 (imbalanced) 데이터면 test 에 아예 양성이 없는 사고 발생 가능.

Stratified split: 각 클래스 내부에서 따로 섞어 분할 → train 과 test 의 클래스 비율이 원본과 동일 하게 유지.

알고리즘

for c in 고유 클래스들:
    해당 클래스 인덱스를 섞는다
    n_test_c = round(len(class_c) * test_ratio)   # 각 클래스에서 비율만큼
    test_idx 에 class_c[:n_test_c] 추가
    train_idx 에 class_c[n_test_c:] 추가
train/test 각각 다시 한 번 섞어 순서 무작위화 (optional, 재현성)

왜 중요한가

  • 희귀 클래스: 양성 5% 데이터에서 일반 split 을 하면 test 에 양성이 0개 나올 확률이 실제로 있음.
  • 교차 검증: 모든 fold 의 클래스 분포가 같아야 평가가 안정.
  • sklearn.model_selection.train_test_split(stratify=y) 가 바로 이것.

과제

함수 stratified_split(X, y, test_ratio, seed) 를 완성하세요.

  • X shape (N, D), y shape (N,) 정수 레이블.
  • 반환: (X_train, X_test, y_train, y_test).
  • 각 클래스에서 round(count_c * test_ratio) 개를 test 로.
  • rng = np.random.default_rng(seed) 한 번만 만들고 전체 과정에 사용.
  • 힌트: np.unique(y) 로 클래스 모으고, 클래스별 rng.permutation 후 슬라이스.

테스트 케이스

#이름검증
1반환 4-tuple
2클래스 비율 보존 (train, test 둘 다)
3시드 재현성
4train + test 합 = 원본 (셔플 보존)
5희귀 클래스도 test 에 포함5% 클래스 → 0 아닌 개수
6test 개수 ≈ N·test_ratio (±1·클래스 수)
7X 와 y 인덱스 일관성
코드 작성
Loading...
실행 결과

코드를 작성하고 Run 을 눌러보세요.