Download code/scripts/fewshot_final.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 5.84 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/fewshot_final.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/scripts/fewshot_final.py
-
curl -L -o fewshot_final.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/fewshot_final.py
5.84 kB
| """Final Stage-1 protocol: ensemble of pilot-adapted trees. | |
| The extended ladder showed two things: (i) at high k a boosted refit is the | |
| strongest same-budget learner, and (ii) averaging the adapted tree with the | |
| *0-shot* neural ensemble dilutes it. The final protocol therefore adapts | |
| every tree member with the pilot and averages the adapted trees: | |
| xgb - XGBoost refit on the 398-d identity-free block | |
| rf - random forest refit on the 398-d block | |
| rf_fp - random forest refit on the 398-d block + Morgan fingerprint | |
| xgb_fp - XGBoost refit on the block + fingerprint | |
| Pre-declared mixes (no weights fitted on evaluation data): | |
| best_tree - the strongest single adapted tree (xgb) | |
| trees2 - rank-average(xgb, rf_fp) | |
| trees3 - rank-average(xgb, rf_fp, rf) | |
| trees3_fp - rank-average(xgb, xgb_fp, rf_fp) | |
| trees4 - rank-average of all four | |
| Per-sample predictions are saved to results/predictions_final/ so every mix | |
| can be recomputed without retraining. | |
| PYTHONPATH=src python scripts/fewshot_final.py --ks 0.5 0.8 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import pickle | |
| import re | |
| import time | |
| 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 | |
| import xgboost as xgb | |
| EXTERNAL = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$") | |
| def rank_norm(x: np.ndarray) -> np.ndarray: | |
| return stats.rankdata(x, method="average") / len(x) - 0.5 | |
| def make_xgb(seed: int): | |
| return xgb.XGBRegressor(n_estimators=800, max_depth=6, learning_rate=0.05, | |
| subsample=0.8, colsample_bytree=0.8, reg_lambda=4.0, | |
| min_child_weight=4, random_state=seed, n_jobs=16, | |
| verbosity=0) | |
| def make_rf(seed: int, workers: int): | |
| return RandomForestRegressor(n_estimators=400, min_samples_leaf=2, | |
| n_jobs=workers, random_state=seed) | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--ks", nargs="+", type=float, default=[0.5, 0.8]) | |
| ap.add_argument("--pilot-seeds", nargs="+", type=int, default=[0]) | |
| ap.add_argument("--workers", type=int, default=16) | |
| ap.add_argument("--out", default="results/fewshot_final.csv") | |
| ap.add_argument("--pred-dir", default="results/predictions_final") | |
| 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) | |
| tasks = [t for t in tasks if EXTERNAL.match(t["name"])] | |
| Path(args.pred_dir).mkdir(parents=True, exist_ok=True) | |
| rows = [] | |
| for t in tasks: | |
| name = t["name"] | |
| t0 = time.time() | |
| Xtr = chemistry_block(store, t["train_idx"]) | |
| Xte = chemistry_block(store, t["test_idx"]) | |
| ytr, y = store.y[t["train_idx"]], store.y[t["test_idx"]] | |
| fp_tr = store.il_fp[store.il_id[t["train_idx"]]].astype(np.float32) | |
| fp_te = store.il_fp[store.il_id[t["test_idx"]]].astype(np.float32) | |
| Xtr_fp = np.concatenate([Xtr, fp_tr], axis=1) | |
| Xte_fp = np.concatenate([Xte, fp_te], axis=1) | |
| 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) | |
| yfit = np.concatenate([ytr, y[cal]]) | |
| preds = {} | |
| m = make_rf(pseed, args.workers) | |
| m.fit(np.concatenate([Xtr, Xte[cal]]), yfit) | |
| preds["rf"] = m.predict(Xte) | |
| m = make_xgb(pseed) | |
| m.fit(np.concatenate([Xtr, Xte[cal]]), yfit) | |
| preds["xgb"] = m.predict(Xte) | |
| m = make_rf(pseed, args.workers) | |
| m.fit(np.concatenate([Xtr_fp, Xte_fp[cal]]), yfit) | |
| preds["rf_fp"] = m.predict(Xte_fp) | |
| m = make_xgb(pseed) | |
| m.fit(np.concatenate([Xtr_fp, Xte_fp[cal]]), yfit) | |
| preds["xgb_fp"] = m.predict(Xte_fp) | |
| np.savez_compressed( | |
| Path(args.pred_dir) / f"adapted__{name}__s{pseed}_k{k:.2f}.npz", | |
| idx=t["test_idx"], y=y, rest=rest, cal=cal, | |
| **{f"pred_{a}": p for a, p in preds.items()}) | |
| mixes = { | |
| "best_tree": ["xgb"], | |
| "trees2": ["xgb", "rf_fp"], | |
| "trees3": ["xgb", "rf_fp", "rf"], | |
| "trees3_fp": ["xgb", "xgb_fp", "rf_fp"], | |
| "trees4": ["xgb", "xgb_fp", "rf", "rf_fp"], | |
| } | |
| for mix_name, members in mixes.items(): | |
| p = np.mean([rank_norm(preds[a]) for a in members], axis=0) | |
| rows.append({"task": name, "seed": pseed, "k_shot": k, "arm": mix_name, | |
| "spearman": float(spearmanr(y[rest], p[rest]).statistic)}) | |
| for a, p in preds.items(): | |
| rows.append({"task": name, "seed": pseed, "k_shot": k, "arm": a, | |
| "spearman": float(spearmanr(y[rest], p[rest]).statistic)}) | |
| 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", "arm"]).spearman.agg(["size", "mean"]).round(4).to_string()) | |
| print("wrote", args.out) | |
| if __name__ == "__main__": | |
| main() | |