lingologos-thinkingpython / tools /train_intent.py
tailot's picture
thinking-python: reference implementation, corpus and gates
35d4b41 verified
Raw History Blame Contribute Delete
6.35 kB
"""Train the intent classifier of the bundle from the bundle's own corpus (acceptance D1).
No pre trained model is downloaded or fine tuned: the counts come from corpus/corpus.jsonl,
the split marked train, and the margin that turns the classifier into a second opinion is
chosen on the split marked eval. The artifact is models/intent_model.json, a plain JSON
document with one multinomial naive Bayes per variety, and the measurement of that model on
the eval split lands in results/intent_model_eval.json.
python tools/train_intent.py # train, save, report
python tools/train_intent.py --check # the saved model matches the corpus
"""
import argparse
import json
import os
import sys
from collections import Counter, defaultdict
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
from lingologos_thinkingpython import ngram # noqa: E402
CORPUS = os.path.join(ROOT, "corpus", "corpus.jsonl")
RESULTS_DIR = os.path.join(ROOT, "results")
OUT = os.path.join(RESULTS_DIR, "intent_model_eval.json")
def load_rows(path: str):
rows = []
with open(path, "r", encoding="utf-8") as handle:
for line in handle:
if line.strip():
rows.append(json.loads(line))
return rows
def wilson(k: int, n: int, z: float = 1.96):
if n == 0:
return [0.0, 0.0]
p = k / n
denominator = 1 + z * z / n
centre = (p + z * z / (2 * n)) / denominator
half = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / denominator
return [round(max(0.0, centre - half), 4), round(min(1.0, centre + half), 4)]
def evaluate(model, rows, margin):
per_language = defaultdict(lambda: Counter())
overall = Counter()
for row in rows:
if row.get("split") != "eval":
continue
frame, _gap = ngram.classify(model, row.get("lang", ""), row.get("text", ""), margin)
expected = row.get("frame") or ""
cell = per_language[row.get("lang", "")]
cell["n"] += 1
overall["n"] += 1
if frame == expected:
cell["correct"] += 1
overall["correct"] += 1
if expected:
cell["in_scope"] += 1
overall["in_scope"] += 1
if frame:
cell["answered"] += 1
overall["answered"] += 1
if frame == expected:
cell["kept"] += 1
overall["kept"] += 1
else:
cell["refuse"] += 1
overall["refuse"] += 1
if not frame:
cell["refused"] += 1
overall["refused"] += 1
def view(cell):
return {"n": cell["n"],
"top1": round(cell["correct"] / cell["n"], 4) if cell["n"] else 0.0,
"top1_ci95": wilson(cell["correct"], cell["n"]),
"recall": (round(cell["kept"] / cell["in_scope"], 4)
if cell["in_scope"] else 0.0),
"recall_ci95": wilson(cell["kept"], cell["in_scope"]),
"precision": (round(cell["kept"] / cell["answered"], 4)
if cell["answered"] else 0.0),
"refusal": (round(cell["refused"] / cell["refuse"], 4)
if cell["refuse"] else 0.0)}
by_language = {language: view(cell) for language, cell in sorted(per_language.items())}
top = [cell["top1"] for cell in by_language.values()]
return {"margin": margin, "overall": view(overall), "by_language": by_language,
"top1_spread": round(max(top) - min(top), 4) if top else 0.0}
def main(argv=None) -> int:
parser = argparse.ArgumentParser(description="Train the intent classifier from the corpus.")
parser.add_argument("--corpus", default=CORPUS)
parser.add_argument("--model", default=ngram.MODEL_PATH)
parser.add_argument("--out", default=OUT)
parser.add_argument("--check", action="store_true",
help="re-train in memory and compare with the saved model")
args = parser.parse_args(argv)
if not os.path.isfile(args.corpus):
print("FAIL no corpus at %s" % args.corpus)
return 1
rows = load_rows(args.corpus)
model = ngram.train(rows)
margin, choice = ngram.choose_margin(model, rows)
model["margin"] = margin
report = evaluate(model, rows, margin)
report["margin_rule"] = ("smallest margin of the grid whose eval precision is at least "
"0.999, chosen on the eval split only")
report["margin_choice"] = choice
report["rows"] = {"train": sum(1 for r in rows if r.get("split") == "train"),
"eval": sum(1 for r in rows if r.get("split") == "eval")}
report["languages"] = sorted(model["languages"])
report["classes"] = len(model["classes"])
if args.check:
if not ngram.exists(args.model):
print("FAIL no saved model at %s" % args.model)
return 1
saved = ngram.load(args.model)
same = (saved.get("languages") == model.get("languages")
and saved.get("alpha") == model.get("alpha"))
print("check=%s languages=%d classes=%d"
% ("PASS" if same else "FAIL", len(model["languages"]), len(model["classes"])))
return 0 if same else 1
size = ngram.save(model, args.model)
os.makedirs(os.path.dirname(args.out), exist_ok=True)
with open(args.out, "w", encoding="utf-8", newline="\n") as handle:
json.dump(report, handle, indent=2, sort_keys=True, ensure_ascii=False)
handle.write("\n")
overall = report["overall"]
print("trained %d classes over %d varieties from %d train rows, model %d bytes"
% (report["classes"], len(report["languages"]), report["rows"]["train"], size))
print("margin=%.1f eval top1=%.4f recall=%.4f precision=%.4f refusal=%.4f spread=%.4f"
% (margin, overall["top1"], overall["recall"], overall["precision"],
overall["refusal"], report["top1_spread"]))
for language, cell in sorted(report["by_language"].items()):
print(" %s top1=%.4f recall=%.4f ci95=%s" % (language, cell["top1"], cell["recall"],
cell["recall_ci95"]))
return 0
if __name__ == "__main__":
raise SystemExit(main())