File size: 11,076 Bytes
0164c03 | 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 | """
Controls for the zero-shot-features results, version 2 (after an adversarial review of v1).
============================================================================================
Fixes relative to features_controls.py (v1 outputs are kept):
* Top-choice control uses Jev's *returned* choice (it differs from the rounded-probability argmax on 266 fit-set
and 28 evaluation rows), one-hot.
* Stacked-embedding control builds its out-of-fold features inside the selection split: first-stage models for the
selection fits never see selection-slice labels; for the final fit, 5-fold out-of-fold over the whole fit set.
* One wider grid for all three controls: C in {10, 30, 100} x class weight x w in {0.01, 0.03, 0.1, 0.3, 1}.
* Learning curve with selection inside each budget: for n in {500, 2k, 8k, 20k} and three subsample seeds, the
hyperparameters are chosen on a 10% slice of the n complaints themselves and the model is refitted on all n.
Models: TF-IDF, TF-IDF + Jev probabilities, TF-IDF + label-name similarity.
uv run --no-project --with numpy --with scikit-learn --with scipy --with joblib --with datasets \\
--with huggingface_hub --with typesafe-sdk --with sentence-transformers python verification/features_controls_v2.py
"""
import json
import sys
import time
from pathlib import Path
import numpy as np
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT)); sys.path.insert(0, str(ROOT / "verification"))
from utils.data_utils import load_course_data, LABEL_LIST, NUM_LABELS
from jev_benchmark import SEED, macro_f1
from jev_extended import jev_probs, jev_feats
ART = ROOT / "verification" / "jev_benchmark_artifacts"
K = NUM_LABELS
C_GRID, W_GRID = (10.0, 30.0, 100.0), (0.01, 0.03, 0.1, 0.3, 1.0)
def main():
from joblib import Parallel, delayed
from scipy.sparse import csr_matrix, hstack
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold, train_test_split
from sklearn.preprocessing import StandardScaler
tr_ds, val_ds, te_ds = load_course_data()
fit_texts = list(tr_ds["text"]) + list(te_ds["text"])
y_fit = np.concatenate([tr_ds["label"], te_ds["label"]])
val_texts, y_val = list(val_ds["text"]), np.array(val_ds["label"])
idx = np.arange(len(y_fit))
tr, dev = train_test_split(idx, test_size=0.1, stratify=y_fit, random_state=SEED)
lr = lambda C, cw: LogisticRegression(C=C, class_weight=cw, max_iter=2000, solver="lbfgs")
tfidf = lambda: TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2))
# ---- feature blocks ----------------------------------------------------------------------------------
(ptr, ctr), (pte, cte) = jev_probs("train"), jev_probs("test")
p_fit, choice_fit = np.vstack([ptr, pte]), np.concatenate([ctr, cte]).astype(int)
p_val, choice_val = jev_probs("val"); choice_val = np.asarray(choice_val).astype(int)
print(f"returned choice != probability argmax: fit {(choice_fit != p_fit.argmax(-1)).sum()}, "
f"val {(choice_val != p_val.argmax(-1)).sum()}")
E_fit = np.load(ART / "embeddings_mpnet_fit.npz")["emb"]; E_val = np.load(ART / "embeddings_mpnet_val.npz")["emb"]
from sentence_transformers import SentenceTransformer
L = SentenceTransformer("sentence-transformers/all-mpnet-base-v2", device="cpu").encode(
LABEL_LIST, normalize_embeddings=True, convert_to_numpy=True)
sim_fit, sim_val = E_fit @ L.T, E_val @ L.T
def oof(rows_train, rows_apply=None, E_apply=None):
"""Out-of-fold probabilities over rows_train (5-fold) and, if given, a model on all rows_train applied to
E_apply. First stage: logistic regression on embeddings, C=0.01 (the selected embeddings-only config)."""
out = np.zeros((len(rows_train), K))
folds = list(StratifiedKFold(5, shuffle=True, random_state=SEED).split(rows_train, y_fit[rows_train]))
def fold(a, b):
m = lr(0.01, None).fit(E_fit[rows_train[a]], y_fit[rows_train[a]])
o = np.zeros((len(b), K)); o[:, m.classes_] = m.predict_proba(E_fit[rows_train[b]]); return b, o
for b, o in Parallel(n_jobs=5)(delayed(fold)(a, b) for a, b in folds):
out[b] = o
applied = None
if E_apply is not None:
m = lr(0.01, None).fit(E_fit[rows_train], y_fit[rows_train])
applied = np.zeros((len(E_apply), K)); applied[:, m.classes_] = m.predict_proba(E_apply)
return out, applied
cache_oof = ART / "controls_v2_oof.npz"
if cache_oof.exists():
d = np.load(cache_oof); oof_tr, oof_dev, oof_fit, oof_val = d["tr"], d["dev"], d["fit"], d["val"]
else:
t0 = time.time()
oof_tr, oof_dev = oof(tr, E_apply=E_fit[dev]) # selection: first stage never sees dev labels
oof_fit, oof_val = oof(idx, E_apply=E_val) # final: out-of-fold over the whole fit set
np.savez_compressed(cache_oof, tr=oof_tr, dev=oof_dev, fit=oof_fit, val=oof_val)
print(f" stacking features in {time.time() - t0:.0f}s")
# per control: (train-rows block for selection, dev block, full fit block, val block)
blocks = {"onehot_choice": (np.eye(K)[choice_fit[tr]], np.eye(K)[choice_fit[dev]], np.eye(K)[choice_fit], np.eye(K)[choice_val]),
"labelsim": (sim_fit[tr], sim_fit[dev], sim_fit, sim_val),
"oof_emb_insplit": (jev_feats(oof_tr), jev_feats(oof_dev), jev_feats(oof_fit), jev_feats(oof_val))}
vec_tr = tfidf().fit([fit_texts[i] for i in tr])
T_tr, T_dev = vec_tr.transform([fit_texts[i] for i in tr]), vec_tr.transform([fit_texts[i] for i in dev])
vec_all = tfidf().fit(fit_texts)
T_fit, T_val = vec_all.transform(fit_texts), vec_all.transform(val_texts)
comb = lambda T, B, sc, w: hstack([T, csr_matrix(sc.transform(B) * w)]).tocsr()
grid = [dict(C=C, class_weight=cw, w=w) for C in C_GRID for cw in (None, "balanced") for w in W_GRID]
cache_p = ART / "controls_v2_selection_cache.json"
cache = json.loads(cache_p.read_text()) if cache_p.exists() else {}
key = lambda k, c: f"{k} {json.dumps(c, sort_keys=True)}"
def dev_score(kind, cfg):
Btr, Bdev, _, _ = blocks[kind]; sc = StandardScaler().fit(Btr)
m = lr(cfg["C"], cfg["class_weight"]).fit(comb(T_tr, Btr, sc, cfg["w"]), y_fit[tr])
return kind, cfg, macro_f1(y_fit[dev], m.predict(comb(T_dev, Bdev, sc, cfg["w"])))
jobs = [(k, c) for k in blocks for c in grid if key(k, c) not in cache]
print(f"Selection: {len(jobs)} fits"); t0 = time.time()
for k, c, f in Parallel(n_jobs=12)(delayed(dev_score)(k, c) for k, c in jobs):
cache[key(k, c)] = f
cache_p.write_text(json.dumps(cache, indent=1))
print(f" selection done in {(time.time() - t0) / 60:.0f} min")
best = {k: max(((c, cache[key(k, c)]) for c in grid), key=lambda x: x[1]) for k in blocks}
def final(kind):
cfg = best[kind][0]; _, _, Bf, Bv = blocks[kind]; sc = StandardScaler().fit(Bf)
m = lr(cfg["C"], cfg["class_weight"]).fit(comb(T_fit, Bf, sc, cfg["w"]), y_fit)
out = np.zeros((len(y_val), K)); out[:, m.classes_] = m.predict_proba(comb(T_val, Bv, sc, cfg["w"])); return kind, out
finals = dict(Parallel(n_jobs=3)(delayed(final)(k) for k in blocks))
np.savez_compressed(ART / "controls_v2_val_probs.npz", labels=y_val, **finals)
for k, v in finals.items():
print(f" EVAL {k:<16} acc {(v.argmax(-1) == y_val).mean():.3f} macro F1 {macro_f1(y_val, v.argmax(-1)):.3f} {best[k][0]}")
# ---- learning curve, selection inside each budget ------------------------------------------------------
lc_grid = {"tfidf": [dict(C=C, class_weight=cw) for C in (1.0, 10.0, 30.0, 100.0) for cw in (None, "balanced")],
"tfidf+jev": [dict(C=C, class_weight=cw, w=w) for C in (10.0, 30.0, 100.0) for cw in (None, "balanced") for w in (0.03, 0.1, 0.3)],
"tfidf+sim": [dict(C=C, class_weight=cw, w=w) for C in (10.0, 30.0, 100.0) for cw in (None, "balanced") for w in (0.1, 0.3, 1.0)]}
dense = {"tfidf+jev": (jev_feats(p_fit), jev_feats(p_val)), "tfidf+sim": (sim_fit, sim_val)}
def lc_job(n, seed):
rows = np.random.default_rng(seed).permutation(len(y_fit))[:n]
ys = y_fit[rows]; cnt = np.bincount(ys, minlength=K)
strat = ys if cnt[cnt > 0].min() >= 2 else None
try:
a, b = train_test_split(np.arange(n), test_size=0.1, stratify=strat, random_state=SEED)
except ValueError:
a, b = train_test_split(np.arange(n), test_size=0.1, random_state=SEED)
txt = [fit_texts[i] for i in rows]
va = tfidf().fit([txt[i] for i in a]); Ta, Tb = va.transform([txt[i] for i in a]), va.transform([txt[i] for i in b])
vall = tfidf().fit(txt); Tall, Tv = vall.transform(txt), vall.transform(val_texts)
out = []
for kind, g in lc_grid.items():
scores = []
for cfg in g:
if kind == "tfidf":
m = lr(cfg["C"], cfg["class_weight"]).fit(Ta, ys[a]); f = macro_f1(ys[b], m.predict(Tb))
else:
Bf = dense[kind][0][rows]; sc = StandardScaler().fit(Bf[a])
m = lr(cfg["C"], cfg["class_weight"]).fit(comb(Ta, Bf[a], sc, cfg["w"]), ys[a])
f = macro_f1(ys[b], m.predict(comb(Tb, Bf[b], sc, cfg["w"])))
scores.append(f)
cfg = g[int(np.argmax(scores))]
if kind == "tfidf":
pred = lr(cfg["C"], cfg["class_weight"]).fit(Tall, ys).predict(Tv)
else:
Bf, Bv = dense[kind][0][rows], dense[kind][1]; sc = StandardScaler().fit(Bf)
pred = lr(cfg["C"], cfg["class_weight"]).fit(comb(Tall, Bf, sc, cfg["w"]), ys).predict(comb(Tv, Bv, sc, cfg["w"]))
out.append({"model": kind, "n": n, "seed": seed, "selected": cfg,
"accuracy": float((pred == y_val).mean()), "macro_f1": float(macro_f1(y_val, pred))})
return out
t0 = time.time()
lc = [r for res in Parallel(n_jobs=12)(delayed(lc_job)(n, s) for n in (500, 2000, 8000, 20000) for s in (0, 1, 2)) for r in res]
print(f" learning curve in {(time.time() - t0) / 60:.0f} min")
for r in sorted(lc, key=lambda r: (r["model"], r["n"], r["seed"])):
print(f" CURVE {r['model']:<10} n={r['n']:>6} seed={r['seed']} acc {r['accuracy']:.3f} macro F1 {r['macro_f1']:.3f}")
res = {"selected": {k: {**best[k][0], "selection_macro_f1": best[k][1]} for k in best},
"returned_choice_differs_from_argmax": {"fit": int((choice_fit != p_fit.argmax(-1)).sum()),
"val": int((choice_val != p_val.argmax(-1)).sum())},
"learning_curve_nested": lc}
(ART / "controls_v2_results.json").write_text(json.dumps(res, indent=2))
print(" saved controls_v2_val_probs.npz and controls_v2_results.json")
if __name__ == "__main__":
main()
|