Download code/scripts/stack_probe.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 6.7 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/stack_probe.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/scripts/stack_probe.py
-
curl -L -o stack_probe.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/stack_probe.py
6.7 kB
| """Can the ontology block improve the final ensemble? | |
| The ontology/schema feature block did not beat the chemistry block on its own | |
| (0.368 vs 0.376 over 20 tasks), but it is the best model on the two held-out | |
| studies where everything else collapses (LM_2019, BL_2023) and the worst on the | |
| two where everything else is saturated. That is the signature of a member that | |
| is worth adding to an ensemble even though it is not worth deploying alone. | |
| This script therefore works purely on saved per-sample predictions -- no | |
| retraining -- and answers three questions: | |
| 1. What does adding one candidate member to the four-member LNPBench-Stack do? | |
| 2. Which members would a greedy forward selection pick? | |
| 3. Does that selection survive? A greedy search on the same 20 tasks it is | |
| scored on is optimistic, so the honest number is a **leave-one-study-out** | |
| protocol: the member set is chosen on three held-out studies and scored on | |
| the fourth, rotated over all four. | |
| Usage:: | |
| python scripts/stack_probe.py --pred-dir results/predictions | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| from pathlib import Path | |
| from typing import Dict, List | |
| import numpy as np | |
| import pandas as pd | |
| from scipy.stats import rankdata, spearmanr | |
| BASE_STACK = ["physchem_tree", "physset_phys", "randomforest", "extratrees"] | |
| CANDIDATES = [ | |
| "base_onto", "base_cb", "base_onto_cb", | |
| "xgboost", "agile", "lion", "phcausal_phys", "probe_flat_rank", "seqcausal", | |
| ] | |
| STUDIES = ["LM_2019", "BL_2023", "SL_2020", "ZC_2023"] | |
| def load(dirpath: Path) -> Dict[str, Dict[str, tuple]]: | |
| """model -> task -> (idx, y, rank-normalised mean prediction over seeds).""" | |
| raw: Dict[str, Dict[str, List[tuple]]] = {} | |
| for f in sorted(dirpath.glob("*.npz")): | |
| parts = f.stem.split("__") | |
| if len(parts) != 3: | |
| continue | |
| model, task, _seed = parts | |
| z = np.load(f) | |
| raw.setdefault(model, {}).setdefault(task, []).append( | |
| (z["idx"], z["y"], z["pred"].astype(np.float64)) | |
| ) | |
| out: Dict[str, Dict[str, tuple]] = {} | |
| for model, per_task in raw.items(): | |
| out[model] = {} | |
| for task, runs in per_task.items(): | |
| idx = runs[0][0] | |
| y = runs[0][1] | |
| ranks = [] | |
| for i, yy, p in runs: | |
| order = np.argsort(np.argsort(i)) | |
| p = p[order] | |
| ranks.append(rankdata(p) / max(len(p) - 1, 1)) | |
| out[model][task] = (idx, y, np.mean(ranks, axis=0)) | |
| return out | |
| def score(models: Dict[str, Dict[str, tuple]], members: List[str], | |
| tasks: List[str]) -> Dict[str, float]: | |
| """Per-task Spearman of the equal-weight rank average over ``members``.""" | |
| res = {} | |
| for t in tasks: | |
| have = [m for m in members if m in models and t in models[m]] | |
| if not have: | |
| continue | |
| vecs, y = [], None | |
| for m in have: | |
| idx, yy, p = models[m][t] | |
| vecs.append(p) | |
| y = yy | |
| pred = np.mean(vecs, axis=0) | |
| res[t] = float(spearmanr(y, pred).statistic) | |
| return res | |
| def greedy(models, pool: List[str], tasks: List[str], start: List[str], | |
| max_add: int = 4) -> List[str]: | |
| chosen = list(start) | |
| best = float(np.mean(list(score(models, chosen, tasks).values()))) | |
| for _ in range(max_add): | |
| gains = [] | |
| for c in pool: | |
| if c in chosen: | |
| continue | |
| s = float(np.mean(list(score(models, chosen + [c], tasks).values()))) | |
| gains.append((s - best, c)) | |
| if not gains: | |
| break | |
| gain, c = max(gains) | |
| if gain <= 1e-6: | |
| break | |
| chosen.append(c) | |
| best += gain | |
| return chosen | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--pred-dir", default="results/predictions") | |
| ap.add_argument("--out", default="results/stack_probe.csv") | |
| args = ap.parse_args() | |
| models = load(Path(args.pred_dir)) | |
| tasks = [t for t in sorted(models["physchem_tree"]) if t.split("_fold")[0] in STUDIES] | |
| print(f"{len(models)} models, {len(tasks)} tasks") | |
| print("available:", sorted(models)) | |
| rows = [] | |
| # ---- 1. one-at-a-time addition to the published stack ------------------- | |
| ref = score(models, BASE_STACK, tasks) | |
| ref_mean = float(np.mean(list(ref.values()))) | |
| print(f"\nBASE_STACK = {ref_mean:.4f}") | |
| rows.append({"setting": "fixed", "members": "|".join(BASE_STACK), | |
| "mean": ref_mean, "delta": 0.0}) | |
| for c in CANDIDATES: | |
| if c not in models: | |
| continue | |
| s = score(models, BASE_STACK + [c], tasks) | |
| m = float(np.mean(list(s.values()))) | |
| per_study = {st: np.mean([v for k, v in s.items() if k.startswith(st)]) for st in STUDIES} | |
| rows.append({"setting": "fixed", "members": "|".join(BASE_STACK + [c]), | |
| "mean": m, "delta": m - ref_mean, **{f"d_{k}": per_study[k] - np.mean( | |
| [v for kk, v in ref.items() if kk.startswith(k)]) for k in STUDIES}}) | |
| print(f" +{c:18s} {m:.4f} ({m - ref_mean:+.4f})") | |
| # ---- 2. greedy on all 20 tasks (optimistic) ----------------------------- | |
| pool = [c for c in CANDIDATES if c in models] | |
| chosen = greedy(models, pool, tasks, BASE_STACK) | |
| g = score(models, chosen, tasks) | |
| gm = float(np.mean(list(g.values()))) | |
| print(f"\ngreedy (in-sample, optimistic): {gm:.4f} {chosen}") | |
| rows.append({"setting": "greedy_in_sample", "members": "|".join(chosen), "mean": gm, | |
| "delta": gm - ref_mean}) | |
| # ---- 3. leave-one-study-out selection ---------------------------------- | |
| loso, base_loso = [], [] | |
| for held in STUDIES: | |
| train_tasks = [t for t in tasks if not t.startswith(held)] | |
| test_tasks = [t for t in tasks if t.startswith(held)] | |
| sel = greedy(models, pool, train_tasks, BASE_STACK) | |
| m_sel = float(np.mean(list(score(models, sel, test_tasks).values()))) | |
| m_base = float(np.mean(list(score(models, BASE_STACK, test_tasks).values()))) | |
| loso.append(m_sel) | |
| base_loso.append(m_base) | |
| print(f" held={held:8s} selected={sel} selected={m_sel:.4f} base={m_base:.4f}") | |
| rows.append({"setting": f"loso_{held}", "members": "|".join(sel), | |
| "mean": m_sel, "delta": m_sel - m_base}) | |
| print(f"\nLOSO honest estimate: selected={np.mean(loso):.4f} base={np.mean(base_loso):.4f} " | |
| f"delta={np.mean(loso) - np.mean(base_loso):+.4f}") | |
| df = pd.DataFrame(rows) | |
| Path(args.out).parent.mkdir(parents=True, exist_ok=True) | |
| df.to_csv(args.out, index=False) | |
| print("wrote", args.out) | |
| if __name__ == "__main__": | |
| main() |