File size: 9,325 Bytes
4bc63c7
 
 
 
 
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
4bc63c7
 
35d4b41
4bc63c7
 
 
ac3a340
 
 
 
 
 
 
4bc63c7
 
 
35d4b41
 
 
 
 
 
 
 
 
 
 
4bc63c7
 
 
 
 
 
 
 
 
 
ac3a340
 
35d4b41
 
 
 
4bc63c7
35d4b41
 
4bc63c7
 
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
 
4bc63c7
 
 
 
 
 
 
 
35d4b41
 
4bc63c7
 
ac3a340
35d4b41
 
4bc63c7
ac3a340
4bc63c7
 
 
35d4b41
 
4bc63c7
 
 
 
ac3a340
 
 
 
4bc63c7
 
 
35d4b41
4bc63c7
35d4b41
 
 
 
 
 
 
 
 
4bc63c7
 
35d4b41
4bc63c7
35d4b41
 
 
 
 
 
 
 
 
4bc63c7
 
 
35d4b41
 
4bc63c7
 
 
 
35d4b41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4bc63c7
 
 
35d4b41
4bc63c7
 
 
 
 
 
 
 
 
 
35d4b41
 
 
 
 
 
 
 
 
 
4bc63c7
 
 
 
 
 
 
 
 
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
200
201
202
203
204
205
206
207
"""Measure how much of the corpus the router understands, per variety and per level."""

import argparse
import json
import os
import sys
from collections import defaultdict
from typing import Dict, List

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

from lingologos_thinkingpython import (  # noqa: E402
    catalog,
    intent,
    lexicon,
    ngram,
)
RESULTS_DIR = os.path.join(ROOT, "results")
CORPUS_DIR = os.path.join(ROOT, "corpus")
DEFAULT_OUT = os.path.join(RESULTS_DIR, "coverage.json")


def load_rows(path: str) -> List[Dict]:
    """Accept one path or several, separated by commas."""
    rows: List[Dict] = []
    for one in [p.strip() for p in str(path).split(",") if p.strip()]:
        with open(one, "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) -> List[float]:
    """Wilson score interval for a proportion, so a 25-row variety is not read as a fact."""
    if not n:
        return [0.0, 0.0]
    p = k / n
    denom = 1.0 + z * z / n
    centre = (p + z * z / (2 * n)) / denom
    half = z * ((p * (1 - p) / n + z * z / (4 * n * n)) ** 0.5) / denom
    return [round(max(0.0, centre - half), 4), round(min(1.0, centre + half), 4)]


def measure(rows_: List[Dict]) -> Dict:
    frames = {entry["id"]: entry.get("frames", []) for entry in catalog.load_entries()}
    by_lang_frames: Dict[str, Dict[str, List[str]]] = {}
    for lang in lexicon.LANGS:
        merged = defaultdict(list)
        for frame, phrases in lexicon.load(lang)["frames"].items():
            merged[frame] = phrases
        by_lang_frames[lang] = dict(merged)

    stats = {"total": 0, "understood": 0, "correct": 0, "refused_expected": 0,
             "refused_correct": 0, "answered": 0, "correct_in_scope": 0,
             "by_lang": {}, "by_level": {}}
    per_lang = defaultdict(lambda: {"n": 0, "correct": 0, "in_scope": 0, "answered": 0,
                                    "correct_in_scope": 0})
    per_level = defaultdict(lambda: {"n": 0, "correct": 0, "in_scope": 0, "answered": 0,
                                     "correct_in_scope": 0})
    confusion = defaultdict(int)
    model = ngram.load() if ngram.exists() else None
    second_opinions = 0

    for row in rows_:
        lang = row["lang"]
        ir = intent.route(row["text"], lang, by_lang_frames[lang])
        expected = row.get("frame") or ""
        stats["total"] += 1
        per_lang[lang]["n"] += 1
        per_level[row["level"]]["n"] += 1
        got = "" if ir.get("reason") else ir["frame"]
        if not got and ir.get("reason") == "NOT_UNDERSTOOD" and model is not None:
            # Same second opinion the intent node consults: the lexicon ranking first, the
            # classifier trained from the corpus only when the ranking abstains.
            voted, _gap = ngram.classify(model, lang, row["text"])
            if voted:
                got = voted
                second_opinions += 1
        if expected == "":
            stats["refused_expected"] += 1
            if got == "":
                stats["correct"] += 1
                stats["refused_correct"] += 1
                per_lang[lang]["correct"] += 1
                per_level[row["level"]]["correct"] += 1
            continue
        per_lang[lang]["in_scope"] += 1
        per_level[row["level"]]["in_scope"] += 1
        if got:
            stats["understood"] += 1
            stats["answered"] += 1
            per_lang[lang]["answered"] += 1
            per_level[row["level"]]["answered"] += 1
        if got == expected:
            stats["correct_in_scope"] += 1
            stats["correct"] += 1
            per_lang[lang]["correct"] += 1
            per_level[row["level"]]["correct"] += 1
            per_lang[lang]["correct_in_scope"] += 1
            per_level[row["level"]]["correct_in_scope"] += 1
        else:
            confusion["%s->%s" % (expected, got or "REFUSED")] += 1

    stats["top1"] = round(stats["correct"] / stats["total"], 4) if stats["total"] else 0.0
    in_scope = stats["total"] - stats["refused_expected"]
    stats["recall"] = round(stats["correct_in_scope"] / in_scope, 4) if in_scope else 0.0
    stats["precision"] = (round(stats["correct_in_scope"] / stats["answered"], 4)
                          if stats["answered"] else 0.0)
    stats["refusal"] = (round(stats["refused_correct"] / stats["refused_expected"], 4)
                        if stats["refused_expected"] else 0.0)
    for lang in sorted(per_lang):
        cell = per_lang[lang]
        stats["by_lang"][lang] = {
            "n": cell["n"],
            "in_scope": cell["in_scope"],
            "top1": round(cell["correct"] / cell["n"], 4) if cell["n"] else 0.0,
            "recall": (round(cell["correct_in_scope"] / cell["in_scope"], 4)
                       if cell["in_scope"] else 0.0),
            "precision": (round(cell["correct_in_scope"] / cell["answered"], 4)
                          if cell["answered"] else 0.0),
            "top1_ci95": wilson(cell["correct"], cell["n"]),
            "recall_ci95": wilson(cell["correct_in_scope"], cell["in_scope"]),
        }
    for level in sorted(per_level):
        cell = per_level[level]
        stats["by_level"][level] = {
            "n": cell["n"],
            "in_scope": cell["in_scope"],
            "top1": round(cell["correct"] / cell["n"], 4) if cell["n"] else 0.0,
            "recall": (round(cell["correct_in_scope"] / cell["in_scope"], 4)
                       if cell["in_scope"] else 0.0),
            "precision": (round(cell["correct_in_scope"] / cell["answered"], 4)
                          if cell["answered"] else 0.0),
            "top1_ci95": wilson(cell["correct"], cell["n"]),
            "recall_ci95": wilson(cell["correct_in_scope"], cell["in_scope"]),
        }
    spread = [stats["by_lang"][lang]["top1"] for lang in stats["by_lang"]]
    stats["worst_variety_gap"] = round(max(spread) - min(spread), 4) if spread else 0.0
    stats["second_opinions"] = second_opinions
    stats["model_margin"] = (model.get("margin") if model is not None else None)
    stats["confusion_top"] = sorted(confusion.items(), key=lambda kv: -kv[1])[:10]
    return stats


def evaluation_booklet(corpus: List[Dict]) -> Dict:
    """Section 7 of the specification: the contrastive set scored separately, per variety.

    The minimal pairs are the only rows that tell whether the router keeps the right frame
    when another frame's word is present, so they are reported apart from the aggregate.
    """
    booklet = {"generated_by": "tools/measure_coverage.py", "splits": {}}
    for name in ("train", "eval"):
        rows_split = [r for r in corpus if r.get("split") == name]
        contrastive = measure([r for r in rows_split if r["level"] == "L3"])
        booklet["splits"][name] = {
            "contrastive": {
                "n": contrastive["total"],
                "top1": contrastive["top1"],
                "per_variety": contrastive["by_lang"],
            },
            "refusal_per_variety": {
                lang: cell["top1"] for lang, cell in
                measure([r for r in rows_split if r.get("expected") == "REFUSED"]
                        )["by_lang"].items()
            },
            "levels": {level: cell for level, cell in measure(rows_split)["by_level"].items()},
            "confusion_top": measure(rows_split)["confusion_top"],
        }
    return booklet


def main(argv=None) -> int:
    parser = argparse.ArgumentParser(description="Measure corpus coverage.")
    parser.add_argument("--corpus", default=os.path.join(CORPUS_DIR, "corpus.jsonl"))
    parser.add_argument("--out", default=DEFAULT_OUT)
    args = parser.parse_args(argv)

    corpus = load_rows(args.corpus)
    stats = measure([r for r in corpus if r.get("split") == "train"])
    eval_stats = measure([r for r in corpus if r.get("split") == "eval"])
    result = {"all": stats, "eval": eval_stats}
    os.makedirs(RESULTS_DIR, exist_ok=True)
    with open(args.out, "w", encoding="utf-8", newline="\n") as handle:
        json.dump(result, handle, indent=2, sort_keys=True)
        handle.write("\n")
    if os.path.abspath(args.out) == os.path.abspath(DEFAULT_OUT):
        booklet = evaluation_booklet(corpus)
        with open(os.path.join(RESULTS_DIR, "evaluation.json"), "w",
                  encoding="utf-8", newline="\n") as handle:
            json.dump(booklet, handle, indent=2, sort_keys=True)
            handle.write("\n")
        print("evaluation.json written: eval contrastive n=%d top1=%.4f over %d varieties"
              % (booklet["splits"]["eval"]["contrastive"]["n"],
                 booklet["splits"]["eval"]["contrastive"]["top1"],
                 len(booklet["splits"]["eval"]["contrastive"]["per_variety"])))
    print(json.dumps({"eval_top1": eval_stats["top1"], "eval_refusal": eval_stats["refusal"],
                      "eval_contrastive": eval_stats["by_level"].get("L3", {}).get("top1"),
                      "worst_variety_gap": eval_stats["worst_variety_gap"],
                      "eval_by_lang": eval_stats["by_lang"]}, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())