"""Subject-level repeated stratified cross-validation splits. Leakage prevention is the whole point: splitting happens at the subject level (one volume per subject, so no subject appears in both train and test). Stratification uses a composite key of class x age-band x sex so folds stay balanced on all three. For each of 3 seeds we build a 5-fold split (15 evaluations total). Within each outer fold, the training portion is further split 80/20 into train/val for early stopping. All fitting (impute/standardize/class-weights) must happen on the train portion only -- handled downstream, not here. """ from __future__ import annotations import numpy as np import pandas as pd from sklearn.model_selection import StratifiedKFold, train_test_split SEEDS = [7, 13, 21] N_FOLDS = 5 VAL_FRACTION = 0.2 def age_band(age: float) -> str: if age < 70: return "60s" if age < 80: return "70s" return "80+" def _strata_key(df: pd.DataFrame) -> pd.Series: bands = df["age"].apply(age_band) return df["class_id"].astype(str) + "_" + bands + "_" + df["sex"].astype(str) def _merge_rare(strata: pd.Series, min_count: int = 2) -> pd.Series: """StratifiedKFold needs every stratum to have >= n_splits members ideally; collapse ultra-rare composite strata down to the class label alone.""" counts = strata.value_counts() rare = set(counts[counts < min_count].index) return strata.map(lambda s: s.split("_")[0] if s in rare else s) def make_folds(df: pd.DataFrame) -> pd.DataFrame: """Return a long-form dataframe: one row per (subject, seed) giving fold id and the train/val/test role for the fold where the subject is in test. Output columns: subject_id, seed, fold (int, the test fold this subject belongs to). Downstream, evaluation `(seed, fold)` uses fold==test, and the remaining subjects are the train pool (val carved out per model run). """ records = [] strata_full = _merge_rare(_strata_key(df)) for seed in SEEDS: skf = StratifiedKFold(n_splits=N_FOLDS, shuffle=True, random_state=seed) fold_of = np.empty(len(df), dtype=int) for fold_idx, (_, test_idx) in enumerate(skf.split(df, strata_full)): fold_of[test_idx] = fold_idx for sid, fold in zip(df["subject_id"].to_numpy(), fold_of): records.append({"subject_id": sid, "seed": seed, "fold": int(fold)}) return pd.DataFrame.from_records(records) def split_for(folds: pd.DataFrame, df: pd.DataFrame, seed: int, fold: int): """Return (train_ids, val_ids, test_ids) for one (seed, fold) evaluation. Test = subjects whose assigned fold == `fold` for this seed. Remaining are split into train/val (stratified on class) using the same seed for reproducibility. """ fs = folds[folds["seed"] == seed] test_ids = fs.loc[fs["fold"] == fold, "subject_id"].tolist() trainval_ids = fs.loc[fs["fold"] != fold, "subject_id"].tolist() sub = df[df["subject_id"].isin(trainval_ids)] strat = sub["class_id"] train_ids, val_ids = train_test_split( sub["subject_id"].tolist(), test_size=VAL_FRACTION, random_state=seed, stratify=strat, ) return train_ids, val_ids, test_ids def assert_no_leakage(train_ids, val_ids, test_ids) -> None: s_tr, s_va, s_te = set(train_ids), set(val_ids), set(test_ids) assert not (s_tr & s_te), "train/test subject overlap" assert not (s_tr & s_va), "train/val subject overlap" assert not (s_va & s_te), "val/test subject overlap"