File size: 6,346 Bytes
35d4b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
"""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())