File size: 8,531 Bytes
667319c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Score the machine syntax layer against an independent manual correction.

The benchmark deliberately does not measure `conllu_machine` against the
treebank projects, because the point of the layer is to be agnostic to their
conventions. Instead a sample of published machine trees was corrected token by
token by a language model annotator (Claude Fable 5.1) following the Universal
Dependencies v2 guidelines and its own written conventions, without access to
any other annotation of those sentences. This script compares the parser's
output with that correction and reports:

* UAS, LAS and label accuracy for heads and dependency relations;
* precision, recall and F1 per UPOS tag, with micro and macro averages;
* precision, recall and F1 per FEATS key=value pair, with micro and macro
  averages, treating each token's features as a set.

Tokens are fixed, so every token is compared. A record appearing more than once
in the corrections file is taken from its last occurrence.
"""

from __future__ import annotations

import argparse
import json
from collections import Counter, defaultdict
from pathlib import Path


def load_jsonl(path: Path) -> dict[str, dict]:
    records: dict[str, dict] = {}
    with path.open(encoding="utf-8") as stream:
        for line in stream:
            if line.strip():
                record = json.loads(line)
                records[record["id"]] = record
    return records


def prf(tp: int, fp: int, fn: int) -> dict[str, float]:
    precision = tp / (tp + fp) if tp + fp else 0.0
    recall = tp / (tp + fn) if tp + fn else 0.0
    f1 = 2 * precision * recall / (precision + recall) if precision + recall else 0.0
    return {"precision": round(precision, 4), "recall": round(recall, 4), "f1": round(f1, 4),
            "support": tp + fn}


def label_scores(pairs: list[tuple[str, str]]) -> dict:
    """Per-label precision/recall/F1 for one gold/predicted label per token."""
    tp: Counter[str] = Counter()
    fp: Counter[str] = Counter()
    fn: Counter[str] = Counter()
    for gold, predicted in pairs:
        if gold == predicted:
            tp[gold] += 1
        else:
            fp[predicted] += 1
            fn[gold] += 1
    labels = sorted(set(tp) | set(fp) | set(fn))
    per_label = {label: prf(tp[label], fp[label], fn[label]) for label in labels}
    present = [label for label in labels if per_label[label]["support"]]
    macro = {
        key: round(sum(per_label[label][key] for label in present) / len(present), 4)
        for key in ("precision", "recall", "f1")
    } if present else {}
    accuracy = sum(tp.values()) / len(pairs) if pairs else 0.0
    return {"accuracy": round(accuracy, 4), "macro": macro, "per_label": per_label}


def set_scores(pairs: list[tuple[set[str], set[str]]]) -> dict:
    """Per-value precision/recall/F1 for a set of key=value features per token."""
    tp: Counter[str] = Counter()
    fp: Counter[str] = Counter()
    fn: Counter[str] = Counter()
    exact = 0
    for gold, predicted in pairs:
        if gold == predicted:
            exact += 1
        for value in gold & predicted:
            tp[value] += 1
        for value in predicted - gold:
            fp[value] += 1
        for value in gold - predicted:
            fn[value] += 1
    values = sorted(set(tp) | set(fp) | set(fn))
    per_value = {value: prf(tp[value], fp[value], fn[value]) for value in values}
    present = [value for value in values if per_value[value]["support"]]
    macro = {
        key: round(sum(per_value[value][key] for value in present) / len(present), 4)
        for key in ("precision", "recall", "f1")
    } if present else {}
    micro = prf(sum(tp.values()), sum(fp.values()), sum(fn.values()))
    by_key: dict[str, dict[str, int]] = defaultdict(Counter)
    for counter, name in ((tp, "tp"), (fp, "fp"), (fn, "fn")):
        for value, count in counter.items():
            by_key[value.split("=", 1)[0]][name] += count
    per_key = {key: prf(c["tp"], c["fp"], c["fn"]) for key, c in sorted(by_key.items())}
    return {
        "exact_set_accuracy": round(exact / len(pairs), 4) if pairs else 0.0,
        "micro": micro, "macro": macro, "per_key": per_key, "per_value": per_value,
    }


def feats_set(value) -> set[str]:
    if not value or value == "_":
        return set()
    return set(value.split("|"))


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--machine", type=Path, required=True, help="sampled machine trees (JSONL)")
    parser.add_argument("--corrected", type=Path, required=True, help="manual corrections (JSONL)")
    parser.add_argument("--conventions", type=Path, help="the annotator's conventions file, recorded by path")
    parser.add_argument("--output", type=Path, required=True)
    args = parser.parse_args()

    machine = load_jsonl(args.machine)
    corrected = load_jsonl(args.corrected)
    missing = sorted(set(machine) - set(corrected))
    if missing:
        raise SystemExit(f"{len(missing)} sampled sentences have no correction: {missing[:5]}")

    heads = deprels = both = tokens = 0
    upos_pairs: list[tuple[str, str]] = []
    deprel_pairs: list[tuple[str, str]] = []
    feats_pairs: list[tuple[set[str], set[str]]] = []
    changed_sentences = 0
    changed_tokens = 0
    by_author: dict[str, Counter] = defaultdict(Counter)
    for sentence_id, sample in machine.items():
        gold_tokens = corrected[sentence_id]["tokens"]
        predicted_tokens = sample["tokens"]
        assert len(gold_tokens) == len(predicted_tokens), sentence_id
        assert [t["form"] for t in gold_tokens] == [t["form"] for t in predicted_tokens], sentence_id
        sentence_changed = False
        for gold, predicted in zip(gold_tokens, predicted_tokens):
            tokens += 1
            head_ok = gold["head"] == predicted["head"]
            deprel_ok = gold["deprel"] == predicted["deprel"]
            heads += head_ok
            deprels += deprel_ok
            both += head_ok and deprel_ok
            upos_pairs.append((gold["upos"], predicted["upos"]))
            deprel_pairs.append((gold["deprel"], predicted["deprel"]))
            gold_feats, predicted_feats = feats_set(gold["feats"]), feats_set(predicted["feats"])
            feats_pairs.append((gold_feats, predicted_feats))
            token_changed = not (head_ok and deprel_ok and gold["upos"] == predicted["upos"]
                                 and gold_feats == predicted_feats)
            changed_tokens += token_changed
            sentence_changed = sentence_changed or token_changed
            author = by_author[sample["author"]]
            author["tokens"] += 1
            author["las"] += head_ok and deprel_ok
            author["upos"] += gold["upos"] == predicted["upos"]
        changed_sentences += sentence_changed

    report = {
        "annotator": "Claude Fable 5.1, manual token-by-token correction of the sampled machine trees, "
                     "without access to any other annotation of the sentences",
        "conventions": str(args.conventions) if args.conventions else None,
        "sentences": len(machine),
        "tokens": tokens,
        "sentences_with_any_correction": changed_sentences,
        "tokens_with_any_correction": changed_tokens,
        "dependency": {
            "uas": round(heads / tokens, 4),
            "las": round(both / tokens, 4),
            "label_accuracy": round(deprels / tokens, 4),
            "deprel": label_scores(deprel_pairs),
        },
        "upos": label_scores(upos_pairs),
        "feats": set_scores(feats_pairs),
        "by_author": {
            author: {
                "tokens": c["tokens"],
                "las": round(c["las"] / c["tokens"], 4),
                "upos_accuracy": round(c["upos"] / c["tokens"], 4),
            }
            for author, c in sorted(by_author.items())
        },
    }
    args.output.parent.mkdir(parents=True, exist_ok=True)
    args.output.write_text(json.dumps(report, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
    summary = {
        "sentences": report["sentences"], "tokens": tokens,
        "uas": report["dependency"]["uas"], "las": report["dependency"]["las"],
        "upos_accuracy": report["upos"]["accuracy"], "upos_macro_f1": report["upos"]["macro"].get("f1"),
        "feats_micro_f1": report["feats"]["micro"]["f1"], "feats_macro_f1": report["feats"]["macro"].get("f1"),
    }
    print(json.dumps(summary, indent=2))


if __name__ == "__main__":
    main()