"""Rank-average ensembles over every saved per-sample prediction. The published LNPBench-Stack has four members. This script sweeps larger member sets over the *same* saved predictions, so the comparison costs no retraining and no new evaluation data. PYTHONPATH=src python scripts/stack_big.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 PATTERN = re.compile(r"(?P.+?)__(?P.+?)__s(?P\d+)\.npz$") EXTERNAL = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$") # candidate stacks, all fixed a priori (no weight is fitted on any evaluation data) STACKS = { "published_4": ["physchem_tree", "physset_phys", "randomforest", "extratrees"], "published_3": ["physset_phys", "randomforest", "extratrees"], "trees6": ["physchem_tree", "randomforest", "extratrees", "xgboost", "catboost", "lightgbm"], "neural4": ["physset_phys", "relmode_nr_w", "physmode_chem", "lion"], "all11": ["physchem_tree", "physset_phys", "relmode_nr_w", "physmode_chem", "randomforest", "extratrees", "xgboost", "lion", "agile", "probe_flat_rank", "phcausal_phys"], "best6": ["physchem_tree", "physset_phys", "relmode_nr_w", "randomforest", "extratrees", "lion"], "best4": ["physchem_tree", "physset_phys", "relmode_nr_w", "randomforest"], } def rank_norm(x: np.ndarray) -> np.ndarray: return stats.rankdata(x, method="average") / len(x) - 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 or not EXTERNAL.match(m["task"]): continue z = np.load(f) table[(m["model"], m["task"])][int(m["seed"])] = (z["y"], z["pred"]) return table def main(): ap = argparse.ArgumentParser() ap.add_argument("--pred-dirs", nargs="+", default=["results/predictions", "results/predictions_new"]) ap.add_argument("--out", default="results/stack_big.csv") args = ap.parse_args() table = load(args.pred_dirs) models = sorted({m for m, _ in table}) print("available models:", models) tasks = sorted({t for _, t in table}) # per-model: rank-normalise each seed, average over seeds per_model: dict[str, dict[str, tuple[np.ndarray, np.ndarray]]] = defaultdict(dict) for model in models: for task in tasks: seeds = table.get((model, task), {}) if not seeds: continue ys, ps = [], [] for _, (y, p) in sorted(seeds.items()): ys.append(y) ps.append(rank_norm(np.asarray(p, dtype=np.float64))) per_model[model][task] = (ys[0], np.mean(ps, axis=0)) rows = [] for sname, members in STACKS.items(): avail = [m for m in members if m in per_model] if len(avail) < len(members): print(f"[skip] {sname}: missing {set(members) - set(avail)}") for task in tasks: parts = [per_model[m][task] for m in avail if task in per_model[m]] if len(parts) < 2: continue y = parts[0][0] if any(not np.array_equal(p[0], y) for p in parts[1:]): continue pred = np.mean([p[1] for p in parts], axis=0) rho = stats.spearmanr(y, pred).statistic rows.append({"stack": sname, "members": len(parts), "task": task, "spearman": rho}) df = pd.DataFrame(rows) df.to_csv(args.out, index=False) print("\n== 20-task mean ==") print(df.groupby(["stack", "members"]).spearman.agg(["size", "mean"]).round(4).to_string()) # single-model references on the same protocol print("\n== single models ==") single = [] for model, tasks_d in per_model.items(): rhos = [stats.spearmanr(y, p).statistic for y, p in tasks_d.values()] if len(rhos) >= 20: single.append((model, len(rhos), float(np.mean(rhos)))) for m, n, r in sorted(single, key=lambda x: -x[2]): print(f"{m:20s} n={n:3d} rho={r:.4f}") if __name__ == "__main__": main()