File size: 10,883 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 179 180 181 182 183 184 185 186 187 188 189 | """
Controls for the Jev-features result (paper section "Zero-shot probabilities as features").
===========================================================================================
Run after `jev_extended.py features` and `embedding_control.py`. Same fit set (79,278), same stratified 10%
selection slice (seed 42), evaluation split scored once per control. Designed after the main feature results
were known (status B).
A TF-IDF + one-hot(Jev's bare-label choice): does Jev's *top choice* carry the gain, or its distribution?
B Logit adjustment (Menon et al. 2021): TF-IDF (and TF-IDF + Jev) probabilities divided by prior^tau, tau tuned
for macro F1 on the selection slice. Tests whether the Jev gain is a shift of the decision rule toward rare
labels that a prior correction would also produce.
C TF-IDF + label-name similarity: cosine between each complaint's sentence embedding and each of the 113 label
names' embeddings -- a 113-dim zero-shot label scorer with no API.
C' TF-IDF + stacked embedding probabilities: 5-fold out-of-fold probabilities of logistic regression on sentence
embeddings, 113-dim like Jev's vector, same log transform.
E Learning curve: TF-IDF, Jev probabilities, and TF-IDF + Jev fitted on 500 / 2,000 / 8,000 / 20,000 / all fit-set
complaints with the hyperparameters selected on the full data.
Controls A, C, C' use the TF-IDF + Jev grid restricted to C in {10, 30} (the values TF-IDF and TF-IDF + Jev selected)
x class weight x w in {0.01, 0.03, 0.1, 0.3}.
uv run --no-project --with numpy --with scikit-learn --with scipy --with joblib --with datasets \\
--with sentence-transformers python verification/features_controls.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
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)
def lr(C, cw):
return LogisticRegression(C=C, class_weight=cw, max_iter=2000, solver="lbfgs")
# --- dense 113-dim blocks for fit set and evaluation split -------------------------------------------------
p_fit = np.vstack([jev_probs("train")[0], jev_probs("test")[0]]); p_val, _ = jev_probs("val")
onehot = lambda P: np.eye(K)[P.argmax(-1)]
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
oof_path = ART / "controls_oof_embedding_probs.npz"
if oof_path.exists():
d = np.load(oof_path); oof_fit, oof_val = d["fit"], d["val"]
else:
t0 = time.time()
folds = list(StratifiedKFold(5, shuffle=True, random_state=SEED).split(E_fit, y_fit))
def fold(trn, tst):
m = lr(0.01, None).fit(E_fit[trn], y_fit[trn])
out = np.zeros((len(tst), K)); out[:, m.classes_] = m.predict_proba(E_fit[tst]); return tst, out
oof_fit = np.zeros((len(y_fit), K))
for tst, out in Parallel(n_jobs=5)(delayed(fold)(a, b) for a, b in folds):
oof_fit[tst] = out
m = lr(0.01, None).fit(E_fit, y_fit)
oof_val = np.zeros((len(y_val), K)); oof_val[:, m.classes_] = m.predict_proba(E_val)
np.savez_compressed(oof_path, fit=oof_fit, val=oof_val)
print(f" out-of-fold embedding probabilities in {time.time() - t0:.0f}s")
blocks = {"onehot_jev": (onehot(p_fit), onehot(p_val)),
"labelsim": (sim_fit, sim_val),
"oof_emb": (jev_feats(oof_fit), jev_feats(oof_val))}
# --- TF-IDF matrices (vectorizer fitted on the rows being trained on) --------------------------------------
vec_tr = TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2)).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 = TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2)).fit(fit_texts)
T_fit, T_val = vec_all.transform(fit_texts), vec_all.transform(val_texts)
def combined(T, B, scaler, w):
return hstack([T, csr_matrix(scaler.transform(B) * w)]).tocsr()
grid = [dict(C=C, class_weight=cw, w=w) for C in (10.0, 30.0) for cw in (None, "balanced")
for w in (0.01, 0.03, 0.1, 0.3)]
cache_p = ART / "controls_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):
Bf, _ = blocks[kind]
sc = StandardScaler().fit(Bf[tr])
m = lr(cfg["C"], cfg["class_weight"]).fit(combined(T_tr, Bf[tr], sc, cfg["w"]), y_fit[tr])
return kind, cfg, macro_f1(y_fit[dev], m.predict(combined(T_dev, Bf[dev], 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, f1 in Parallel(n_jobs=12)(delayed(dev_score)(k, c) for k, c in jobs):
cache[key(k, c)] = f1
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(combined(T_fit, Bf, sc, cfg["w"]), y_fit)
out = np.zeros((len(y_val), K)); out[:, m.classes_] = m.predict_proba(combined(T_val, Bv, sc, cfg["w"]))
return kind, out
finals = dict(Parallel(n_jobs=3)(delayed(final)(k) for k in blocks))
# --- B: logit adjustment on the selected TF-IDF and TF-IDF + Jev models -----------------------------------
sel = json.loads((ART / "jev-1.13.0_features_results.json").read_text())["selected"]
feat_val = np.load(ART / "jev-1.13.0_features_val_probs.npz")
prior_tr = np.bincount(y_fit[tr], minlength=K) / len(tr); prior_all = np.bincount(y_fit, minlength=K) / len(y_fit)
taus = np.round(np.arange(0, 2.01, 0.1), 2)
def dev_probs(kind):
cfg = sel[kind]
if kind == "tfidf":
X_tr, X_dev = T_tr, T_dev
else:
sc = StandardScaler().fit(jev_feats(p_fit[tr]))
X_tr, X_dev = combined(T_tr, jev_feats(p_fit[tr]), sc, cfg["w"]), combined(T_dev, jev_feats(p_fit[dev]), sc, cfg["w"])
m = lr(cfg["C"], cfg["class_weight"]).fit(X_tr, y_fit[tr])
out = np.zeros((len(dev), K)); out[:, m.classes_] = m.predict_proba(X_dev); return kind, out
dprobs = dict(Parallel(n_jobs=2)(delayed(dev_probs)(k) for k in ("tfidf", "tfidf+jev")))
adjusted, tau_sel = {}, {}
for kind, vkey in (("tfidf", "tfidf"), ("tfidf+jev", "tfidf_jev")):
f1s = [macro_f1(y_fit[dev], (np.log(dprobs[kind] + 1e-12) - t * np.log(prior_tr + 1e-12)).argmax(-1)) for t in taus]
t = float(taus[int(np.argmax(f1s))]); tau_sel[kind] = {"tau": t, "selection_macro_f1": float(max(f1s)),
"selection_macro_f1_tau0": float(f1s[0])}
z = np.log(feat_val[vkey] + 1e-12) - t * np.log(prior_all + 1e-12)
e = np.exp(z - z.max(-1, keepdims=True)); adjusted[kind] = e / e.sum(-1, keepdims=True)
# --- E: learning curve ----------------------------------------------------------------------------------
rng = np.random.default_rng(SEED); perm = rng.permutation(len(y_fit))
sizes = [500, 2000, 8000, 20000, len(y_fit)]
def curve(kind, n):
rows = perm[:n]; cfg = sel[kind]
if kind == "jev":
sc = StandardScaler().fit(jev_feats(p_fit[rows]))
m = lr(cfg["C"], cfg["class_weight"]).fit(sc.transform(jev_feats(p_fit[rows])), y_fit[rows])
pred = m.predict(sc.transform(jev_feats(p_val)))
else:
v = TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2)).fit([fit_texts[i] for i in rows])
Tr, Tv = v.transform([fit_texts[i] for i in rows]), v.transform(val_texts)
if kind == "tfidf+jev":
sc = StandardScaler().fit(jev_feats(p_fit[rows]))
Tr, Tv = combined(Tr, jev_feats(p_fit[rows]), sc, cfg["w"]), combined(Tv, jev_feats(p_val), sc, cfg["w"])
m = lr(cfg["C"], cfg["class_weight"]).fit(Tr, y_fit[rows]); pred = m.predict(Tv)
return kind, n, float((pred == y_val).mean()), float(macro_f1(y_val, pred))
lc = Parallel(n_jobs=12)(delayed(curve)(k, n) for k in ("tfidf", "jev", "tfidf+jev") for n in sizes)
np.savez_compressed(ART / "controls_val_probs.npz", labels=y_val, **{k: v for k, v in finals.items()},
tfidf_logit_adjusted=adjusted["tfidf"], tfidf_jev_logit_adjusted=adjusted["tfidf+jev"])
res = {"selected": {k: {**best[k][0], "selection_macro_f1": best[k][1]} for k in best},
"logit_adjustment": tau_sel,
"learning_curve": [{"model": k, "n": n, "accuracy": a, "macro_f1": f} for k, n, a, f in lc]}
(ART / "controls_results.json").write_text(json.dumps(res, indent=2))
for k, v in finals.items():
print(f" EVAL {k:<12} acc {(v.argmax(-1) == y_val).mean():.3f} macro F1 {macro_f1(y_val, v.argmax(-1)):.3f} {best[k][0]}")
for k, v in adjusted.items():
print(f" EVAL {k} logit-adjusted tau={tau_sel[k]['tau']}: acc {(v.argmax(-1) == y_val).mean():.3f} "
f"macro F1 {macro_f1(y_val, v.argmax(-1)):.3f}")
for k, n, a, f in lc:
print(f" CURVE {k:<10} n={n:>6} acc {a:.3f} macro F1 {f:.3f}")
print(" saved controls_val_probs.npz and controls_results.json")
if __name__ == "__main__":
main()
|