File size: 7,078 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
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
"""A bag of n grams classifier trained from the corpus of this bundle (acceptance D1).

No pre trained model is used anywhere in this dataset: the classifier here counts word
unigrams, word bigrams and character trigrams and four grams, then scores a request with a
multinomial naive Bayes in log space. One model is trained per variety, because the feature
space of a Chinese request shares nothing with an Italian one. The class for a request that
is out of the catalog is a class of its own, so the same model that recognises a frame also
decides when to abstain.

The classifier is a second opinion: the intent node keeps the lexicon ranking, and only when
the ranking abstains does it ask this model. A margin on the log score gap decides how much
confidence the second opinion needs, and that margin is chosen on the eval split of the
corpus, never on a held out set.
"""

import json
import math
import os
import re
import sys
from collections import Counter, defaultdict
from typing import Any, Dict, Iterable, List, Optional, Tuple

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)

MODEL_PATH = os.path.join(ROOT, "models", "intent_model.json")
REFUSE = "__refuse__"
ALPHA = 0.1
WORD = re.compile(r"\w+", re.UNICODE)


class ModelError(Exception):
    pass


def features(text: str) -> Counter:
    """Counts of the n grams a request is made of, script independent."""
    tokens = WORD.findall(str(text or "").lower())
    counts: Counter = Counter()
    for token in tokens:
        counts["w:" + token] += 1
        for size in (3, 4):
            if len(token) >= size:
                for start in range(len(token) - size + 1):
                    counts["c:" + token[start:start + size]] += 1
    for first, second in zip(tokens, tokens[1:]):
        counts["b:" + first + " " + second] += 1
    return counts


def train(rows: Iterable[Dict[str, Any]]) -> Dict[str, Any]:
    """One naive Bayes per variety over the rows of the train split."""
    per_language: Dict[str, Dict[str, Counter]] = defaultdict(lambda: defaultdict(Counter))
    documents: Dict[str, Counter] = defaultdict(Counter)
    for row in rows:
        if row.get("split") != "train":
            continue
        language = row.get("lang") or ""
        label = row.get("frame") or REFUSE
        per_language[language][label].update(features(row.get("text", "")))
        documents[language][label] += 1
    languages: Dict[str, Any] = {}
    for language, bags in per_language.items():
        vocab = len({feature for bag in bags.values() for feature in bag})
        totals = {label: sum(bag.values()) for label, bag in bags.items()}
        corpus = sum(documents[language].values())
        priors = {label: math.log((documents[language][label] + 1)
                                  / (corpus + len(documents[language])))
                  for label in bags}
        languages[language] = {"vocab": vocab, "totals": totals, "priors": priors,
                               "counts": {label: dict(bag) for label, bag in bags.items()}}
    return {"alpha": ALPHA, "classes": sorted({label for bags in per_language.values()
                                               for label in bags}),
            "languages": languages}


def score(model: Dict[str, Any], language: str, counts: Counter) -> List[Tuple[str, float]]:
    """Log posterior of every class, best first."""
    entry = model["languages"].get(language)
    if not entry:
        raise ModelError("no model trained for %s" % language)
    alpha, vocab = model["alpha"], entry["vocab"]
    scored: List[Tuple[str, float]] = []
    for label, bag in entry["counts"].items():
        total = entry["totals"][label] + alpha * vocab
        value = entry["priors"][label]
        for feature, times in counts.items():
            value += times * math.log((bag.get(feature, 0) + alpha) / total)
        scored.append((label, value))
    scored.sort(key=lambda pair: (-pair[1], pair[0]))
    return scored


def classify(model: Dict[str, Any], language: str, text: str,
             margin: Optional[float] = None) -> Tuple[str, float]:
    """The frame the model votes for, or an empty string when it is not sure."""
    margin = float(model.get("margin", 8.0)) if margin is None else float(margin)
    scored = score(model, language, features(text))
    if not scored:
        return "", 0.0
    best, best_score = scored[0]
    gap = best_score - scored[1][1] if len(scored) > 1 else float("inf")
    if best == REFUSE or gap < margin:
        return "", gap
    return best, gap


def choose_margin(model: Dict[str, Any], rows: List[Dict[str, Any]],
                  grid: Tuple[float, ...] = (0.0, 1.0, 2.0, 3.0, 5.0, 8.0, 12.0, 20.0),
                  precision_floor: float = 0.999) -> Tuple[float, Dict[str, Any]]:
    """The smallest margin whose eval precision clears the floor.

    The grid is scored on the eval split of the corpus: the held out sets are never read
    here, so the margin cannot be tuned on the data the gates later measure.
    """
    scored_rows = []
    for row in rows:
        if row.get("split") != "eval":
            continue
        ranked = score(model, row.get("lang", ""), features(row.get("text", "")))
        if not ranked:
            continue
        best, best_score = ranked[0]
        gap = best_score - ranked[1][1] if len(ranked) > 1 else float("inf")
        scored_rows.append((row.get("frame") or "", best, gap))
    best_margin, best_report = grid[0], {}
    for margin in grid:
        answered = correct = in_scope = 0
        for expected, label, gap in scored_rows:
            got = "" if label == REFUSE or gap < margin else label
            if expected:
                in_scope += 1
                if got:
                    answered += 1
                if got == expected:
                    correct += 1
        precision = correct / answered if answered else 0.0
        report = {"margin": margin, "eval_in_scope": in_scope, "eval_answered": answered,
                  "eval_correct": correct, "eval_precision": round(precision, 4)}
        if best_report == "":
            best_margin, best_report = margin, report
        if precision >= precision_floor:
            return margin, report
    return best_margin, best_report


def save(model: Dict[str, Any], path: str = MODEL_PATH) -> int:
    os.makedirs(os.path.dirname(path), exist_ok=True)
    with open(path, "w", encoding="utf-8", newline="\n") as handle:
        json.dump(model, handle, ensure_ascii=False, sort_keys=True)
        handle.write("\n")
    return os.path.getsize(path)


def load(path: str = MODEL_PATH) -> Dict[str, Any]:
    if not os.path.isfile(path):
        raise ModelError("no trained model at %s: run tools/train_intent.py" % path)
    with open(path, "r", encoding="utf-8") as handle:
        model = json.load(handle)
    if "languages" not in model:
        raise ModelError("the model file is not a trained intent model")
    return model


def exists(path: str = MODEL_PATH) -> bool:
    return os.path.isfile(path)