Download scripts/hallucination_stats.py from legexbenchmark/code: direct link, hf CLI and curl.
- Browser
- Download file 2.49 kB
-
https://huggingface.co/datasets/legexbenchmark/code/resolve/main/scripts/hallucination_stats.py
- Command line
-
hf download hf://datasets/legexbenchmark/code/scripts/hallucination_stats.py
-
curl -L -o hallucination_stats.py https://huggingface.co/datasets/legexbenchmark/code/resolve/main/scripts/hallucination_stats.py
2.49 kB
| #!/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()) | |