File size: 3,219 Bytes
e222dea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Exact-substring scoring.

A response is correct if the whole golden answer appears in it as one
contiguous, case-insensitive substring. No tokenisation, no word boundaries,
no stemming.

    is_correct = answer.lower() in response.lower()

See scripts/README.md for what this measures, where it gives false positives
and false negatives, and how it compares with word_overlap.py.

Usage:
    python exact_substring.py --responses my_model_english.csv
    python exact_substring.py --responses my_model_english.csv --out scored.csv

Input CSV: the language file from this dataset (columns `question`, `answer`,
`Domain`) with a `response` column added holding the model's raw output.
"""

import argparse
import sys

import pandas as pd

REQUIRED = ["question", "answer", "Domain", "response"]


def is_correct(answer, response):
    """The golden answer must appear as one contiguous run of characters."""
    return str(answer).lower() in str(response).lower()


def report(df, label):
    """Print per-domain and combined accuracy."""
    per_domain = df.groupby("Domain")["is_correct"].agg(["sum", "size"])

    print(f"\n{label}\n")
    print(f"{'Domain':<20} {'Correct':>8} {'Total':>7} {'Accuracy':>10}")
    print("-" * 48)
    for domain, row in per_domain.iterrows():
        acc = row["sum"] / row["size"] * 100
        print(f"{domain:<20} {int(row['sum']):>8} {int(row['size']):>7} {acc:>9.2f}%")

    correct, total = int(df["is_correct"].sum()), len(df)
    blank = int((df["response"].fillna("").astype(str).str.strip() == "").sum())
    print("-" * 48)
    print(f"{'COMBINED':<20} {correct:>8} {total:>7} {correct / total * 100:>9.2f}%")
    print("\nCombined is the micro-average over all pooled questions, which is")
    print("identical to weighting each domain by its size.")
    if blank:
        print(f"Blank responses: {blank} (scored incorrect)")


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--responses", required=True,
                    help="CSV with columns: question, answer, Domain, response")
    ap.add_argument("--out", help="Optional path to write per-question verdicts")
    args = ap.parse_args()

    df = pd.read_csv(args.responses)

    missing = [c for c in REQUIRED if c not in df.columns]
    if missing:
        sys.exit(f"Error: {args.responses} is missing column(s): {', '.join(missing)}\n"
                 f"Found: {', '.join(df.columns)}")

    # A blank answer would match every response vacuously; flag rather than
    # silently inflate the score.
    blank_answers = int((df["answer"].fillna("").astype(str).str.strip() == "").sum())
    if blank_answers:
        print(f"Warning: {blank_answers} row(s) have an empty golden answer. "
              f"These match any response and will score correct.", file=sys.stderr)

    df["is_correct"] = [is_correct(a, r) for a, r in zip(df["answer"], df["response"])]

    report(df, f"Exact substring — {args.responses}")

    if args.out:
        df.to_csv(args.out, index=False)
        print(f"\nPer-question verdicts written to {args.out}")


if __name__ == "__main__":
    main()