Datasets:
File size: 7,301 Bytes
5237fbc | 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 | """Collect fine-tuning runs: choose lr per representation by mean validation AUC,
report test metrics over seeds, and write per-sample scores (seed-averaged)."""
import os, sys, json, glob
import numpy as np, pandas as pd
from sklearn.metrics import roc_auc_score, f1_score, accuracy_score, precision_recall_curve
H = sys.argv[1]; RN = sys.argv[2] if len(sys.argv) > 2 else "runs"; R = f"{H}/{RN}"
RES = f"{H}/results" if RN == "runs" else f"{H}/results_{RN}"; os.makedirs(RES, exist_ok=True)
runs = [json.load(open(f)) for f in sorted(glob.glob(f"{R}/*.json"))]
df = pd.DataFrame([dict(rep=r["rep"] + ("_scratch" if r.get("from_scratch") else ""), lr=r["lr"], seed=r["seed"], tag=r["tag"],
val_auc=r["val"]["auc"], test_auc=r["test"]["auc"], test_f1=r["test"]["f1"], test_acc=r["test"]["acc"],
test_prec=r["test"]["precision"], test_rec=r["test"]["recall"], best_epoch=r["best_epoch"],
trunc_test=r["truncated_frac"]["test"], n_missing=r["n_missing_rep"], sec=r["seconds"]) for r in runs])
df.to_csv(f"{RES}/all_runs.csv", index=False)
g = df.groupby(["rep", "lr"]).agg(n=("seed", "size"), val_auc=("val_auc", "mean"), test_auc=("test_auc", "mean"),
test_auc_sd=("test_auc", "std"), test_f1=("test_f1", "mean"), test_f1_sd=("test_f1", "std"),
test_acc=("test_acc", "mean"), best_epoch=("best_epoch", "mean"), trunc_test=("trunc_test", "first"),
n_missing=("n_missing", "first")).reset_index()
g.to_csv(f"{RES}/lr_sweep.csv", index=False)
best = g.loc[g.groupby("rep").val_auc.idxmax()].reset_index(drop=True)
def rec_at_prec(y, p, target):
pr, rc, th = precision_recall_curve(y, p)
ok = pr[:-1] >= target
if not ok.any(): return 0.0, None
i = np.argmax(np.where(ok, rc[:-1], -1)); return float(rc[i]), float(th[i])
def hi_fp(y, p, t): return int(((p >= t) & (y == 0)).sum())
base = pd.read_parquet(f"{H}/reps.parquet", columns=["id", "set", "label", "source_dir", "formula", "nsites", "nelements", "spacegroup"])
scores = base[base.set.isin(["val", "test"])].reset_index(drop=True)
rows = []
for _, b in best.iterrows():
tags = df[(df.rep == b.rep) & (df.lr == b.lr)].tag
P = pd.concat([pd.read_csv(f"{R}/{t}.pred.csv").set_index("id").prob.rename(t) for t in tags], axis=1)
col = "S_text_" + b.rep
scores[col] = scores.id.map(P.mean(1)); scores[col + "_sd"] = scores.id.map(P.std(1))
te = scores[(scores.set == "test") & scores[col].notna()]; va = scores[(scores.set == "val") & scores[col].notna()]
y, p = te.label.values, te[col].values
r99, _ = rec_at_prec(y, p, 0.99); r100, _ = rec_at_prec(y, p, 1.0)
_, t99v = rec_at_prec(va.label.values, va[col].values, 0.99)
row = dict(rep=b.rep, lr=b.lr, n_seeds=int(b.n), single_test_auc=b.test_auc, single_test_auc_sd=b.test_auc_sd,
single_test_f1=b.test_f1, single_test_f1_sd=b.test_f1_sd, ens_test_auc=roc_auc_score(y, p),
ens_test_f1=f1_score(y, p >= 0.5), ens_test_acc=accuracy_score(y, p >= 0.5), n_test=len(te),
recall_at_p99=r99, recall_at_p100=r100, trunc_test=b.trunc_test, n_missing=int(b.n_missing))
row.update({"fp_ge_0.9": hi_fp(y, p, 0.9), "fp_ge_0.95": hi_fp(y, p, 0.95), "fp_ge_0.99": hi_fp(y, p, 0.99), "fn_le_0.1": int(((p <= 0.1) & (y == 1)).sum())})
if t99v is not None:
sel = p >= t99v; row.update(valthr_p99=t99v, test_prec_at_valthr=float(y[sel].mean()) if sel.any() else None, test_rec_at_valthr=float((sel & (y == 1)).sum() / (y == 1).sum()))
rows.append(row)
summ = pd.DataFrame(rows); summ.to_csv(f"{RES}/summary.csv", index=False)
scores.to_csv(f"{RES}/test_scores.csv", index=False)
pd.set_option("display.width", 250); pd.set_option("display.max_columns", 40); pd.set_option("display.float_format", lambda x: f"{x:.4f}")
print(g.to_string(index=False)); print(); print(summ.T.to_string())
# error overlap between representations on test (threshold 0.5)
te = scores[scores.set == "test"]; cols = [c for c in scores.columns if c.startswith("S_text_") and not c.endswith("_sd")]
err = {c: set(te.id[(te[c] >= 0.5) != (te.label == 1)][te[c].notna()]) for c in cols}
print("\nerror overlap (Jaccard) / score correlation (Spearman)")
for i, a in enumerate(cols):
for b in cols[i + 1:]:
j = len(err[a] & err[b]) / max(1, len(err[a] | err[b]))
print(f" {a[7:]:24s} {b[7:]:24s} nerr {len(err[a]):4d} {len(err[b]):4d} both {len(err[a] & err[b]):4d} jaccard {j:.3f} spearman {te[[a, b]].corr(method='spearman').iloc[0, 1]:.3f}")
print("\nby negative source (test), mean score / AUC vs positives")
for c in cols:
out = []
for s in ["Ehull_5500", "CSPD", "phonon_structures"]:
x = te[(te.source_dir == s) | (te.label == 1)]; x = x[x[c].notna()]
out.append(f"{s}: auc {roc_auc_score(x.label, x[c]):.3f} (n_neg {(x.label == 0).sum()})")
print(f" {c[7:]:24s} " + " | ".join(out))
# ---- fusion of representations: mean of probabilities, and logistic regression on logits fitted on the validation set
from sklearn.linear_model import LogisticRegression
def logit(p): p = np.clip(p, 1e-6, 1 - 1e-6); return np.log(p / (1 - p))
va = scores[scores.set == "val"].copy(); te = scores[scores.set == "test"].copy()
for d_ in (va, te):
for c in cols: d_[c] = d_[c].fillna(d_["S_text_composition"])
frows = []
def report(name, pv, pt):
y = te.label.values; r99, _ = rec_at_prec(y, pt, 0.99); r100, _ = rec_at_prec(y, pt, 1.0)
_, t99v = rec_at_prec(va.label.values, pv, 0.99); sel = pt >= t99v
frows.append(dict(model=name, test_auc=roc_auc_score(y, pt), test_f1=f1_score(y, pt >= 0.5), test_acc=accuracy_score(y, pt >= 0.5),
recall_at_p99=r99, recall_at_p100=r100, test_prec_at_valthr99=float(y[sel].mean()), test_rec_at_valthr99=float((sel & (y == 1)).sum() / (y == 1).sum()),
fp_ge_09=hi_fp(y, pt, 0.9), fp_ge_099=hi_fp(y, pt, 0.99), n_err=int(((pt >= 0.5) != (y == 1)).sum())))
for c in cols: report(c[7:], va[c].values, te[c].values)
SETS = {"comp+slices": ["composition", "slices"], "comp+cif_p1": ["composition", "cif_p1"], "slices+cif_p1": ["slices", "cif_p1"],
"comp+slices+cif_p1": ["composition", "slices", "cif_p1"], "comp+slices+cif_sym": ["composition", "slices", "cif_symmetrized"],
"all6": [c[7:] for c in cols]}
for name, reps in SETS.items():
cc = ["S_text_" + r for r in reps]
if not all(c in scores for c in cc): continue
report("mean[" + name + "]", va[cc].mean(1).values, te[cc].mean(1).values)
lr = LogisticRegression(C=1.0, max_iter=1000).fit(logit(va[cc].values), va.label.values)
pt = lr.predict_proba(logit(te[cc].values))[:, 1]; pv = lr.predict_proba(logit(va[cc].values))[:, 1]
report("LR[" + name + "]", pv, pt)
if name in ("comp+slices+cif_p1", "all6"):
te["S_text_fused_" + name.replace("+", "_")] = pt; scores.loc[te.index, "S_text_fused_" + name.replace("+", "_")] = pt
print("LR coef", name, dict(zip(reps, lr.coef_[0].round(3))), "intercept", lr.intercept_.round(3))
F = pd.DataFrame(frows); F.to_csv(f"{RES}/fusion.csv", index=False); scores.to_csv(f"{RES}/test_scores.csv", index=False)
print("\nfusion (test set)"); print(F.to_string(index=False))
|