File size: 9,763 Bytes
0dff23d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
208
209
210
211
212
# CallOpeningDetX v0.1. Licence: CDLA-Permissive-2.0 (see LICENSE).
"""Score predictions on CallOpeningDetX (Python standard library only).

    python score.py --gold data/test.jsonl --pred my_preds.jsonl [--out scores.json] [--bootstrap 1000]

Prediction file: one JSON object per line, one per gold record:
    {"id": "...", "agent_identification": "present", "institution_identification": "present",
     "recording_notice": "possible_recording", "opening_coverage": "complete",
     "recording_purpose": ["quality", "training"],
     "spans": [{"start": 110, "end": 133, "type": "INST"}, ...]}          # optional; offsets in render(record)

Metrics, per subset and over the whole file:
- all_fields_exact: share of calls with all four fields and the purpose set right (headline);
- per field: accuracy and macro F1 (over the values present in gold or prediction);
- purpose micro / macro F1, on calls where gold or prediction has a notice;
- purpose and span metrics are null when there is nothing to measure (no notice anywhere; no span rows);
- evidence spans, typed: F1 overlap (a span counts if it touches a gold span of the same type) and exact (same
  start and end); rows without span supervision are left out;
- policy A / B agreement: the pass / fail / review decision from the prediction equals the one from gold
  (A accepts definite or possible recording, B only definite);
- all_fields_exact per construction tag, and a 95% bootstrap interval for all_fields_exact (calls resampled).
A missing prediction counts as wrong for every field ("<missing>").
"""
import argparse
import collections
import json
import random
import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent))
from render import gold_spans                                         # noqa: E402

FIELDS = {
    "agent_identification": ["present", "absent", "unclear"],
    "institution_identification": ["present", "absent", "unclear"],
    "recording_notice": ["definite_recording", "possible_recording", "monitoring_only", "none", "unclear"],
    "opening_coverage": ["complete", "incomplete", "unknown"],
}
PURPOSES = ["quality", "training", "security", "other", "not_stated", "unclear"]
NOTICE = {"definite_recording", "possible_recording", "monitoring_only"}
SPAN_TYPES = ["AGENT", "INST", "NOTICE", "PURPOSE", "NEGATED", "DISTRACTOR"]
MISSING = "<missing>"


def policy(lab, accept):
    if lab["opening_coverage"] != "complete":
        return "review"
    vals = [lab["agent_identification"], lab["institution_identification"], lab["recording_notice"]]
    if "unclear" in vals:
        return "review"
    if "absent" in vals[:2] or lab["recording_notice"] in ("none", "monitoring_only"):
        return "fail"
    return "pass" if lab["recording_notice"] in accept else "review"


def f1(tp, n_pred, n_gold):
    p = tp / n_pred if n_pred else 0.0
    r = tp / n_gold if n_gold else 0.0
    return 2 * p * r / (p + r) if p + r else 0.0


def macro_f1(gold, pred):
    out = []
    for c in sorted(set(gold) | set(pred)):
        tp = sum(g == c and p == c for g, p in zip(gold, pred))
        out.append(f1(tp, sum(p == c for p in pred), sum(g == c for g in gold)))
    return sum(out) / len(out) if out else 0.0


def exact(r, x):
    return all(r["labels"][f] == x.get(f) for f in FIELDS) and \
        sorted(r["labels"]["recording_purpose"]) == sorted(x.get("recording_purpose") or [])


def score(rows, preds):
    """rows: gold records; preds: prediction dicts in the same order."""
    m = {"n": len(rows)}
    f1s = []
    for f in FIELDS:
        g = [r["labels"][f] for r in rows]
        p = [x.get(f, MISSING) for x in preds]
        m[f"{f}_acc"] = sum(a == b for a, b in zip(g, p)) / len(g)
        m[f"{f}_macro_f1"] = macro_f1(g, p)
        f1s.append(m[f"{f}_macro_f1"])
    m["field_macro_f1_mean"] = sum(f1s) / len(f1s)
    m["all_fields_exact"] = sum(exact(r, x) for r, x in zip(rows, preds)) / len(rows)
    tp, npred, ngold = collections.Counter(), collections.Counter(), collections.Counter()
    for r, x in zip(rows, preds):
        if r["labels"]["recording_notice"] in NOTICE or x.get("recording_notice") in NOTICE:
            g, p = set(r["labels"]["recording_purpose"]), set(x.get("recording_purpose") or [])
            for v in PURPOSES:
                tp[v] += v in g and v in p
                npred[v] += v in p
                ngold[v] += v in g
    m["purpose_micro_f1"] = f1(sum(tp.values()), sum(npred.values()), sum(ngold.values()))
    used = [v for v in PURPOSES if ngold[v] or npred[v]]
    m["purpose_macro_f1"] = sum(f1(tp[v], npred[v], ngold[v]) for v in used) / len(used) if used else 0.0
    m["purpose_rows"] = sum(1 for r, x in zip(rows, preds)
                            if r["labels"]["recording_notice"] in NOTICE or x.get("recording_notice") in NOTICE)
    if not m["purpose_rows"]:                                 # no notice in gold or prediction: not measurable
        m["purpose_micro_f1"] = m["purpose_macro_f1"] = None
    ex = ov_p = ov_g = ng = npr = 0
    by = collections.defaultdict(lambda: [0, 0, 0, 0])
    span_rows = 0
    for r, x in zip(rows, preds):
        if r.get("span_supervision") is False:
            continue
        span_rows += 1
        gold = set(gold_spans(r))
        pred = {(s["start"], s["end"], s["type"]) for s in x.get("spans") or []}
        ng += len(gold)
        npr += len(pred)
        ex += len(gold & pred)
        ov_p += sum(any(t == t2 and s < e2 and e > s2 for s2, e2, t2 in gold) for s, e, t in pred)
        ov_g += sum(any(t == t2 and s < e2 and e > s2 for s2, e2, t2 in pred) for s, e, t in gold)
        for t in {t for *_, t in gold | pred}:
            gt = [g for g in gold if g[2] == t]
            pt = [p for p in pred if p[2] == t]
            by[t][0] += sum(any(s < e2 and e > s2 for s2, e2, _ in gt) for s, e, _ in pt)
            by[t][1] += len(pt)
            by[t][2] += len(gt)
            by[t][3] += sum(any(s < e2 and e > s2 for s2, e2, _ in pt) for s, e, _ in gt)
    m["span_rows"] = span_rows
    m["span_f1_exact"] = f1(ex, npr, ng)
    pp, rr = (ov_p / npr if npr else 0.0), (ov_g / ng if ng else 0.0)
    m["span_f1_overlap"] = 2 * pp * rr / (pp + rr) if pp + rr else 0.0
    m["span_f1_overlap_by_type"] = {}
    for t, (a, b, c, d) in sorted(by.items()):
        pp, rr = (a / b if b else 0.0), (d / c if c else 0.0)
        m["span_f1_overlap_by_type"][t] = 2 * pp * rr / (pp + rr) if pp + rr else 0.0
    if not span_rows:
        m["span_f1_exact"] = m["span_f1_overlap"] = None
    for name, accept in (("A", {"definite_recording", "possible_recording"}), ("B", {"definite_recording"})):
        m[f"policy_{name}_agree"] = sum(
            policy(r["labels"], accept) == policy({f: x.get(f, MISSING) for f in FIELDS}, accept)
            for r, x in zip(rows, preds)) / len(rows)
    return m


def bootstrap(rows, preds, n, random_state=13):
    if n <= 0:
        return None
    rng = random.Random(random_state)
    hits = [exact(r, x) for r, x in zip(rows, preds)]
    vals = sorted(sum(hits[rng.randrange(len(hits))] for _ in hits) / len(hits) for _ in range(n))
    return [vals[int(0.025 * n)], vals[int(0.975 * n) - 1]]


def rounded(v):
    if isinstance(v, float):
        return round(v, 4)
    if isinstance(v, dict):
        return {k: rounded(x) for k, x in v.items()}
    if isinstance(v, list):
        return [rounded(x) for x in v]
    return v


def evaluate(rows, pred_by_id, n_boot=1000):
    preds = [pred_by_id.get(r["id"], {}) for r in rows]
    res = {"missing_predictions": sum(r["id"] not in pred_by_id for r in rows)}
    groups = {"all": list(range(len(rows)))}
    for i, r in enumerate(rows):
        groups.setdefault(r["subset"], []).append(i)
    for g, idx in groups.items():
        rs, ps = [rows[i] for i in idx], [preds[i] for i in idx]
        res[g] = score(rs, ps)
        res[g]["all_fields_exact_ci95"] = bootstrap(rs, ps, n_boot)
        tags = collections.defaultdict(list)
        for i in idx:
            for t in rows[i]["construction"]:
                tags[t].append(i)
        res[g]["all_fields_exact_by_construction"] = {
            t: {"n": len(ii), "all_fields_exact": sum(exact(rows[i], preds[i]) for i in ii) / len(ii)}
            for t, ii in sorted(tags.items())}
    return rounded(res)


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--gold", required=True)
    ap.add_argument("--pred", required=True)
    ap.add_argument("--out")
    ap.add_argument("--bootstrap", type=int, default=1000)
    a = ap.parse_args()
    rows = [json.loads(x) for x in open(a.gold, encoding="utf-8")]
    pred = {}
    for x in open(a.pred, encoding="utf-8"):
        x = json.loads(x)
        pred[x["id"]] = x
    res = evaluate(rows, pred, a.bootstrap)
    if a.out:
        Path(a.out).write_text(json.dumps(res, indent=1) + "\n")
    print(f"missing predictions: {res['missing_predictions']}")

    def v(x):
        return "   n/a" if x is None else f"{x:6.3f}"
    print(f"{'subset':12s} {'n':>5s} {'exact':>6s} {'agent':>6s} {'inst':>6s} {'notice':>6s} {'cover':>6s} "
          f"{'purpF1':>6s} {'spanOv':>6s} {'spanEx':>6s} {'polA':>6s} {'polB':>6s}")
    for g, m in res.items():
        if g == "missing_predictions":
            continue
        print(f"{g:12s} {m['n']:5d} {m['all_fields_exact']:6.3f} {m['agent_identification_acc']:6.3f} "
              f"{m['institution_identification_acc']:6.3f} {m['recording_notice_acc']:6.3f} "
              f"{m['opening_coverage_acc']:6.3f} {v(m['purpose_micro_f1'])} {v(m['span_f1_overlap'])} "
              f"{v(m['span_f1_exact'])} {m['policy_A_agree']:6.3f} {m['policy_B_agree']:6.3f}")


if __name__ == "__main__":
    main()