"""Pilot refit combined with the fixed ensemble base. `fewshot_active.py` showed that refitting the forest with the pilot labels is far stronger than calibrating the fixed prediction (+0.074 vs +0.016 at k=10%): the pilot labels let the model re-learn the target study's chemistry->activity mapping in feature space, not just its prediction marginal. `fewshot_stack.py` showed that the six-member ensemble is the strongest 0-shot base (0.407). This script combines the two: refit the identity-free forest on train + pilot, then rank-average the refit forest with the fixed ensemble base. Everything is evaluated on the unlabelled remainder, exactly like the published ladder. PYTHONPATH=src python scripts/fewshot_ens_refit.py --ks 0.05 0.10 0.20 """ 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.cluster import KMeans from sklearn.ensemble import RandomForestRegressor PATTERN = re.compile(r"(?P.+?)__(?P.+?)__s(?P\d+)\.npz$") EXTERNAL = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$") ENSEMBLE = ["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("--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("--selects", nargs="+", default=["random", "repr"]) ap.add_argument("--workers", type=int, default=32) ap.add_argument("--n-estimators", type=int, default=400) ap.add_argument("--pred-dir", default="results/predictions") ap.add_argument("--out", default="results/fewshot_ens_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), ENSEMBLE) rows = [] for t in tasks: name = t["name"] if not EXTERNAL.match(name): continue t0 = time.time() cols, y = [], None for mem in ENSEMBLE: 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 base = np.mean(cols, axis=0) study = name.rsplit("_fold", 1)[0] fold = int(name.rsplit("fold", 1)[1]) 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) draws = { "random": rng.permutation(n_all)[:n_lab], "repr": representative_rows(Xte, n_lab, pseed), } for sel in args.selects: cal = draws[sel] rest = np.setdiff1d(np.arange(n_all), cal) rf = RandomForestRegressor(n_estimators=args.n_estimators, min_samples_leaf=2, n_jobs=args.workers, random_state=pseed) rf.fit(np.concatenate([Xtr, Xte[cal]]), np.concatenate([ytr, y[cal]])) p_refit = rf.predict(Xte) rho_solo = spearmanr(y[rest], p_refit[rest]).statistic rows.append({"task": name, "study": study, "fold": fold, "seed": pseed, "select": sel, "use": "refit", "k_shot": k, "n_target_labels": len(cal), "n_eval": len(rest), "spearman": float(rho_solo)}) mix = np.mean([rank_norm(p_refit), base], axis=0) rho_mix = spearmanr(y[rest], mix[rest]).statistic rows.append({"task": name, "study": study, "fold": fold, "seed": pseed, "select": sel, "use": "refit+ens", "k_shot": k, "n_target_labels": len(cal), "n_eval": len(rest), "spearman": float(rho_mix)}) 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", "select", "use"]).spearman.agg(["size", "mean"]) .round(4).to_string()) print("wrote", args.out) if __name__ == "__main__": main()