File size: 4,324 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 121 | """Family-rule ensemble: one member per model family, selected without the
held-out study.
The published four-member stack (PhysChem-Tree + PhysSet-LNP + RF + ET) was
fixed a priori. This script formalises a cleaner rule - one member per
*family* present in the benchmark (identity-free tree, physics-informed
neural, neural baseline, discrete-relation kernel) - and prices it with the
same leave-one-study-out protocol as `stack_loso.py`: within each family the
representative is chosen on the three training studies only, then the ensemble
is evaluated on the held-out study.
PYTHONPATH=src python scripts/stack_family.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")
FAMILIES = {
"tree": ["physchem_tree", "randomforest", "extratrees", "xgboost"],
"neural_phys": ["physset_phys", "phcausal_phys", "probe_flat_rank"],
"neural_base": ["lion", "agile"],
"relation": ["relmode_nr_w", "physmode_chem"],
}
# fixed sets reported alongside the LOSO estimate
FIXED = {
"family4": ["physchem_tree", "physset_phys", "lion", "relmode_nr_w"],
"family5": ["physchem_tree", "physset_phys", "lion", "relmode_nr_w",
"extratrees"],
"published_4": ["physchem_tree", "physset_phys", "randomforest", "extratrees"],
"published_5": ["physchem_tree", "physset_phys", "randomforest", "extratrees",
"relmode_nr_w"],
}
def rank_norm(x: np.ndarray) -> np.ndarray:
return stats.rankdata(x, method="average") / len(x) - 0.5
def load(pred_dir: Path) -> 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"]):
continue
z = np.load(f)
table[(m["model"], m["task"])][int(m["seed"])] = (z["y"], z["pred"])
return table
def ens_pred(table, members, task):
cols, y = [], None
for mem in members:
seeds = table.get((mem, task))
if not seeds:
continue
cols.append(np.mean([rank_norm(p) for _, p in seeds.values()], axis=0))
if y is None:
y = seeds[0][0]
if len(cols) < 2:
return None, None
return y, np.mean(cols, axis=0)
def rho(table, members, task):
y, p = ens_pred(table, members, task)
return float("nan") if y is None else spearmanr(y, p).statistic
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--pred-dir", default="results/predictions")
ap.add_argument("--out", default="results/stack_family.csv")
args = ap.parse_args()
table = load(Path(args.pred_dir))
tasks = sorted({t for (_, t) in table})
rows = []
for name, members in FIXED.items():
per = {t: rho(table, members, t) for t in tasks}
s = pd.Series(per).dropna()
by = s.groupby(s.index.to_series().str.rsplit("_fold", n=1).str[0]).mean()
rows.append({"stack": name, "n": len(s), "mean": s.mean(),
"selection": "fixed", **{f"s_{k}": v for k, v in by.items()}})
for held in STUDIES:
tr_tasks = [t for t in tasks if not t.startswith(held)]
he_tasks = [t for t in tasks if t.startswith(held)]
sel = [max(cands, key=lambda m: np.nanmean([rho(table, [m], t) for t in tr_tasks]))
for cands in FAMILIES.values()]
h = np.nanmean([rho(table, sel, t) for t in he_tasks])
tr = np.nanmean([rho(table, sel, t) for t in tr_tasks])
rows.append({"stack": "family4_loso", "n": len(he_tasks), "mean": h,
"selection": f"held-out {held}; members {'/'.join(sel)}",
"train_mean": tr})
df = pd.DataFrame(rows)
df.to_csv(args.out, index=False)
loso = df.loc[df["stack"] == "family4_loso", "mean"].mean()
print(df.round(4).to_string(index=False))
print(f"\nhonest family-LOSO estimate: {loso:.4f}")
print("wrote", args.out)
if __name__ == "__main__":
main()
|