File size: 3,466 Bytes
473c56f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python
"""classifier2: pooled logistic STACK (dethead_stack.pooled protocol, re-implemented to write here): fitted on CONTRA OOF +
DEV-A mean-heat sources (equal population weight, class-balanced), patient-grouped 5-fold OOF; final fit -> dev-test.
  cls2_stack.py --name N --heads h1[,h2..] [--extra p_d331_max,p_d331_mean,log_vox] [--novel 0|1] [--C 1.0]
Head inputs enter as logits; 'extra' are table columns (p_* as logits)."""
from __future__ import annotations
import argparse, sys
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import GroupKFold
sys.path.insert(0, str(Path(__file__).resolve().parent))
import cls2_common as Q   # noqa: E402
import cls2_eval as E     # noqa: E402


def lg(x):
    x = np.clip(np.asarray(x, float), 1e-4, 1 - 1e-4); return np.log(x / (1 - x))


def feats(df, heads, extra):
    cols = [lg(df["hs_" + h]) for h in heads]
    for c in extra:
        cols.append(lg(df[c]) if c.startswith("p_") else df[c].to_numpy(float))
    return np.c_[tuple(cols)]


def run(a):
    heads = a.heads.split(","); extra = [c for c in a.extra.split(",") if c]
    P = E.pops()
    out = {}
    for pop in ("contra", "dev", "test_prim", "test_lab"):
        tab = P[pop][0].copy()
        for h in heads:
            s = E.head_scores(h, "test" if pop.startswith("test") else pop)
            tab = tab.join(s.set_index(["key", "src", "cid"])["score"].rename("hs_" + h), on=["key", "src", "cid"])
        out[pop] = tab
    df = pd.concat([out["contra"].assign(_p="contra"), out["dev"].assign(_p="dev")], ignore_index=True)
    df = df[np.all([df["hs_" + h].notna() for h in heads], 0)].reset_index(drop=True)
    isc = (df["_p"] == "contra").to_numpy(); y = df["pos"].to_numpy()
    trm = (df["p_d331_max"] < 0.5).to_numpy() if a.novel else np.ones(len(df), bool)
    w = np.where(isc, 0.5 / (isc & trm).sum(), 0.5 / (~isc & trm).sum()) * trm.sum()
    X = feats(df, heads, extra)
    s = np.zeros(len(df))
    for tr, te in GroupKFold(5).split(X, y, df["key"]):
        tr = tr[trm[tr]]
        m = LogisticRegression(C=a.C, class_weight="balanced", max_iter=3000).fit(X[tr], y[tr], sample_weight=w[tr])
        s[te] = m.predict_proba(X[te])[:, 1]
    m = LogisticRegression(C=a.C, class_weight="balanced", max_iter=3000).fit(X[trm], y[trm], sample_weight=w[trm])
    print(a.name, "coef", np.round(m.coef_[0], 3), np.round(m.intercept_, 3))
    od = Q.OUT / "scores" / a.name; od.mkdir(parents=True, exist_ok=True)
    df["score"] = s
    df.loc[isc, ["key", "src", "cid", "score"]].to_pickle(Q.guard_write(od / "oof.pkl"))
    df.loc[~isc, ["key", "src", "cid", "score"]].to_pickle(Q.guard_write(od / "dev.pkl"))
    te = pd.concat([out["test_prim"], out["test_lab"]])
    o = te[["key", "src", "cid"]].copy(); o["score"] = m.predict_proba(feats(te, heads, extra))[:, 1]
    o.to_pickle(Q.guard_write(od / "test.pkl"))
    import pickle
    pickle.dump({"model": m, "heads": heads, "extra": extra, "novel": a.novel}, open(Q.guard_write(Q.OUT / "models" / f"{a.name}.pkl"), "wb"))


if __name__ == "__main__":
    ap = argparse.ArgumentParser(); ap.add_argument("--name", required=True); ap.add_argument("--heads", required=True)
    ap.add_argument("--extra", default="p_d331_max,p_d331_mean,log_vox"); ap.add_argument("--novel", type=int, default=0)
    ap.add_argument("--C", type=float, default=1.0)
    run(ap.parse_args())