File size: 5,109 Bytes
0e6d825
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Scorers for sentence boundaries (M1) and entities on character spans (M4), with paired bootstrap.

Sentence boundaries. A document is its text plus the character offsets where sentences end. Offsets are compared
in whitespace-free coordinates, so a system that puts a boundary before or after the separating space, or trims
spaces, is not penalised; the document's own end is not a boundary (every system gets it for free). Reports
boundary precision, recall and F1, and also "space-correct" (accuracy over the space characters of the text, the
older Thai metric) only for comparison with old papers: it mostly rewards not splitting.

Entities. Gold and system entities are (start, end, type) character spans of the same text; exact match of all
three, micro-averaged; also per-type F1 and the type-blind span F1.
"""

from __future__ import annotations

from collections import Counter
from dataclasses import dataclass, field


def nows_offsets(text: str) -> list[int]:
    """Map each character offset 0..len(text) to its offset in the whitespace-free text."""
    out, k = [], 0
    for ch in text:
        out.append(k)
        if not ch.isspace():
            k += 1
    out.append(k)
    return out


def boundaries(text: str, ends: list[int]) -> set[int]:
    """Sentence ends (character offsets into `text`) as whitespace-free positions, document end excluded."""
    m = nows_offsets(text)
    total = m[-1]
    return {m[e] for e in ends if 0 < m[e] < total}


@dataclass
class DocCounts:
    gold: int = 0
    system: int = 0
    correct: int = 0
    spaces: int = 0
    spaces_correct: int = 0


def sentence_counts(text: str, gold_ends: list[int], sys_ends: list[int]) -> DocCounts:
    g, s = boundaries(text, gold_ends), boundaries(text, sys_ends)
    c = DocCounts(gold=len(g), system=len(s), correct=len(g & s))
    m = nows_offsets(text)
    for i, ch in enumerate(text):
        if ch == " ":  # a space is a gold/system break when a boundary falls at its position
            c.spaces += 1
            c.spaces_correct += (m[i] in g) == (m[i] in s)
    return c


def sentence_summary(counts: list[DocCounts]) -> dict[str, float]:
    G = sum(c.gold for c in counts)
    S = sum(c.system for c in counts)
    C = sum(c.correct for c in counts)
    p = C / S if S else 0.0
    r = C / G if G else 0.0
    sp = sum(c.spaces for c in counts)
    return {"precision": 100 * p, "recall": 100 * r, "f1": 100 * (2 * p * r / (p + r) if p + r else 0.0),
            "gold": G, "system": S, "space_correct": 100 * sum(c.spaces_correct for c in counts) / sp if sp else 0.0}


@dataclass
class EntCounts:
    gold: int = 0
    system: int = 0
    correct: int = 0
    span_correct: int = 0
    by_type: Counter = field(default_factory=Counter)  # (type, "g"|"s"|"c") -> n


def entity_counts(gold: list[tuple[int, int, str]], system: list[tuple[int, int, str]]) -> EntCounts:
    g, s = set(gold), set(system)
    c = EntCounts(gold=len(g), system=len(s), correct=len(g & s),
                  span_correct=len({(a, b) for a, b, _ in g} & {(a, b) for a, b, _ in s}))
    for a, b, t in g:
        c.by_type[(t, "g")] += 1
    for a, b, t in s:
        c.by_type[(t, "s")] += 1
    for a, b, t in g & s:
        c.by_type[(t, "c")] += 1
    return c


def entity_summary(counts: list[EntCounts]) -> dict:
    def f1(cor: int, gol: int, sysn: int) -> float:
        p, r = (cor / sysn if sysn else 0.0), (cor / gol if gol else 0.0)
        return 100 * (2 * p * r / (p + r) if p + r else 0.0)

    G, S, C = (sum(getattr(c, k) for c in counts) for k in ("gold", "system", "correct"))
    SC = sum(c.span_correct for c in counts)
    bt: Counter = Counter()
    for c in counts:
        bt.update(c.by_type)
    types = sorted({t for t, _ in bt})
    per = {t: f1(bt[(t, "c")], bt[(t, "g")], bt[(t, "s")]) for t in types}
    return {"f1": f1(C, G, S), "span_f1": f1(SC, G, S), "macro_f1": sum(per.values()) / len(per) if per else 0.0,
            "per_type": per, "gold": G, "system": S}


def paired_bootstrap_f1(a: list, b: list, n: int = 10000, seed: int = 112) -> dict[str, float]:
    """Micro-F1 difference a - b with a 95% interval, resampling documents (DocCounts or EntCounts lists)."""
    import numpy as np

    xa = np.array([[c.correct, c.gold, c.system] for c in a], float)
    xb = np.array([[c.correct, c.gold, c.system] for c in b], float)

    def f1(x: np.ndarray) -> np.ndarray:
        c, g, s = x[..., 0], x[..., 1], x[..., 2]
        p = np.divide(c, s, out=np.zeros_like(c), where=s > 0)
        r = np.divide(c, g, out=np.zeros_like(c), where=g > 0)
        return np.divide(2 * p * r, p + r, out=np.zeros_like(p), where=(p + r) > 0)

    rng = np.random.default_rng(seed)
    idx = rng.integers(0, len(a), (n, len(a)))
    diffs = f1(xa[idx].sum(1)) - f1(xb[idx].sum(1))
    base = float(f1(xa.sum(0)) - f1(xb.sum(0)))
    lo, hi = np.percentile(diffs, [2.5, 97.5])
    p = 2 * float(np.mean(diffs <= 0)) if base > 0 else (2 * float(np.mean(diffs >= 0)) if base < 0 else 1.0)
    return {"diff": 100 * base, "lo": 100 * float(lo), "hi": 100 * float(hi), "p": min(p, 1.0)}