File size: 5,925 Bytes
530fba0
00cf4bb
530fba0
 
 
 
 
00cf4bb
530fba0
 
 
00cf4bb
530fba0
00cf4bb
 
 
 
 
 
 
530fba0
00cf4bb
 
 
 
530fba0
 
 
 
 
00cf4bb
 
530fba0
 
 
 
 
00cf4bb
530fba0
 
00cf4bb
530fba0
 
 
 
00cf4bb
530fba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf4bb
530fba0
 
 
00cf4bb
 
 
 
530fba0
 
 
00cf4bb
 
 
 
530fba0
00cf4bb
 
 
 
 
530fba0
00cf4bb
 
 
 
530fba0
00cf4bb
530fba0
 
 
 
 
 
 
 
 
 
 
 
00cf4bb
530fba0
 
00cf4bb
530fba0
 
 
 
 
00cf4bb
 
530fba0
00cf4bb
530fba0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
00cf4bb
 
 
 
530fba0
 
00cf4bb
 
 
 
530fba0
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
"""Few-shot calibration on top of the rank-averaged ensemble base.

The published LNPAdapt ladder calibrates a single random forest. This script
asks whether the same pilot budget buys more when the 0-shot base is the
cross-family ensemble: the pilot labels fit a residual Ridge correction or an
isotonic map on the *rank-averaged* ensemble prediction, which costs no
retraining at all.

Protocol is identical to `fewshot_active.py`: same k values, same pilot
selectors (random vs k-means medoid), same seeds, same evaluation. The only
difference is the base predictor.

    PYTHONPATH=src python scripts/fewshot_stack.py --ks 0.05 0.10 0.20
"""

from __future__ import annotations

import argparse
import pickle
import re
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
from sklearn.cluster import KMeans
from sklearn.isotonic import IsotonicRegression
from sklearn.linear_model import Ridge

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+$")

BEST6 = ["physchem_tree", "physset_phys", "relmode_nr_w", "randomforest",
         "extratrees", "lion"]


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 representative_rows(X: np.ndarray, k: int, seed: int) -> np.ndarray:
    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] = int(np.random.default_rng(seed + j).integers(len(X)))
            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 main() -> None:
    ap = argparse.ArgumentParser()
    ap.add_argument("--members", nargs="+", default=BEST6)
    ap.add_argument("--ks", nargs="+", type=float, default=[0.05, 0.10, 0.20])
    ap.add_argument("--pilot-seeds", nargs="+", type=int, default=[0, 1])
    ap.add_argument("--pred-dir", default="results/predictions")
    ap.add_argument("--out", default="results/fewshot_stack.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)
    table = load(Path(args.pred_dir), args.members)

    rows = []
    for t in tasks:
        name = t["name"]
        if not EXTERNAL.match(name):
            continue
        # per-member seed average, then cross-member rank average
        cols = []
        y = None
        for mem in args.members:
            seeds = table.get((mem, name))
            if not seeds:
                continue
            per_seed = [rank_norm(p) for _, p in seeds.values()]
            cols.append(np.mean(per_seed, axis=0))
            if y is None:
                y = seeds[0][0]
        if len(cols) < 2 or y is None:
            continue
        base = np.mean(cols, axis=0)

        study = name.rsplit("_fold", 1)[0]
        fold = int(name.rsplit("fold", 1)[1])
        rows.append({"task": name, "study": study, "fold": fold, "seed": -1,
                     "select": "none", "use": "ensemble", "k_shot": 0.0,
                     "n_target_labels": 0, "n_eval": len(y),
                     "spearman": float(spearmanr(y, base).statistic)})

        Xte = chemistry_block(store, 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)
                pilots = {
                    "random": rng.permutation(n_all)[:n_lab],
                    "repr": representative_rows(Xte, n_lab, pseed),
                }
                for sel, cal in pilots.items():
                    ycal = y[cal]
                    # residual Ridge correction on the pilot
                    ridge = Ridge(alpha=1.0).fit(base[cal].reshape(-1, 1), ycal - base[cal])
                    corr = ridge.predict(base.reshape(-1, 1))
                    rho = spearmanr(y, base + corr).statistic
                    rows.append({"task": name, "study": study, "fold": fold,
                                 "seed": pseed, "select": sel, "use": "residual",
                                 "k_shot": k, "n_target_labels": len(cal),
                                 "n_eval": n_all, "spearman": float(rho)})
                    # monotone calibration on the pilot
                    iso = IsotonicRegression(out_of_bounds="clip").fit(base[cal], ycal)
                    rho = spearmanr(y, iso.predict(base)).statistic
                    rows.append({"task": name, "study": study, "fold": fold,
                                 "seed": pseed, "select": sel, "use": "isotonic",
                                 "k_shot": k, "n_target_labels": len(cal),
                                 "n_eval": n_all, "spearman": float(rho)})
        print(f"{name} done", flush=True)

    df = pd.DataFrame(rows)
    df.to_csv(args.out, index=False)
    print("\n== mean over tasks ==")
    print(df.groupby(["k_shot", "select", "use"]).spearman.agg(["size", "mean"])
          .round(4).to_string())
    print("wrote", args.out)


if __name__ == "__main__":
    main()