DAY-4 - 재현 가능한 Random Seed
오늘의 주제
- 학습 목표
난수 seed가 통제하는 범위를 이해하고 데이터 분할과 실험 결과를 반복 가능하게 만들되, seed 하나가 완전한 재현성을 보장하지 않는 이유를 설명한다.
학습 전 기반 지식
- 의사난수 생성기
일반적인 난수 함수는 내부 상태에서 결정적인 수열을 생성한다. 같은 알고리즘과 초기 seed를 사용하면 같은 수열을 얻을 수 있다. 암호학적 무작위성과 실험 반복을 위한 의사난수는 목적이 다르다.
- 전역 seed의 문제
하나의 전역 generator를 여러 함수가 공유하면 호출 순서가 바뀔 때 결과도 바뀐다. component별 generator를 만들거나 seed를 명시적으로 전달하면 숨은 결합을 줄일 수 있다.
- 데이터 분할과 leakage
같은 seed로 train/test index를 고정하면 model 비교가 공정해진다. 하지만 시간 데이터나 사용자별 중복이 있는 데이터는 무작위 분할 자체가 leakage를 만들 수 있으므로 split 전략이 seed보다 먼저다.
- Library와 hardware 비결정성
Python, NumPy, 학습 framework는 각각 난수 상태를 가질 수 있다. 병렬 연산 순서, GPU kernel, library version, floating-point 차이도 결과를 바꾼다. framework별 deterministic 설정은 성능 저하나 미지원 연산을 동반할 수 있다.
- 재현성 기록 단위
seed뿐 아니라 data version, split algorithm, row ordering, code version, dependency, hardware, deterministic flag를 함께 기록해야 차이를 설명할 수 있다.
단계별 실습
- 다음 코드를
day4_seed.py로 저장한다.
import hashlib import json import random def split_ids(ids: list[str], seed: int, test_ratio: float = 0.25): shuffled = ids.copy() rng = random.Random(seed) rng.shuffle(shuffled) test_size = max(1, round(len(shuffled) * test_ratio)) return shuffled[test_size:], shuffled[:test_size] def fingerprint(values: list[str]) -> str: payload = json.dumps(values, separators=(",", ":")).encode() return hashlib.sha256(payload).hexdigest()[:12] ids = [f"customer-{number}" for number in range(12)] train_a, test_a = split_ids(ids, seed=42) train_b, test_b = split_ids(ids, seed=42) train_c, test_c = split_ids(ids, seed=7) assert (train_a, test_a) == (train_b, test_b) assert test_a != test_c assert set(train_a).isdisjoint(test_a) assert set(train_a) | set(test_a) == set(ids) print({"seed": 42, "train_hash": fingerprint(train_a), "test_hash": fingerprint(test_a)})
- 같은 seed를 두 번 실행해 split fingerprint가 같은지 확인한다.
- 입력
ids순서를 뒤집고 같은 seed를 사용해 결과가 달라지는지 확인한다.
- split 결과 자체 또는 index Artifact를 저장해야 하는 이유를 설명한다.
- 실제 framework를 사용한다면 Python, NumPy, framework seed와 deterministic 설정을 한 함수에서 적용한다.
재현성 수준 구분
- 동일 split: 같은 sample이 train/validation/test에 배정된다.
- 동일 초기화: model parameter와 sampling 순서가 같다.
- 동일 연산 경로: deterministic kernel과 thread 설정이 같다.
- 동일 binary 결과: hardware와 library까지 고정해야 할 수 있으며 항상 현실적인 목표는 아니다.
- 통계적 재현: 여러 seed에서 평균과 분산이 유사한지 확인하는 것이 더 적절한 실험도 있다.
실패 상황과 해석
- seed만 기록: 입력 row 순서가 달라지면 같은 seed도 다른 split을 만든다. dataset fingerprint와 split Artifact를 남긴다.
- 좋은 seed 선택: 우연히 metric이 높은 seed를 고르면 과대평가다. 여러 seed의 분포를 보고한다.
- 완전 결정성을 기본 요구: 비용과 속도 영향이 있을 수 있다. 필요한 재현성 수준을 먼저 정의한다.
완료 기준
- seed가 재현성을 돕지만 보장하지 않는 이유를 설명할 수 있다.
- 같은 seed, 다른 seed, 다른 입력 순서를 비교했다.
- seed와 함께 기록할 환경·데이터 metadata 목록을 작성했다.