File size: 8,422 Bytes
c4e317f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68d3a65
 
c4e317f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
68d3a65
 
c4e317f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""Ensemble and multi-seed analysis over saved per-sample predictions.

Three questions are answered here, all from the same stored predictions:

1. **Seed averaging.**  Neural models vary by ~0.03-0.05 Spearman between random
   seeds, so a single-seed comparison can reverse the ranking of two models.
   Every model is first averaged over the seeds it has (rank-normalised
   predictions, equal weight) and only then compared.
2. **Cross-family ensembling.**  A random forest is an average of 400 trees;
   comparing it with one neural network is not like-for-like.  Ensembles below
   are built *identically* for every family, so the comparison stays symmetric.
3. **The final LNPBench-Stack.**  A three-member, equal-weight, rank-normalised
   average of PhysSet-LNP and the two tree ensembles.  The member list is fixed
   a priori (one model per family: physics-informed neural, bagged trees,
   randomised trees) and no weight is fitted on any evaluation data, so the
   stack has no more freedom than a single model.

Usage::

    python scripts/ensemble.py --pred-dirs results_gpu/pred_gpu results_gpu/pred_cpu \
        --out results/ensemble.csv
"""

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

# Pre-registered group definitions (member lists are fixed, never tuned on the
# held-out studies).
GROUPS = {
    "trees": ["randomforest", "extratrees", "xgboost"],
    "neural baselines": ["lion", "agile", "mlp_fp"],
    "proposed": ["physset_phys", "phcausal_phys", "seqcausal"],
    "LNPBench-Stack": ["physset_phys", "randomforest", "extratrees"],
    # leave-one-out members, used only to attribute the stack's gain
    "Stack w/o PhysSet-LNP": ["randomforest", "extratrees"],
    "Stack w/o random forest": ["physset_phys", "extratrees"],
    "Stack w/o extra trees": ["physset_phys", "randomforest"],
    # reference upper bounds, not the declared model
    "stack+lgbm": ["physset_phys", "randomforest", "extratrees", "xgboost"],
    "stack+mpnn": ["physset_phys", "randomforest", "extratrees", "agile", "lion"],
    "all": ["randomforest", "extratrees", "xgboost", "lion", "agile", "mlp_fp",
            "physset_phys", "phcausal_phys"],
}

PATTERN = re.compile(r"(?P<model>.+?)__(?P<task>.+?)__s(?P<seed>\d+)\.npz$")
# only the external protocol (4 held-out studies x 5 folds) enters the ensemble
EXTERNAL_TASK = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$")


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


def load(pred_dirs) -> dict:
    table: dict = defaultdict(dict)
    for d in pred_dirs:
        p = Path(d)
        if not p.exists():
            continue
        for f in sorted(p.glob("*.npz")):
            m = PATTERN.match(f.name)
            if not m:
                continue
            if not EXTERNAL_TASK.match(m["task"]):
                continue
            z = np.load(f)
            table[(m["model"], m["task"])][int(m["seed"])] = (z["y"], z["pred"])
    return table


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--pred-dirs", nargs="+",
                    default=["results_gpu/pred_gpu", "results_gpu/pred_cpu"])
    ap.add_argument("--out", default="results/ensemble.csv")
    args = ap.parse_args()

    table = load(args.pred_dirs)
    if not table:
        print("no predictions found")
        return

    # ---- average over seeds, per (model, task) ---------------------------
    averaged: dict = {}
    seed_counts: dict = defaultdict(set)
    for (model, task), per_seed in table.items():
        y_ref = None
        stack = []
        for seed, (y, pred) in sorted(per_seed.items()):
            y_ref = y
            stack.append(rank_normalise(pred))
            seed_counts[model].add(seed)
        averaged[(model, task)] = (y_ref, np.vstack(stack).mean(0))

    tasks = sorted({t for (_, t) in averaged})
    models = sorted({m for (m, _) in averaged})

    rows = []
    for task in tasks:
        present = {m: averaged[(m, task)] for m in models if (m, task) in averaged}
        y_ref = next(iter(present.values()))[0]
        for m, (y, pred) in present.items():
            rows.append({"group": f"single:{m}", "task": task, "n_models": 1,
                         "n_seeds": len(seed_counts[m]),
                         "spearman": float(stats.spearmanr(y, pred).statistic)})
        for gname, glist in GROUPS.items():
            avail = [m for m in glist if m in present]
            if len(avail) < 2:
                continue
            stack = np.vstack([present[m][1] for m in avail]).mean(0)
            rows.append({"group": gname, "task": task, "n_models": len(avail),
                         "n_seeds": int(min(len(seed_counts[m]) for m in avail)),
                         "spearman": float(stats.spearmanr(y_ref, stack).statistic)})

    df = pd.DataFrame(rows)
    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    df.to_csv(out, index=False)

    sing = df[df.group.str.startswith("single:")].copy()
    sing["model"] = sing.group.str.replace("single:", "", regex=False)
    tab = (sing.groupby("model")
           .agg(tasks=("spearman", "size"), seeds=("n_seeds", "max"),
                spearman=("spearman", "mean"), sd=("spearman", "std"))
           .round(3).sort_values("spearman", ascending=False))
    print("=== single models, seed-averaged, all 20 external tasks ===")
    print(tab.to_string())

    ens = (df[~df.group.str.startswith("single:")]
           .groupby("group").spearman.agg(["size", "mean", "std"]).round(3)
           .sort_values("mean", ascending=False))
    print("\n=== ensembles (equal-weight, rank-normalised) ===")
    print(ens.to_string())

    piv = df.copy()
    piv["study"] = piv.task.str.extract(r"^([A-Z]{2}_\d{4})")[0]
    print("\n=== per held-out study (seed-averaged) ===")
    print(piv.pivot_table(index="group", columns="study", values="spearman",
                          aggfunc="mean").round(3).to_string())

    # ---- paired tests between named models ------------------------------
    wide = sing.pivot_table(index="task", columns="model", values="spearman")
    pairs = [("physset_phys", "agile"), ("physset_phys", "lion"),
             ("physset_phys", "randomforest"), ("physset_phys", "extratrees"),
             ("physset_phys", "xgboost"), ("agile", "randomforest"),
             ("lion", "randomforest")]
    print("\n=== paired Wilcoxon on the 20 shared tasks ===")
    for a, b in pairs:
        if a in wide.columns and b in wide.columns:
            sub = wide[[a, b]].dropna()
            if len(sub) < 5:
                continue
            stat, p = stats.wilcoxon(sub[a], sub[b])
            print(f"  {a:14s} vs {b:14s}  delta={sub[a].sub(sub[b]).mean():+.3f}  "
                  f"p={p:.4f}  n={len(sub)}")

    # ---- the final stack vs every single model, paired -------------------
    stack_wide = df[~df.group.str.startswith("single:")].pivot_table(
        index="task", columns="group", values="spearman")
    test_rows = []
    if "LNPBench-Stack" in stack_wide.columns:
        for m in wide.columns:
            sub = pd.concat([stack_wide["LNPBench-Stack"], wide[m]], axis=1).dropna()
            if len(sub) < 5:
                continue
            a, b = sub.iloc[:, 0], sub.iloc[:, 1]
            stat, p = stats.wilcoxon(a, b)
            test_rows.append({"model_a": "LNPBench-Stack", "model_b": m,
                              "delta": float((a - b).mean()), "p": float(p), "n": int(len(sub))})
        print("\n=== LNPBench-Stack vs each single model (paired Wilcoxon) ===")
        print(pd.DataFrame(test_rows).sort_values("p").round(4).to_string(index=False))

    # persist all paired tests
    rows_t = []
    for a, b in pairs:
        if a in wide.columns and b in wide.columns:
            sub = wide[[a, b]].dropna()
            if len(sub) < 5:
                continue
            stat, p = stats.wilcoxon(sub[a], sub[b])
            rows_t.append({"model_a": a, "model_b": b,
                           "delta": float((sub[a] - sub[b]).mean()), "p": float(p), "n": int(len(sub))})
    pd.DataFrame(rows_t + test_rows).to_csv(
        Path(args.out).with_name("paired_tests.csv"), index=False)


if __name__ == "__main__":
    main()