File size: 7,360 Bytes
4e4f237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
"""Active few-shot calibration on the identity-free chemistry block.

The published adaptation ladder draws the pilot batch at random.  This script
asks two questions that matter for a real deployment:

1. **Which** formulations should the lab synthesise?  Random draws may miss the
   study's chemical diversity; a *representative* pilot (k-means over the
   target-study feature space, one medoid per cluster) covers it with the same
   number of measurements.
2. **How** should the pilot be used?  Three options:
   * ``refit``    -- add the pilot labels to the training pool and refit the
                     forest (the current LNPAdapt).
   * ``residual`` -- keep the 0-shot model and fit a small ridge correction on
                     the pilot residuals; the correction can only move the
                     prediction by a few tenths of a z-unit.
   * ``isotonic`` -- fit a monotone mapping from the 0-shot predictions to the
                     pilot labels; changes the ranking only where the base
                     model is systematically biased.

Everything else is the published protocol: same block, same estimator, same
folds, same seeds, same evaluation on the unlabelled remainder.

    PYTHONPATH=src python scripts/fewshot_active.py --ks 0.05 0.10 --seeds 0 1
"""

from __future__ import annotations

import argparse
import pickle
import time
from pathlib import Path

import numpy as np
import pandas as pd
from scipy.stats import spearmanr
from sklearn.cluster import KMeans
from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import Ridge

from lnpbench.features import chemistry_block

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


def make_head(workers: int, n_estimators: int = 400, min_leaf: int = 2, seed: int = 0):
    from sklearn.ensemble import RandomForestRegressor

    return RandomForestRegressor(n_estimators=n_estimators, min_samples_leaf=min_leaf,
                                 n_jobs=workers, random_state=seed)


def representative_rows(X: np.ndarray, k: int, seed: int) -> np.ndarray:
    """One medoid per k-means cluster: a pilot that covers the study's space."""
    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] = rng_pick(len(X), seed + j)
            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 rng_pick(n: int, seed: int) -> int:
    return int(np.random.default_rng(seed).integers(n))


def main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--ks", nargs="+", type=float, default=[0.05, 0.10])
    ap.add_argument("--seeds", nargs="+", type=int, default=[0, 1])
    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("--out", default="results/fewshot_active.csv")
    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)

    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"]]

        for seed in args.seeds:
            t0 = time.time()
            # 0-shot model, shared by every variant
            base = make_head(args.workers, args.n_estimators, args.min_leaf, seed)
            base.fit(Xtr, ytr)
            pred_te = base.predict(Xte)
            rho0 = spearmanr(yte, pred_te).statistic
            rows.append({"task": name, "study": study, "fold": fold, "seed": seed,
                         "select": "none", "use": "none", "k_shot": 0.0,
                         "n_target_labels": 0, "n_eval": len(yte), "spearman": float(rho0)})
            print(f"{name} s{seed} k=0     rho={rho0:.4f}", flush=True)

            for k in args.ks:
                n_lab = max(10, int(round(k * len(yte))))
                rng = np.random.default_rng(seed)
                perm = rng.permutation(len(yte))
                pilots = {
                    "random": perm[:n_lab],
                    "repr": representative_rows(Xte, n_lab, seed),
                }
                for sel, cal in pilots.items():
                    ycal = yte[cal]
                    # (a) refit on train + pilot
                    m = make_head(args.workers, args.n_estimators, args.min_leaf, seed)
                    m.fit(np.concatenate([Xtr, Xte[cal]]),
                          np.concatenate([ytr, ycal]))
                    rest = np.setdiff1d(np.arange(len(yte)), cal)
                    rho = spearmanr(yte[rest], m.predict(Xte[rest])).statistic
                    rows.append({"task": name, "study": study, "fold": fold, "seed": seed,
                                 "select": sel, "use": "refit", "k_shot": k,
                                 "n_target_labels": len(cal), "n_eval": len(rest),
                                 "spearman": float(rho)})
                    # (b) ridge residual correction on the pilot
                    p_cal = base.predict(Xte[cal])
                    ridge = Ridge(alpha=1.0).fit(p_cal.reshape(-1, 1), ycal - p_cal)
                    corr = ridge.predict(pred_te.reshape(-1, 1))
                    rho = spearmanr(yte, pred_te + corr).statistic
                    rows.append({"task": name, "study": study, "fold": fold, "seed": seed,
                                 "select": sel, "use": "residual", "k_shot": k,
                                 "n_target_labels": len(cal), "n_eval": len(yte),
                                 "spearman": float(rho)})
                    # (c) monotone calibration on the pilot
                    iso = IsotonicRegression(out_of_bounds="clip").fit(p_cal, ycal)
                    rho = spearmanr(yte, iso.predict(pred_te)).statistic
                    rows.append({"task": name, "study": study, "fold": fold, "seed": seed,
                                 "select": sel, "use": "isotonic", "k_shot": k,
                                 "n_target_labels": len(cal), "n_eval": len(yte),
                                 "spearman": float(rho)})
                    print(f"{name} s{seed} k={k:<5} {sel:6s} refit/resid/iso done "
                          f"({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 20 tasks ==")
    print(df.groupby(["k_shot", "select", "use"]).spearman.agg(["size", "mean"])
          .round(4).to_string())
    print("wrote", args.out)


if __name__ == "__main__":
    main()