#!/usr/bin/env python3 """Agreement between the published labels and a second annotator's: Cohen's kappa, raw agreement, and the confusion of the disagreements. python3 scripts/kappa.py annotation/round-2/sample.csv """ import csv import sys from collections import Counter from common import ROLES, data, read_jsonl if len(sys.argv) != 2: sys.exit(__doc__) first = {l["id"]: l["role"] for l in read_jsonl(data("roles", "labels.jsonl"))} rows = [r for r in csv.DictReader(open(sys.argv[1], encoding="utf-8")) if r["role"].strip()] bad = [r["id"] for r in rows if r["role"].strip() not in ROLES or r["id"] not in first] if bad: sys.exit(f"unknown role or id: {', '.join(bad[:10])}") pairs = [(first[r["id"]], r["role"].strip()) for r in rows] n = len(pairs) if not n: sys.exit("no row has a role yet") po = sum(a == b for a, b in pairs) / n ca, cb = Counter(a for a, _ in pairs), Counter(b for _, b in pairs) pe = sum(ca[r] * cb[r] for r in ROLES) / (n * n) kappa = (po - pe) / (1 - pe) if pe < 1 else 1.0 print(f"{n} labels compared · agreement {100 * po:.1f} % · Cohen's kappa {kappa:.3f}") for (a, b), k in Counter((a, b) for a, b in pairs if a != b).most_common(): print(f" round 1 {a:<12} round 2 {b:<12} {k}")