File size: 2,488 Bytes
2e511b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Aggregate the published hallucination review into the Figure 3 numbers.

Reads ``data/analysis/hallucinations/hallucination_review_ch.csv`` (one row
per flagged (case, field, model) cell over the 30 Swiss judgments with the
highest flagged-cell counts; see ``scripts/export_hallucination_review.py``)
and prints the per-category shares and the two derived brackets shown in the
paper's hallucination figure.

Usage:  uv run python scripts/hallucination_stats.py
"""

import argparse
import csv
from collections import Counter
from pathlib import Path

DEFAULT_CSV = Path("data/analysis/hallucinations/hallucination_review_ch.csv")

CATEGORY_LABELS = {
    "A": "Fabrication (genuine hallucination)",
    "B": "Misattribution (genuine hallucination)",
    "C": "Gold-set gap (value present in judgment)",
    "D": "Defensible coding (value present in judgment)",
    "E": "Refusal",
}


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("--csv", type=Path, default=DEFAULT_CSV)
    parser.add_argument("--per-model", action="store_true",
                        help="additionally break the categories down per system")
    args = parser.parse_args(argv)

    with args.csv.open(newline="", encoding="utf-8") as f:
        rows = list(csv.DictReader(f))
    n = len(rows)
    counts = Counter(r["category"] for r in rows)
    cases = {r["case_id"] for r in rows}

    print(f"n = {n} flagged (case, field, model) cells over {len(cases)} judgments")
    for cat in sorted(CATEGORY_LABELS):
        c = counts.get(cat, 0)
        print(f"  {cat}  {CATEGORY_LABELS[cat]:<45} {c:>3}  {100 * c / n:.1f}%")
    ab = counts.get("A", 0) + counts.get("B", 0)
    cd = counts.get("C", 0) + counts.get("D", 0)
    print(f"  A+B  Genuine hallucination                        {ab:>3}  {100 * ab / n:.1f}%")
    print(f"  C+D  Value present in judgment / gold-set gap     {cd:>3}  {100 * cd / n:.1f}%")

    if args.per_model:
        by_model: dict[str, Counter] = {}
        for r in rows:
            by_model.setdefault(r["model"], Counter())[r["category"]] += 1
        print()
        for model, c in sorted(by_model.items()):
            total = sum(c.values())
            cats = "  ".join(f"{k}:{c.get(k, 0)}" for k in sorted(CATEGORY_LABELS))
            print(f"  {model:<30} n={total:<4} {cats}")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())