"""Stage-1 refinement: replace the tree slot of the family ensemble with the pilot-refit forest. `fewshot_ens_refit.py` showed that *adding* the fixed ensemble base to the refit forest dilutes the adaptation (-0.011 at k=10%): the stale tree member drags the adapted model back. This script tests the replacement instead - the family ensemble with its tree slot refitted on train + pilot - alongside two cheap refinements of the published ladder: 3-seed averaging of the refit forest, and an isotonic map fitted on the pilot. PYTHONPATH=src python scripts/fewshot_family_refit.py --ks 0.10 """ from __future__ import annotations import argparse import pickle import re import time 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.ensemble import RandomForestRegressor from sklearn.isotonic import IsotonicRegression PATTERN = re.compile(r"(?P.+?)__(?P.+?)__s(?P\d+)\.npz$") EXTERNAL = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$") NEURAL = ["physset_phys", "lion", "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"]) or m["model"] not in NEURAL: 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("--ks", nargs="+", type=float, default=[0.10]) ap.add_argument("--pilot-seeds", nargs="+", type=int, default=[0, 1]) ap.add_argument("--fit-seeds", nargs="+", type=int, default=[0, 1, 2]) ap.add_argument("--workers", type=int, default=32) ap.add_argument("--pred-dir", default="results/predictions") ap.add_argument("--out", default="results/fewshot_family_refit.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)) rows = [] for t in tasks: name = t["name"] if not EXTERNAL.match(name): continue t0 = time.time() cols, y = [], None for mem in NEURAL: seeds = table.get((mem, name)) 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 or y is None: continue Xtr = chemistry_block(store, t["train_idx"]) Xte = chemistry_block(store, t["test_idx"]) ytr = store.y[t["train_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) cal = rng.permutation(n_all)[:n_lab] rest = np.setdiff1d(np.arange(n_all), cal) preds = [] for fseed in args.fit_seeds: rf = RandomForestRegressor(n_estimators=400, min_samples_leaf=2, n_jobs=args.workers, random_state=fseed) rf.fit(np.concatenate([Xtr, Xte[cal]]), np.concatenate([ytr, y[cal]])) preds.append(rank_norm(rf.predict(Xte))) refit = np.mean(preds, axis=0) ycal = y[cal] # (a) refit forest alone (3-seed average) rho = spearmanr(y[rest], refit[rest]).statistic rows.append({"task": name, "seed": pseed, "use": "refit3", "k_shot": k, "n_target_labels": len(cal), "spearman": float(rho)}) # (b) family ensemble with the tree slot replaced by the refit forest mix = np.mean([refit] + [rank_norm(c) for c in cols], axis=0) rho = spearmanr(y[rest], mix[rest]).statistic rows.append({"task": name, "seed": pseed, "use": "family_refit", "k_shot": k, "n_target_labels": len(cal), "spearman": float(rho)}) # (c) refit forest + isotonic on the pilot iso = IsotonicRegression(out_of_bounds="clip").fit(refit[cal], ycal) rho = spearmanr(y[rest], iso.predict(refit)[rest]).statistic rows.append({"task": name, "seed": pseed, "use": "refit3_iso", "k_shot": k, "n_target_labels": len(cal), "spearman": float(rho)}) print(f"{name} done ({time.time() - t0:.0f}s)", flush=True) pd.DataFrame(rows).to_csv(args.out, index=False) df = pd.DataFrame(rows) df.to_csv(args.out, index=False) print("\n== mean over tasks ==") print(df.groupby(["k_shot", "use"]).spearman.agg(["size", "mean"]).round(4).to_string()) print("wrote", args.out) if __name__ == "__main__": main()