Download code/scripts/fewshot_baselines.py from eduzrh/LNPBench: direct link, hf CLI and curl.
- Browser
- Download file 3.89 kB
-
https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/fewshot_baselines.py
- Command line
-
hf download hf://datasets/eduzrh/LNPBench/code/scripts/fewshot_baselines.py
-
curl -L -o fewshot_baselines.py https://huggingface.co/datasets/eduzrh/LNPBench/resolve/main/code/scripts/fewshot_baselines.py
3.89 kB
| """Unified-budget baselines: strong learners get the same pilot batch. | |
| The published ladder compares our k-shot number against 0-shot baselines, | |
| which is not a unified setting. This script gives CatBoost / XGBoost / | |
| ExtraTrees the *same* pilot batch (k% of the target study, same draw, same | |
| seeds) and refits them on train + pilot, evaluated on the unlabelled | |
| remainder - exactly the protocol of the refit arm in `fewshot_kscale.py`. | |
| PYTHONPATH=src python scripts/fewshot_baselines.py --ks 0.1 0.5 | |
| """ | |
| 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.stats import spearmanr | |
| PATTERN = re.compile(r".*") | |
| EXTERNAL = re.compile(r"^(LM_2019|BL_2023|SL_2020|ZC_2023)_fold\d+$") | |
| def make_catboost(seed: int): | |
| from catboost import CatBoostRegressor | |
| return CatBoostRegressor(iterations=800, depth=6, learning_rate=0.05, | |
| l2_leaf_reg=6.0, random_seed=seed, verbose=0) | |
| def make_xgboost(seed: int): | |
| import xgboost as xgb | |
| 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_extratrees(seed: int): | |
| from sklearn.ensemble import ExtraTreesRegressor | |
| return ExtraTreesRegressor(n_estimators=400, min_samples_leaf=2, | |
| n_jobs=32, random_state=seed) | |
| MAKERS = {"catboost": make_catboost, "xgboost": make_xgboost, | |
| "extratrees": make_extratrees} | |
| def main() -> None: | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--models", nargs="+", default=["catboost", "xgboost", "extratrees"]) | |
| ap.add_argument("--ks", nargs="+", type=float, default=[0.1, 0.5]) | |
| 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("--out", default="results/fewshot_baselines.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] | |
| 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"]] | |
| 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) | |
| Xfit = np.concatenate([Xtr, Xte[cal]]) | |
| yfit = np.concatenate([ytr, y[cal]]) | |
| for m in args.models: | |
| model = MAKERS[m](pseed) | |
| model.fit(Xfit, yfit) | |
| pred = model.predict(Xte) | |
| rows.append({"task": name, "model": m, "seed": pseed, "k_shot": k, | |
| "spearman": float(spearmanr(y[rest], pred[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", "model"]).spearman.agg(["size", "mean"]).round(4).to_string()) | |
| print("wrote", args.out) | |
| if __name__ == "__main__": | |
| main() | |