LNPBench / code /scripts /fewshot_stack.py
eduzrh's picture
LNPBench: code, caches, results and figures
530fba0 verified
Raw History Blame Contribute Delete
5.93 kB
"""Few-shot calibration on top of the rank-averaged ensemble base.
The published LNPAdapt ladder calibrates a single random forest. This script
asks whether the same pilot budget buys more when the 0-shot base is the
cross-family ensemble: the pilot labels fit a residual Ridge correction or an
isotonic map on the *rank-averaged* ensemble prediction, which costs no
retraining at all.
Protocol is identical to `fewshot_active.py`: same k values, same pilot
selectors (random vs k-means medoid), same seeds, same evaluation. The only
difference is the base predictor.
PYTHONPATH=src python scripts/fewshot_stack.py --ks 0.05 0.10 0.20
"""
from __future__ import annotations
import argparse
import pickle
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
from sklearn.cluster import KMeans
from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import Ridge
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+$")
BEST6 = ["physchem_tree", "physset_phys", "relmode_nr_w", "randomforest",
"extratrees", "lion"]
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 representative_rows(X: np.ndarray, k: int, seed: int) -> np.ndarray:
if k >= len(X):
return np.arange(len(X))
km = KMeans(n_clusters=k, n_init=4, random_state=seed).fit(X)
med = np.zeros(k, dtype=np.int64)
for j in range(k):
m = km.labels_ == j
if not m.any():
med[j] = int(np.random.default_rng(seed + j).integers(len(X)))
continue
d = ((X[m] - km.cluster_centers_[j]) ** 2).sum(1)
med[j] = np.flatnonzero(m)[int(np.argmin(d))]
return np.unique(med)
def main() -> None:
ap = argparse.ArgumentParser()
ap.add_argument("--members", nargs="+", default=BEST6)
ap.add_argument("--ks", nargs="+", type=float, default=[0.05, 0.10, 0.20])
ap.add_argument("--pilot-seeds", nargs="+", type=int, default=[0, 1])
ap.add_argument("--pred-dir", default="results/predictions")
ap.add_argument("--out", default="results/fewshot_stack.csv")
args = ap.parse_args()
from lnpbench.features import chemistry_block
from lnpbench.store import FeatureStore
store = FeatureStore()
with open(Path(store.cache) / "tasks.pkl", "rb") as fh:
tasks = pickle.load(fh)
table = load(Path(args.pred_dir), args.members)
rows = []
for t in tasks:
name = t["name"]
if not EXTERNAL.match(name):
continue
# per-member seed average, then cross-member rank average
cols = []
y = None
for mem in args.members:
seeds = table.get((mem, name))
if not seeds:
continue
per_seed = [rank_norm(p) for _, p in seeds.values()]
cols.append(np.mean(per_seed, axis=0))
if y is None:
y = seeds[0][0]
if len(cols) < 2 or y is None:
continue
base = np.mean(cols, axis=0)
study = name.rsplit("_fold", 1)[0]
fold = int(name.rsplit("fold", 1)[1])
rows.append({"task": name, "study": study, "fold": fold, "seed": -1,
"select": "none", "use": "ensemble", "k_shot": 0.0,
"n_target_labels": 0, "n_eval": len(y),
"spearman": float(spearmanr(y, base).statistic)})
Xte = chemistry_block(store, t["test_idx"])
n_all = len(y)
for k in args.ks:
n_lab = max(10, int(round(k * n_all)))
for pseed in args.pilot_seeds:
rng = np.random.default_rng(pseed)
pilots = {
"random": rng.permutation(n_all)[:n_lab],
"repr": representative_rows(Xte, n_lab, pseed),
}
for sel, cal in pilots.items():
ycal = y[cal]
# residual Ridge correction on the pilot
ridge = Ridge(alpha=1.0).fit(base[cal].reshape(-1, 1), ycal - base[cal])
corr = ridge.predict(base.reshape(-1, 1))
rho = spearmanr(y, base + corr).statistic
rows.append({"task": name, "study": study, "fold": fold,
"seed": pseed, "select": sel, "use": "residual",
"k_shot": k, "n_target_labels": len(cal),
"n_eval": n_all, "spearman": float(rho)})
# monotone calibration on the pilot
iso = IsotonicRegression(out_of_bounds="clip").fit(base[cal], ycal)
rho = spearmanr(y, iso.predict(base)).statistic
rows.append({"task": name, "study": study, "fold": fold,
"seed": pseed, "select": sel, "use": "isotonic",
"k_shot": k, "n_target_labels": len(cal),
"n_eval": n_all, "spearman": float(rho)})
print(f"{name} done", flush=True)
df = pd.DataFrame(rows)
df.to_csv(args.out, index=False)
print("\n== mean over tasks ==")
print(df.groupby(["k_shot", "select", "use"]).spearman.agg(["size", "mean"])
.round(4).to_string())
print("wrote", args.out)
if __name__ == "__main__":
main()