Download evaluate.mjs from sumankrsh/scam-sms-classifier-mini: direct link, hf CLI and curl.
- Browser
- Download file 8.71 kB
-
https://huggingface.co/sumankrsh/scam-sms-classifier-mini/resolve/main/evaluate.mjs
- Command line
-
hf download hf://sumankrsh/scam-sms-classifier-mini/evaluate.mjs
-
curl -L -o evaluate.mjs https://huggingface.co/sumankrsh/scam-sms-classifier-mini/resolve/main/evaluate.mjs
8.71 kB
| // Score rules only, model only and combined, with the same JavaScript the web page runs. | |
| // | |
| // node evaluate.mjs validation tune the combination threshold on the validation split; writes combine.json | |
| // node evaluate.mjs heldout score the held-out split ONCE; writes heldout_report.json and EVALUATION.md | |
| // | |
| // "Flagged" means the verdict is "Looks like a scam" or "Be careful". Split files come from train.py | |
| // (default cache folder ~/.cache/scam-sms-classifier-mini/splits; override with SPLITS_DIR). | |
| // Built by Suman Mukherjee. Apache-2.0. | |
| import { readFileSync, writeFileSync, existsSync } from "node:fs"; | |
| import { homedir } from "node:os"; | |
| import { join } from "node:path"; | |
| import { fileURLToPath } from "node:url"; | |
| import { checkRules, combine, THRESHOLDS } from "./js/rules.js"; | |
| import { loadModel } from "./js/scam_model.js"; | |
| const here = fileURLToPath(new URL(".", import.meta.url)); | |
| const split = process.argv[2]; | |
| if (!["validation", "heldout"].includes(split)) { console.error("usage: node evaluate.mjs validation|heldout"); process.exit(2); } | |
| const dir = process.env.SPLITS_DIR || join(homedir(), ".cache", "scam-sms-classifier-mini", "splits"); | |
| const rows = readFileSync(join(dir, `${split}.jsonl`), "utf8").split("\n").filter(Boolean).map((l) => JSON.parse(l)); | |
| const modelJson = JSON.parse(readFileSync(join(here, "model.json"), "utf8")); | |
| const model = loadModel(modelJson); | |
| function metrics(pairs) { | |
| let tp = 0, fp = 0, fn = 0, tn = 0; | |
| for (const [y, f] of pairs) { | |
| if (f && y) tp++; else if (f && !y) fp++; else if (!f && y) fn++; else tn++; | |
| } | |
| const precision = tp + fp ? tp / (tp + fp) : 0; | |
| const recall = tp + fn ? tp / (tp + fn) : 0; | |
| const f1 = precision + recall ? (2 * precision * recall) / (precision + recall) : 0; | |
| const r4 = (x) => Math.round(x * 10000) / 10000; | |
| return { messages: pairs.length, positives: tp + fn, negatives: fp + tn, precision: r4(precision), recall: r4(recall), f1: r4(f1), tp, fp, fn, tn }; | |
| } | |
| const scored = rows.map((r) => { | |
| const rules = checkRules(r.text); | |
| const { p } = model.predict(r.text); | |
| return { ...r, rules, p }; | |
| }); | |
| function evaluate(cfg) { | |
| const out = {}; | |
| const groups = { all: scored, uci: scored.filter((s) => s.source === "uci"), synthetic: scored.filter((s) => s.source === "synthetic") }; | |
| for (const [g, list] of Object.entries(groups)) { | |
| out[g] = { | |
| rules_only: metrics(list.map((s) => [s.label, s.rules.verdict !== "allow"])), | |
| model_only: metrics(list.map((s) => [s.label, s.p >= modelJson.threshold])), | |
| combined: metrics(list.map((s) => [s.label, combine(s.rules, s.p, cfg).verdict !== "allow"])), | |
| }; | |
| } | |
| return out; | |
| } | |
| if (split === "validation") { | |
| // Parity check: the JavaScript probabilities must match scikit-learn's on every validation message. | |
| const sk = readFileSync(join(dir, "validation_sklearn_proba.txt"), "utf8").trim().split("\n").map(Number); | |
| let maxDiff = 0; | |
| scored.forEach((s, i) => { maxDiff = Math.max(maxDiff, Math.abs(s.p - sk[i])); }); | |
| console.log(`parity: max |p_js - p_sklearn| over ${sk.length} validation messages = ${maxDiff.toExponential(2)}`); | |
| if (maxDiff > 1e-3) { console.error("FAIL parity"); process.exit(1); } | |
| // Tune the combination on validation: a model score at or above t adds 2 points to the rule score. | |
| let best = null; | |
| for (let t = 0.05; t <= 0.951; t += 0.01) { | |
| const cfg = { threshold: Math.round(t * 100) / 100, points: 2 }; | |
| const m = evaluate(cfg).all.combined; | |
| if (!best || m.f1 > best.m.f1 + 1e-9 || (Math.abs(m.f1 - best.m.f1) < 1e-9 && cfg.threshold > best.cfg.threshold)) best = { cfg, m }; | |
| } | |
| const report = evaluate(best.cfg); | |
| const combineCfg = { ...best.cfg, tuned_on: "validation", rule_thresholds: THRESHOLDS, parity_max_abs_diff: maxDiff }; | |
| writeFileSync(join(here, "combine.json"), JSON.stringify(combineCfg, null, 2) + "\n"); | |
| const prev = JSON.parse(readFileSync(join(here, "validation_report.json"), "utf8")); | |
| prev.js = { combine: combineCfg, results: report }; | |
| writeFileSync(join(here, "validation_report.json"), JSON.stringify(prev, null, 2) + "\n"); | |
| console.log("combine.json:", JSON.stringify(combineCfg)); | |
| for (const g of ["all", "uci", "synthetic"]) for (const k of ["rules_only", "model_only", "combined"]) { | |
| const m = report[g][k]; | |
| console.log(`validation ${g.padEnd(9)} ${k.padEnd(10)} P ${m.precision.toFixed(3)} R ${m.recall.toFixed(3)} F1 ${m.f1.toFixed(3)} tp ${m.tp} fp ${m.fp} fn ${m.fn} tn ${m.tn}`); | |
| } | |
| process.exit(0); | |
| } | |
| // ---- Held-out: scored once ------------------------------------------------------------------------ | |
| const reportPath = join(here, "heldout_report.json"); | |
| if (existsSync(reportPath) && !process.argv.includes("--i-know-this-rescores-the-heldout-split")) { | |
| console.error("heldout_report.json already exists: the held-out split has been scored. Not scoring it again."); | |
| process.exit(1); | |
| } | |
| const cfg = JSON.parse(readFileSync(join(here, "combine.json"), "utf8")); | |
| const results = evaluate(cfg); | |
| const byCategory = {}; | |
| for (const s of scored.filter((x) => x.source === "synthetic")) { | |
| const c = (byCategory[s.category] ||= { label: s.label ? "scam" : "genuine", messages: 0, rules_flagged: 0, model_flagged: 0, combined_flagged: 0 }); | |
| c.messages++; | |
| if (s.rules.verdict !== "allow") c.rules_flagged++; | |
| if (s.p >= modelJson.threshold) c.model_flagged++; | |
| if (combine(s.rules, s.p, cfg).verdict !== "allow") c.combined_flagged++; | |
| } | |
| const verdicts = { deny: 0, review: 0, allow: 0 }; | |
| const verdictsByLabel = { scam: { ...verdicts }, genuine: { ...verdicts } }; | |
| for (const s of scored) verdictsByLabel[s.label ? "scam" : "genuine"][combine(s.rules, s.p, cfg).verdict]++; | |
| const report = { | |
| split: "heldout", scored_on: new Date().toISOString().slice(0, 10), flagged_means: "verdict is 'Looks like a scam' or 'Be careful'", | |
| model_threshold: modelJson.threshold, combine: cfg, results, combined_verdicts_by_label: verdictsByLabel, synthetic_by_category: byCategory, | |
| }; | |
| writeFileSync(reportPath, JSON.stringify(report, null, 2) + "\n"); | |
| const pct = (x) => (x * 100).toFixed(1) + "%"; | |
| const line = (name, m) => `| ${name} | ${pct(m.precision)} | ${pct(m.recall)} | ${pct(m.f1)} | ${m.tp} | ${m.fp} | ${m.fn} | ${m.tn} |`; | |
| const table = (g) => ["| Method | Precision | Recall | F1 | Scams flagged | Genuine flagged | Scams missed | Genuine passed |", "|---|---|---|---|---|---|---|---|", | |
| line("Rules only", results[g].rules_only), line("Model only", results[g].model_only), line("Combined (what the page shows)", results[g].combined)].join("\n"); | |
| const a = results.all.combined; | |
| const md = `# Held-out evaluation: scam-sms-classifier-mini and the scam-message-checker rules | |
| Scored once on ${report.scored_on} with \`node evaluate.mjs heldout\`, using the same JavaScript as the web page | |
| (\`js/rules.js\`, \`js/scam_model.js\`, \`model.json\`, \`combine.json\`). Nothing was tuned on this split. | |
| "Flagged" means the page would show **Looks like a scam** or **Be careful**. The positive class is UCI "spam" or synthetic "scam". | |
| Model threshold ${modelJson.threshold} and combination threshold ${cfg.threshold} (+${cfg.points} points) were chosen on the validation split. | |
| ## All held-out messages (${a.messages}: ${a.positives} spam or scam, ${a.negatives} genuine) | |
| ${table("all")} | |
| ## UCI SMS Spam Collection part (${results.uci.combined.messages} messages; real English SMS, mostly UK spam and Singapore ham) | |
| ${table("uci")} | |
| ## Synthetic India-style part (${results.synthetic.combined.messages} messages; templates never used in training or validation) | |
| ${table("synthetic")} | |
| ## Synthetic held-out by category (flagged / messages) | |
| | Category | Kind | Messages | Rules | Model | Combined | | |
| |---|---|---|---|---|---| | |
| ${Object.entries(byCategory).sort().map(([k, c]) => `| ${k} | ${c.label} | ${c.messages} | ${c.rules_flagged} | ${c.model_flagged} | ${c.combined_flagged} |`).join("\n")} | |
| ## Combined verdicts on held-out | |
| | | Looks like a scam | Be careful | No common scam signs found | | |
| |---|---|---|---| | |
| | Spam or scam | ${verdictsByLabel.scam.deny} | ${verdictsByLabel.scam.review} | ${verdictsByLabel.scam.allow} | | |
| | Genuine | ${verdictsByLabel.genuine.deny} | ${verdictsByLabel.genuine.review} | ${verdictsByLabel.genuine.allow} | | |
| ## Caveats | |
| - Small and partly synthetic. The synthetic messages and the rules were written by the same person, which flatters the rules on the synthetic part. | |
| - UCI "spam" includes ordinary promotions, not only scams, and dates from around 2012. It is not Indian SMS. | |
| - Real-world accuracy on today's messages is unknown. Treat the tool as a second opinion, not a guarantee. | |
| `; | |
| writeFileSync(join(here, "EVALUATION.md"), md); | |
| console.log(md); | |