
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, 재현성)
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 | 시드 재현성 | |
| 4 | train + test 합 = 원본 (셔플 보존) | |
| 5 | 희귀 클래스도 test 에 포함 | 5% 클래스 → 0 아닌 개수 |
| 6 | test 개수 ≈ N·test_ratio (±1·클래스 수) | |
| 7 | X 와 y 인덱스 일관성 |
코드를 작성하고 Run 을 눌러보세요.