File size: 5,556 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
"""
Are SemIf's probabilities useful features too? (interface-level test of the Jev features result)
================================================================================================
SemIf (bracket, bare labels) was run on a seeded 20,000-complaint subset of the fit set
(`semif_benchmark.py --variant bracket --fit-subset 20000`). On exactly that subset we fit, with one grid and a
stratified 10% selection slice (seed 42): TF-IDF; TF-IDF + Jev probabilities; TF-IDF + SemIf probabilities; and each
probability vector alone. The evaluation split is scored once. Both probability vectors use log(p + 0.005),
standardized, scaled by w. Designed after the main results were known (status B).

    uv run --no-project --with numpy --with scikit-learn --with scipy --with joblib --with datasets \\
        --with huggingface_hub --with typesafe-sdk python verification/semif_features.py
"""
import json
import sys
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, NUM_LABELS
from jev_benchmark import SEED, macro_f1
from jev_extended import jev_probs, jev_feats

N_SUB = 20000
ART = ROOT / "verification" / "jev_benchmark_artifacts"
SEM = ROOT / "verification" / "semif_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 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"])
    d = np.load(SEM / f"semif-qwen3.5-4b_bracket_fit{N_SUB}_probs.npz")
    rows = d["fit_idx"]; assert len(rows) == N_SUB
    sem_fit = d["probs"]; sem_val = np.load(SEM / "semif-qwen3.5-4b_bracket_val_probs.npz")["probs"]
    jev_fit = np.vstack([jev_probs("train")[0], jev_probs("test")[0]])[rows]; jev_val, _ = jev_probs("val")
    texts = [fit_texts[i] for i in rows]; y = y_fit[rows]
    counts = np.bincount(y, minlength=K)
    strat = y if counts[counts > 0].min() >= 2 else None
    tr, dev = train_test_split(np.arange(N_SUB), test_size=0.1, stratify=strat, random_state=SEED)

    vec_tr = TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2)).fit([texts[i] for i in tr])
    T_tr, T_dev = vec_tr.transform([texts[i] for i in tr]), vec_tr.transform([texts[i] for i in dev])
    vec = TfidfVectorizer(max_features=50000, sublinear_tf=True, ngram_range=(1, 2)).fit(texts)
    T_all, T_val = vec.transform(texts), vec.transform(val_texts)
    P = {"jev": (jev_feats(jev_fit), jev_feats(jev_val)), "semif": (jev_feats(sem_fit), jev_feats(sem_val))}

    def X(kind, T, Pb, sc, w):
        if kind == "tfidf":
            return T
        if kind in ("jev", "semif"):
            return sc.transform(Pb)
        return hstack([T, csr_matrix(sc.transform(Pb) * w)]).tocsr()

    grids = {"tfidf": [dict(C=C, class_weight=cw) for C in (1.0, 10.0, 30.0, 100.0) for cw in (None, "balanced")],
             **{k: [dict(C=C, class_weight=cw) for C in (0.01, 0.1, 1.0, 10.0) for cw in (None, "balanced")] for k in ("jev", "semif")},
             **{f"tfidf+{k}": [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)] for k in ("jev", "semif")}}
    src = lambda kind: kind.split("+")[-1] if kind != "tfidf" else None

    def score(kind, cfg):
        s = src(kind); sc = StandardScaler().fit(P[s][0][tr]) if s else None
        m = LogisticRegression(C=cfg["C"], class_weight=cfg["class_weight"], max_iter=2000).fit(
            X(kind, T_tr, P[s][0][tr] if s else None, sc, cfg.get("w")), y[tr])
        return kind, cfg, macro_f1(y[dev], m.predict(X(kind, T_dev, P[s][0][dev] if s else None, sc, cfg.get("w"))))
    res = Parallel(n_jobs=12)(delayed(score)(k, c) for k, cs in grids.items() for c in cs)
    best = {}
    for k, c, f in res:
        if k not in best or f > best[k][1]:
            best[k] = (c, f)

    def final(kind):
        cfg = best[kind][0]; s = src(kind); sc = StandardScaler().fit(P[s][0]) if s else None
        m = LogisticRegression(C=cfg["C"], class_weight=cfg["class_weight"], max_iter=2000).fit(
            X(kind, T_all, P[s][0] if s else None, sc, cfg.get("w")), y)
        out = np.zeros((len(y_val), K)); out[:, m.classes_] = m.predict_proba(X(kind, T_val, P[s][1] if s else None, sc, cfg.get("w")))
        return kind, out
    finals = dict(Parallel(n_jobs=5)(delayed(final)(k) for k in grids))
    np.savez_compressed(ART / f"semif_features_fit{N_SUB}_val_probs.npz", labels=y_val,
                        **{k.replace("+", "_"): v for k, v in finals.items()})
    out = {"n_fit": N_SUB, "selected": {k: {**best[k][0], "selection_macro_f1": best[k][1]} for k in best},
           "selection": [{"kind": k, **c, "macro_f1": f} for k, c, f in res]}
    (ART / f"semif_features_fit{N_SUB}_results.json").write_text(json.dumps(out, indent=2))
    for k, v in finals.items():
        p = v.argmax(-1)
        print(f"  EVAL {k:<12} acc {(p == y_val).mean():.3f} macro F1 {macro_f1(y_val, p):.3f} {best[k][0]}")


if __name__ == "__main__":
    main()