"""Choose the "uncertain - needs expert review" confidence threshold for the shipped model, on VALIDATION only. Rule: the lowest threshold t (in 0.05 steps) at which answers with confidence >= t are right at least TARGET of the time on validation. Below t, the page says "uncertain" instead of a tier. The test set is used only afterwards, to report what the chosen threshold does there. Probabilities come from the shipped int8 ONNX model, scored one row at a time as the browser does. Usage: python threshold.py --model-dir export_v6 --data data_v6_systems --suffix v6 """ import argparse, json from pathlib import Path import numpy as np import onnxruntime as ort from transformers import AutoTokenizer from train_v4 import LABELS, load ROOT = Path(__file__).parent TARGET = 0.90 def probs(model_dir, xs): tok = AutoTokenizer.from_pretrained(model_dir) sess = ort.InferenceSession(str(Path(model_dir) / "onnx" / "model_quantized.onnx"), providers=["CPUExecutionProvider"]) names = {i.name for i in sess.get_inputs()} out = [] for x in xs: enc = tok(x, truncation=True, max_length=128, return_tensors="np") z = sess.run(None, {k: v.astype(np.int64) for k, v in enc.items() if k in names})[0][0] e = np.exp(z - z.max()); out.append(e / e.sum()) return np.array(out) def table(p, y, ts): conf, pred = p.max(1), p.argmax(1) rows = [] for t in ts: ans = conf >= t acc = float((pred[ans] == y[ans]).mean()) if ans.any() else float("nan") caught = int(((pred != y) & ~ans).sum()); errs = int((pred != y).sum()) sev = int(((y == 3) & np.isin(pred, [0, 1]) & ans).sum()) rows.append({"t": round(float(t), 2), "answered": round(float(ans.mean()), 3), "acc_answered": round(acc, 3), "errors_flagged": f"{caught}/{errs}", "severe_still_answered": sev}) return rows def main(): ap = argparse.ArgumentParser() ap.add_argument("--model-dir", required=True); ap.add_argument("--data", required=True); ap.add_argument("--suffix", required=True) a = ap.parse_args() md = ROOT / a.model_dir xva, yva = load(a.data, a.suffix, "val"); xte, yte = load(a.data, a.suffix, "test") pva, pte = probs(md, xva), probs(md, xte) ts = np.arange(0.30, 0.96, 0.05) tv = table(pva, np.array(yva), ts) ok = [r for r in tv if r["acc_answered"] >= TARGET] chosen = ok[0]["t"] if ok else None print(f"validation ({len(yva)} rows):"); [print(" ", r) for r in tv] print(f"\nchosen threshold (lowest t with answered accuracy >= {TARGET} on validation): {chosen}") res = {"target": TARGET, "threshold": chosen, "validation": tv} if chosen is not None: te = table(pte, np.array(yte), [chosen])[0] print(f"test ({len(yte)} rows) at t={chosen}: {te}") res["test_at_threshold"] = te (ROOT / f"results_{a.suffix}" / "threshold.json").write_text(json.dumps(res, indent=2)) if __name__ == "__main__": main()