File size: 6,014 Bytes
00cf4bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
535fc66
 
00cf4bb
 
535fc66
 
00cf4bb
 
535fc66
 
00cf4bb
 
 
 
 
 
 
 
 
 
 
 
 
 
535fc66
 
 
 
00cf4bb
0aa84f2
 
00cf4bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
535fc66
 
00cf4bb
 
 
 
 
 
 
 
 
535fc66
 
00cf4bb
 
 
 
535fc66
 
00cf4bb
0aa84f2
 
 
 
 
 
 
 
00cf4bb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
"""Few-shot calibration of a tree head on the identity-free chemistry block.

This script defines the *adaptation* setting used in section 9 of the report:

* 0-shot (``--ks 0``) is the strict external protocol — the model never sees a
  label from the held-out study, and the number is directly comparable with the
  rest of the benchmark.
* ``k > 0`` draws ``k * n_test`` formulations **at random from the held-out
  study**, adds their labels to the training set, and evaluates on the rest.
  This is the realistic deployment setting: a lab runs a small pilot batch of
  its own formulations and the model is calibrated on them.

Nothing else changes: same feature block, same estimator, same hyperparameters.

Usage::

    python scripts/fewshot.py --ks 0 0.02 0.05 0.10 0.20 --seeds 0 1 \
        --workers 48 --out results/fewshot.csv
"""

from __future__ import annotations

import argparse
import pickle
from pathlib import Path

import numpy as np
import pandas as pd
from scipy.stats import spearmanr

from lnpbench.features import chemistry_block

STUDIES = ("LM_2019", "BL_2023", "SL_2020", "ZC_2023")


def make_head(kind: str, workers: int, n_estimators: int = 400,
              min_leaf: int = 2, seed: int = 0):
    if kind == "rf":
        from sklearn.ensemble import RandomForestRegressor
        return RandomForestRegressor(n_estimators=n_estimators, min_samples_leaf=min_leaf,
                                     n_jobs=workers, random_state=seed)
    if kind == "et":
        from sklearn.ensemble import ExtraTreesRegressor
        return ExtraTreesRegressor(n_estimators=n_estimators, min_samples_leaf=min_leaf,
                                   n_jobs=workers, random_state=seed)
    from xgboost import XGBRegressor
    return XGBRegressor(n_estimators=600, max_depth=6, learning_rate=0.05,
                        subsample=0.8, colsample_bytree=0.6, n_jobs=workers,
                        tree_method="hist", random_state=0)


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--ks", nargs="+", type=float, default=[0.0, 0.02, 0.05, 0.10, 0.20])
    ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1])
    ap.add_argument("--head", default="rf", choices=["rf", "et", "xgb"])
    ap.add_argument("--folds", nargs="+", type=int, default=[0, 1, 2, 3, 4])
    ap.add_argument("--studies", nargs="+", default=list(STUDIES))
    ap.add_argument("--workers", type=int, default=32)
    ap.add_argument("--n-estimators", type=int, default=400)
    ap.add_argument("--min-leaf", type=int, default=2)
    ap.add_argument("--ns", nargs="+", type=int, default=None,
                    help="absolute label counts; overrides --ks")
    ap.add_argument("--out", default="results/fewshot.csv")
    ap.add_argument("--pred-dir", default=None,
                    help="if set, save the k=0 per-sample predictions here")
    args = ap.parse_args()

    from lnpbench.store import FeatureStore

    store = FeatureStore()
    with open(Path(store.cache) / "tasks.pkl", "rb") as fh:
        tasks = pickle.load(fh)

    # chemistry block is expensive to rebuild; cache per row-index signature
    rows = []
    for t in tasks:
        name = t["name"]
        if not name.startswith(tuple(args.studies)):
            continue
        fold = int(name.rsplit("fold", 1)[1])
        if fold not in args.folds:
            continue
        study = name.rsplit("_fold", 1)[0]
        Xtr = chemistry_block(store, t["train_idx"])
        Xte = chemistry_block(store, t["test_idx"])
        ytr, yte = store.y[t["train_idx"]], store.y[t["test_idx"]]

        ladder = list(args.ks) if args.ns is None else [0] + list(args.ns)
        for k in ladder:
            seeds = [0] if k == 0 else args.seeds
            for seed in seeds:
                if k == 0:
                    Btr, by = Xtr, ytr
                    Bte, byt = Xte, yte
                    n_lab = 0
                else:
                    rng = np.random.default_rng(seed)
                    perm = rng.permutation(len(yte))
                    n_lab = (max(10, int(round(k * len(yte)))) if args.ns is None
                             else min(int(k), max(10, int(0.5 * len(yte)))))
                    cal, rest = perm[:n_lab], perm[n_lab:]
                    Btr = np.concatenate([Xtr, Xte[cal]])
                    by = np.concatenate([ytr, yte[cal]])
                    Bte, byt = Xte[rest], yte[rest]
                m = make_head(args.head, args.workers, args.n_estimators,
                              args.min_leaf, seed=seed)
                m.fit(Btr, by)
                pred = m.predict(Bte)
                rho = spearmanr(byt, pred).statistic
                if k == 0 and args.pred_dir:
                    Path(args.pred_dir).mkdir(parents=True, exist_ok=True)
                    keep = t["test_idx"]
                    np.savez_compressed(
                        Path(args.pred_dir) / f"physchem_tree__{name}__s{seed}.npz",
                        idx=keep, y=yte.astype(np.float32), pred=pred.astype(np.float32))
                rows.append({"model": f"physchem_tree_{args.head}", "task": name,
                             "study": study, "fold": fold, "seed": seed,
                             "k_shot": k, "n_target_labels": n_lab,
                             "n_eval": len(byt), "spearman": float(rho)})
                print(f"{name} s{seed} k={k:<5} n_lab={n_lab:<5} rho={rho:.4f}", flush=True)
                # checkpoint after every fit so an interrupted run still leaves data
                Path(args.out).parent.mkdir(parents=True, exist_ok=True)
                pd.DataFrame(rows).to_csv(args.out, index=False)

    out = Path(args.out)
    out.parent.mkdir(parents=True, exist_ok=True)
    pd.DataFrame(rows).to_csv(out, index=False)
    df = pd.DataFrame(rows)
    print("\n== mean over tasks ==")
    print(df.groupby("k_shot").spearman.agg(["size", "mean", "std"]).round(4).to_string())
    print("wrote", out)


if __name__ == "__main__":
    main()