File size: 4,449 Bytes
530fba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
"""Honest leave-one-study-out estimate of ensemble member selection.

`stack_big.py` reports a `best6` stack whose members were chosen after seeing
the results. This script prices that choice: for each held-out study S, the
member set is selected by greedy forward search on the *other three studies
only*, then evaluated on S. The mean over the four rotations is the honest
estimate of a selection protocol that does not touch the evaluation study.

    PYTHONPATH=src python scripts/stack_loso.py
"""

from __future__ import annotations

import argparse
import re
from collections import defaultdict
from pathlib import Path

import numpy as np
import pandas as pd
from scipy import stats
from scipy.stats import spearmanr

PATTERN = re.compile(r"(?P<model>.+?)__(?P<task>.+?)__s(?P<seed>\d+)\.npz$")
EXTERNAL = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$")
STUDIES = ("LM_2019", "BL_2023", "SL_2020", "ZC_2023")

CANDIDATES = ["physchem_tree", "physset_phys", "relmode_nr_w", "physmode_chem",
              "randomforest", "extratrees", "xgboost", "lion", "agile",
              "probe_flat_rank", "phcausal_phys"]


def rank_norm(x: np.ndarray) -> np.ndarray:
    return stats.rankdata(x, method="average") / len(x) - 0.5


def load(pred_dir: Path, members: list[str]) -> dict:
    table: dict = defaultdict(dict)
    for f in sorted(Path(pred_dir).glob("*.npz")):
        m = PATTERN.match(f.name)
        if not m or not EXTERNAL.match(m["task"]) or m["model"] not in members:
            continue
        z = np.load(f)
        table[(m["model"], m["task"])][int(m["seed"])] = (z["y"], z["pred"])
    return table


def member_task_pred(table, mem, task):
    seeds = table.get((mem, task))
    if not seeds:
        return None
    return np.mean([rank_norm(p) for _, p in seeds.values()], axis=0)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--pred-dir", default="results/predictions")
    ap.add_argument("--max-members", type=int, default=8)
    ap.add_argument("--out", default="results/stack_loso.csv")
    args = ap.parse_args()

    table = load(Path(args.pred_dir), CANDIDATES)
    tasks = sorted({task for (_, task) in table})
    by_study = {s: [t for t in tasks if t.startswith(s)] for s in STUDIES}
    by_study = {s: ts for s, ts in by_study.items() if ts}

    # per-member per-task Spearman (seed-averaged predictions)
    rho = {}
    for mem in CANDIDATES:
        for task in tasks:
            pred = member_task_pred(table, mem, task)
            if pred is None:
                continue
            y = table[(mem, task)][0][0]
            rho[(mem, task)] = spearmanr(y, pred).statistic

    def ens_rho(members, task):
        cols = [member_task_pred(table, m, task) for m in members]
        cols = [c for c in cols if c is not None]
        if len(cols) < 2:
            return float("nan")
        y = table[(members[0], task)][0][0]
        return spearmanr(y, np.mean(cols, axis=0)).statistic

    rows = []
    for held in STUDIES:
        train_studies = [s for s in STUDIES if s != held and by_study.get(s)]
        train_tasks = [t for s in train_studies for t in by_study[s]]
        held_tasks = by_study[held]
        # greedy forward selection on the three training studies
        selected = []
        best_train = -1.0
        while len(selected) < args.max_members:
            cand = [m for m in CANDIDATES if m not in selected]
            scored = []
            for m in cand:
                vals = [ens_rho(selected + [m], t) for t in train_tasks]
                scored.append((np.nanmean(vals), m))
            scored.sort(reverse=True)
            if not scored or scored[0][0] <= best_train + 1e-6:
                break
            best_train, member = scored[0]
            selected.append(member)
        held_vals = [ens_rho(selected, t) for t in held_tasks]
        rows.append({"held_out": held, "n_members": len(selected),
                     "members": ",".join(selected),
                     "train_mean": best_train,
                     "held_mean": float(np.nanmean(held_vals))})
        print(f"held-out {held}: {len(selected)} members, train {best_train:.4f}, "
              f"held {np.nanmean(held_vals):.4f}", flush=True)

    df = pd.DataFrame(rows)
    df.to_csv(args.out, index=False)
    print(f"\nhonest LOSO estimate: {df['held_mean'].mean():.4f}")
    print("wrote", args.out)


if __name__ == "__main__":
    main()