File size: 7,424 Bytes
681b79a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
"""Stage-1 recipe improvements, all fitted on the pilot only.

Three refinements of the refit+ensemble combination, each using the pilot
labels (never the evaluation labels):

* ``stack``      - stacking weights over [refit forest + 6 ensemble members],
  fitted on the pilot with a small ridge (7 features, 53 samples at k=10%).
* ``disagree``   - pilot selection by member disagreement (the rows where the
  6 ensemble members' rank predictions differ most), instead of random.
* ``selftrain``  - one self-training round: pseudo-label the unlabelled
  remainder with the refit+ensemble prediction, refit the forest with the
  pseudo-labels at weight 0.5.

    PYTHONPATH=src python scripts/fewshot_recipes.py --ks 0.1 0.5 --shard 0 --n-shards 2
"""

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
from sklearn.ensemble import RandomForestRegressor
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+$")

ENS6 = ["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 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, None
    return y, np.mean(cols, axis=0), np.stack(cols, axis=1)


def fit_rf(X, y, seed, workers, w=None):
    rf = RandomForestRegressor(n_estimators=400, min_samples_leaf=2,
                               n_jobs=workers, random_state=seed)
    if w is None:
        rf.fit(X, y)
    else:
        rf.fit(X, y, sample_weight=w)
    return rf


def main() -> None:
    ap = argparse.ArgumentParser()
    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("--arms", nargs="+", default=["stack", "disagree", "selftrain"])
    ap.add_argument("--pseudo-weight", type=float, default=0.5)
    ap.add_argument("--workers", type=int, default=48)
    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_recipes.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), ENS6)

    rows = []
    for t in tasks:
        name = t["name"]
        t0 = time.time()
        y, base, cols = ens_base(table, ENS6, 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"]]
        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)
                rest = np.setdiff1d(np.arange(n_all), rng.permutation(n_all)[:n_lab])
                cal = np.setdiff1d(np.arange(n_all), rest)

                # shared refit forest on the random pilot
                rf = fit_rf(np.concatenate([Xtr, Xte[cal]]),
                            np.concatenate([ytr, y[cal]]), pseed, args.workers)
                p_refit = rf.predict(Xte)
                rows.append({"task": name, "seed": pseed, "arm": "refit", "k_shot": k,
                             "select": "random",
                             "spearman": float(spearmanr(y[rest], p_refit[rest]).statistic)})
                mix = np.mean([rank_norm(p_refit), base], axis=0)
                rows.append({"task": name, "seed": pseed, "arm": "refit+ens", "k_shot": k,
                             "select": "random",
                             "spearman": float(spearmanr(y[rest], mix[rest]).statistic)})

                if "stack" in args.arms:
                    feats = np.column_stack([rank_norm(p_refit), cols])
                    ridge = Ridge(alpha=1.0).fit(feats[cal], y[cal])
                    pred = feats @ ridge.coef_ + ridge.intercept_
                    rows.append({"task": name, "seed": pseed, "arm": "stack", "k_shot": k,
                                 "select": "random",
                                 "spearman": float(spearmanr(y[rest], pred[rest]).statistic)})

                if "disagree" in args.arms:
                    dis = cols.std(axis=1)
                    cal_d = np.argsort(-dis)[:n_lab]
                    rest_d = np.setdiff1d(np.arange(n_all), cal_d)
                    rf_d = fit_rf(np.concatenate([Xtr, Xte[cal_d]]),
                                  np.concatenate([ytr, y[cal_d]]), pseed, args.workers)
                    p_d = rf_d.predict(Xte)
                    mix_d = np.mean([rank_norm(p_d), base], axis=0)
                    rows.append({"task": name, "seed": pseed, "arm": "refit+ens", "k_shot": k,
                                 "select": "disagree",
                                 "spearman": float(spearmanr(y[rest_d], mix_d[rest_d]).statistic)})

                if "selftrain" in args.arms:
                    Xfit = np.concatenate([Xtr, Xte])
                    yfit = np.concatenate([ytr, y[cal], mix[rest]])
                    wfit = np.concatenate([np.ones(len(ytr)),
                                           np.ones(len(cal)),
                                           np.full(len(rest), args.pseudo_weight)])
                    rf_st = fit_rf(Xfit, yfit, pseed, args.workers, w=wfit)
                    p_st = rf_st.predict(Xte)
                    mix_st = np.mean([rank_norm(p_st), base], axis=0)
                    rows.append({"task": name, "seed": pseed, "arm": "selftrain", "k_shot": k,
                                 "select": "random",
                                 "spearman": float(spearmanr(y[rest], mix_st[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", "select"]).spearman.agg(["size", "mean"])
          .round(4).to_string())
    print("wrote", args.out)


if __name__ == "__main__":
    main()