File size: 6,976 Bytes
89880f9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Computes Cohen's kappa and self-report consistency between two label files.

The two label files can be any combination of annotators: LLM-vs-LLM,
LLM-vs-human, or human-vs-human. Each CSV must have columns:
    row_idx, candidate_shard, human_label (or llm_label), agent_said_used_it

The "label" column can be either 'human_label' or 'llm_label'; both are read.
The kappa computation does not depend on which annotator type produced the
labels --- it measures agreement between whatever pair of label files
is passed on the command line.

Usage:
    python3 score_annotations.py judge_a.csv judge_b.csv
"""
import csv
import sys


def load_labels(path):
    """Return dict: (row_idx, candidate_shard) -> 'yes' / 'no' / 'unclear' / ''."""
    out = {}
    with open(path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            label = (row.get("llm_label") or row.get("human_label") or "").strip().lower()
            key = (row["row_idx"], row["candidate_shard"])
            out[key] = label
    return out


def agent_claim(path):
    out = {}
    with open(path, newline="", encoding="utf-8") as f:
        reader = csv.DictReader(f)
        for row in reader:
            key = (row["row_idx"], row["candidate_shard"])
            out[key] = row["agent_said_used_it"].strip().lower() == "yes"
    return out


def cohen_kappa(labels_a, labels_b, classes):
    """Cohen's kappa for categorical labels."""
    keys = [k for k in labels_a
            if k in labels_b
            and labels_a[k] in classes
            and labels_b[k] in classes]
    n = len(keys)
    if n == 0:
        return None, 0

    agree = sum(1 for k in keys if labels_a[k] == labels_b[k])
    p_o = agree / n

    p_e = 0.0
    for c in classes:
        p_a = sum(1 for k in keys if labels_a[k] == c) / n
        p_b = sum(1 for k in keys if labels_b[k] == c) / n
        p_e += p_a * p_b

    if p_e == 1.0:
        return (1.0 if p_o == 1.0 else 0.0), n
    return (p_o - p_e) / (1 - p_e), n


def confusion_matrix(labels_a, labels_b, classes, label_a="A", label_b="B"):
    keys = [k for k in labels_a
            if k in labels_b
            and labels_a[k] in classes
            and labels_b[k] in classes]
    matrix = {(ca, cb): 0 for ca in classes for cb in classes}
    for k in keys:
        matrix[(labels_a[k], labels_b[k])] += 1

    col = 12
    print(f"{'':>{col}}", end="")
    for cb in classes:
        print(f"{(label_b + ':' + cb):>{col}}", end="")
    print()
    for ca in classes:
        print(f"{(label_a + ':' + ca):>{col}}", end="")
        for cb in classes:
            print(f"{matrix[(ca, cb)]:>{col}}", end="")
        print()


def self_report_vs_labels(path_csv, annotator_label):
    claim = agent_claim(path_csv)
    labels = load_labels(path_csv)
    keys = [k for k in claim if k in labels and labels[k] in ("yes", "no")]
    tp = sum(1 for k in keys if claim[k] and labels[k] == "yes")
    fp = sum(1 for k in keys if claim[k] and labels[k] == "no")
    fn = sum(1 for k in keys if not claim[k] and labels[k] == "yes")
    tn = sum(1 for k in keys if not claim[k] and labels[k] == "no")
    total = tp + fp + fn + tn
    if total == 0:
        return None
    return {
        "annotator": annotator_label,
        "tp": tp, "fp": fp, "fn": fn, "tn": tn,
        "precision": tp / (tp + fp) if (tp + fp) else 0.0,
        "recall":    tp / (tp + fn) if (tp + fn) else 0.0,
        "accuracy":  (tp + tn) / total,
        "n": total,
    }


def annotator_name_from_path(path):
    base = path.rsplit("/", 1)[-1].rsplit(".", 1)[0]
    return base.replace("_labels", "").replace("_", "-")


def main():
    if len(sys.argv) != 3:
        print(f"Usage: {sys.argv[0]} annotator_a.csv annotator_b.csv")
        sys.exit(1)

    path_a, path_b = sys.argv[1], sys.argv[2]
    name_a = annotator_name_from_path(path_a)
    name_b = annotator_name_from_path(path_b)

    labels_a = load_labels(path_a)
    labels_b = load_labels(path_b)

    classes_strict = ["yes", "no"]
    classes_lenient = ["yes", "no", "unclear"]
    kappa_strict, n_strict = cohen_kappa(labels_a, labels_b, classes_strict)
    kappa_lenient, n_lenient = cohen_kappa(labels_a, labels_b, classes_lenient)

    keys_strict = [k for k in labels_a
                   if k in labels_b
                   and labels_a[k] in classes_strict
                   and labels_b[k] in classes_strict]
    agree_strict = sum(1 for k in keys_strict if labels_a[k] == labels_b[k])

    print("=" * 64)
    print("Inter-annotator agreement report")
    print("=" * 64)
    print(f"Annotator A: {name_a}   ({path_a})")
    print(f"Annotator B: {name_b}   ({path_b})")
    print()
    print("Pairs labelled by both annotators:")
    print(f"  yes/no only (strict):  {n_strict}")
    print(f"  including unclear:     {n_lenient}")
    print()
    if kappa_strict is not None:
        print(f"Strict  kappa (yes/no):  {kappa_strict:+.4f}")
    else:
        print("Strict  kappa: no comparable data")
    if kappa_lenient is not None:
        print(f"Lenient kappa (3-class): {kappa_lenient:+.4f}")
    else:
        print("Lenient kappa: no comparable data")
    if n_strict:
        print(f"Raw agreement (strict):  "
              f"{agree_strict}/{n_strict} = {agree_strict/n_strict:.1%}")
    print()
    print("Landis & Koch (1977) interpretation:")
    print("  <0.00 poor | 0.00-0.20 slight | 0.21-0.40 fair")
    print("  0.41-0.60 moderate | 0.61-0.80 substantial | 0.81-1.00 almost perfect")
    print()
    print("NOTE: Cohen's kappa measures inter-annotator agreement. The")
    print("annotator type (LLM or human) is determined by what produced")
    print("the input CSVs, not by this script. When one of the input")
    print("files contains human-produced labels, kappa is an LLM-vs-human")
    print("(or human-vs-human) agreement; when both are LLM-produced,")
    print("it is an inter-LLM agreement.")
    print()

    print("Confusion matrix (strict, yes/no only):")
    confusion_matrix(labels_a, labels_b, classes_strict,
                     label_a=name_a[:8], label_b=name_b[:8])
    print()

    print("=" * 64)
    print("Self-report vs annotator labels (weak validation)")
    print("=" * 64)
    for path in (path_a, path_b):
        r = self_report_vs_labels(path, annotator_name_from_path(path))
        if r is None:
            print(f"{path}: insufficient data")
            continue
        print(f"{r['annotator']} (n={r['n']}):")
        print(f"  self-report precision: {r['precision']:.3f}  "
              f"(when agent says 'used', how often does this annotator agree?)")
        print(f"  self-report recall:    {r['recall']:.3f}  "
              f"(of annotator-marked 'used', how many did agent self-report?)")
        print(f"  self-report accuracy:  {r['accuracy']:.3f}")
        print(f"    TP={r['tp']}  FP={r['fp']}  FN={r['fn']}  TN={r['tn']}")
        print()


if __name__ == "__main__":
    main()