Download code/scripts/fewshot_kscale_xgb.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 5.58 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/fewshot_kscale_xgb.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/scripts/fewshot_kscale_xgb.py
-
curl -L -o fewshot_kscale_xgb.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/fewshot_kscale_xgb.py
5.58 kB
| """XGBoost arms for the extended k-shot ladder. | |
| The unified-budget baselines showed that a boosted refit is the strongest | |
| same-budget competitor (`fewshot_baselines.py`). This script adds the | |
| boosted arms to the ladder so the final comparison stays inside one protocol: | |
| * ``xgb`` - XGBoost refit on the 398-d identity-free block. | |
| * ``xgb_fp`` - XGBoost refit on the 398-d block + Morgan fingerprint. | |
| * ``xgb_ens`` - xgb rank-averaged with the fixed family4 ensemble. | |
| * ``xgb_fp_ens``- xgb_fp rank-averaged with the fixed family4 ensemble. | |
| PYTHONPATH=src python scripts/fewshot_kscale_xgb.py --ks 0.3 0.5 0.8 | |
| """ | |
| 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 | |
| import xgboost as xgb | |
| 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+$") | |
| ENS4 = ["physchem_tree", "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, 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 ens_base(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 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=8, | |
| verbosity=0) | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--ks", nargs="+", type=float, default=[0.3, 0.5, 0.8]) | |
| ap.add_argument("--pilot-seeds", nargs="+", type=int, default=[0, 1]) | |
| ap.add_argument("--shard", type=int, default=0) | |
| ap.add_argument("--n-shards", type=int, default=1) | |
| ap.add_argument("--pred-dir", default="results/predictions") | |
| ap.add_argument("--out", default="results/fewshot_kscale_xgb.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) | |
| tasks = [t for t in tasks if EXTERNAL.match(t["name"])][args.shard::args.n_shards] | |
| table = load(Path(args.pred_dir), ENS4) | |
| rows = [] | |
| for t in tasks: | |
| name = t["name"] | |
| t0 = time.time() | |
| y, base = ens_base(table, ENS4, name) | |
| if y is None: | |
| continue | |
| Xtr = chemistry_block(store, t["train_idx"]) | |
| Xte = chemistry_block(store, t["test_idx"]) | |
| ytr = store.y[t["train_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]]) | |
| m1 = make_xgb(pseed) | |
| m1.fit(np.concatenate([Xtr, Xte[cal]]), yfit) | |
| p1 = m1.predict(Xte) | |
| rows.append({"task": name, "seed": pseed, "arm": "xgb", "k_shot": k, | |
| "spearman": float(spearmanr(y[rest], p1[rest]).statistic)}) | |
| mix1 = np.mean([rank_norm(p1), base], axis=0) | |
| rows.append({"task": name, "seed": pseed, "arm": "xgb_ens", "k_shot": k, | |
| "spearman": float(spearmanr(y[rest], mix1[rest]).statistic)}) | |
| m2 = make_xgb(pseed) | |
| m2.fit(np.concatenate([Xtr_fp, Xte_fp[cal]]), yfit) | |
| p2 = m2.predict(Xte_fp) | |
| rows.append({"task": name, "seed": pseed, "arm": "xgb_fp", "k_shot": k, | |
| "spearman": float(spearmanr(y[rest], p2[rest]).statistic)}) | |
| mix2 = np.mean([rank_norm(p2), base], axis=0) | |
| rows.append({"task": name, "seed": pseed, "arm": "xgb_fp_ens", "k_shot": k, | |
| "spearman": float(spearmanr(y[rest], mix2[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() | |