File size: 8,761 Bytes
35d4b41
 
 
74acaf8
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74acaf8
 
 
 
35d4b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
74acaf8
35d4b41
 
 
 
 
74acaf8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35d4b41
74acaf8
35d4b41
 
 
 
74acaf8
35d4b41
 
74acaf8
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
"""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, character trigrams and four grams inside each token, and character
four to six grams across the whole request, then scores a request with a complement multinomial
naive Bayes in log space: a feature is scored by how much it belongs to one class against all
the others, not by its raw frequency. The wide character grams carry the shape of a phrase across a reworded
request, which the per token grams alone lose. 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
    joined = " " + " ".join(tokens) + " "
    for size in (4, 5, 6):
        for start in range(len(joined) - size + 1):
            counts["j:" + joined[start:start + size]] += 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,
                               "weights": complement_weights(bags, totals, vocab)}
    return {"alpha": ALPHA, "classes": sorted({label for bags in per_language.values()
                                               for label in bags}),
            "languages": languages}


def complement_weights(bags: Dict[str, Counter], totals: Dict[str, int],
                       vocab: int) -> Dict[str, Dict[str, float]]:
    """One signed log weight per feature and class (complement naive Bayes).

    A feature gets the log ratio between how often it appears in its own class and how often
    it appears in all the other classes together. The ratio form is what carries a request
    the corpus never worded this way: the raw multinomial log likelihood grows with the length
    of the request and with the frequency of the feature, so a common word drags a correct
    class down on a wording the class has only seen a few times.
    """
    everywhere: Counter = Counter()
    for bag in bags.values():
        everywhere.update(bag)
    labels = sorted(bags)
    others = max(1, len(labels) - 1)
    weights: Dict[str, Dict[str, float]] = {}
    for label in labels:
        bag = bags[label]
        own = totals[label] + ALPHA * vocab
        rest = sum(totals[other] for other in labels if other != label) + ALPHA * vocab * others
        weights[label] = {feature: math.log((times + ALPHA) / own)
                          - math.log((everywhere[feature] - times + ALPHA) / rest)
                          for feature, times in bag.items()}
    return weights


def score(model: Dict[str, Any], language: str, counts: Counter) -> List[Tuple[str, float]]:
    """Log score of every class, best first: prior plus the weights its features carry."""
    entry = model["languages"].get(language)
    if not entry:
        raise ModelError("no model trained for %s" % language)
    scored: List[Tuple[str, float]] = []
    for label, table in entry["weights"].items():
        value = entry["priors"][label]
        for feature, times in counts.items():
            value += times * table.get(feature, 0.0)
        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)