"""Subgroup robustness analysis (P10, Table 5 part 2). Evaluates any model's saved OOF predictions sliced by demographic subgroup: age bands (60-69, 70-79, 80+) and sex. Tests whether a model's performance is stable across groups or driven by an age->label correlation. Consumes the per-subject OOF prediction CSVs written by eval/runner.py (columns: subject_id, seed, fold, y_true, y_pred, prob_0, prob_1, prob_2) joined to the cohort table for age/sex, so no re-training is needed. """ from __future__ import annotations from pathlib import Path import numpy as np import pandas as pd from trifuse.eval.metrics import compute_metrics AGE_BANDS = [("60-69", 60, 70), ("70-79", 70, 80), ("80+", 80, 200)] def _band(age: float) -> str: for name, lo, hi in AGE_BANDS: if lo <= age < hi: return name return "other" def subgroup_table(oof_csv: str | Path, subjects_csv: str | Path) -> pd.DataFrame: """Return per-subgroup metrics (pooled over all seeds/folds) for one model.""" oof = pd.read_csv(oof_csv) sub = pd.read_csv(subjects_csv)[["subject_id", "age", "sex"]] df = oof.merge(sub, on="subject_id", how="left") df["age_band"] = df["age"].apply(_band) df["sex_str"] = df["sex"].map({0: "Male", 1: "Female"}).fillna("Unknown") prob_cols = ["prob_0", "prob_1", "prob_2"] def _row(name: str, sl: pd.DataFrame) -> dict: if len(sl) == 0: return {"subgroup": name, "n": 0} m = compute_metrics(sl["y_true"].to_numpy(), sl["y_pred"].to_numpy(), sl[prob_cols].to_numpy()) return {"subgroup": name, "n": int(sl["subject_id"].nunique()), "macro_f1": m["macro_f1"], "balanced_accuracy": m["balanced_accuracy"], "ad_recall": m["recall_AD"]} rows = [_row("Overall", df)] for name, _, _ in AGE_BANDS: rows.append(_row(name, df[df["age_band"] == name])) for sx in ["Male", "Female"]: rows.append(_row(sx, df[df["sex_str"] == sx])) return pd.DataFrame(rows) def run_subgroup(oof_csvs: dict[str, str | Path], subjects_csv: str | Path, out_dir: str | Path) -> pd.DataFrame: """oof_csvs: {model_name: path}. Builds a combined subgroup table across models.""" out_dir = Path(out_dir); out_dir.mkdir(parents=True, exist_ok=True) frames = [] for name, path in oof_csvs.items(): t = subgroup_table(path, subjects_csv) t.insert(0, "model", name) frames.append(t) res = pd.concat(frames, ignore_index=True) res.to_csv(out_dir / "subgroup_summary.csv", index=False) return res if __name__ == "__main__": import sys, glob subj = sys.argv[1] if len(sys.argv) > 1 else "data/metadata/subjects_clean.csv" oof_dir = sys.argv[2] if len(sys.argv) > 2 else "results/oof" csvs = {Path(p).stem.replace("oof_", ""): p for p in glob.glob(f"{oof_dir}/oof_*.csv")} print(run_subgroup(csvs, subj, "results/tables/subgroup").to_string(index=False))