File size: 4,624 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
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
"""
Word-overlap scoring.

A response is correct if every word of the golden answer appears somewhere in
it, in any order. Both sides are lowercased, split on whitespace, stripped of
leading and trailing punctuation, and compared as sets.

    is_correct = set(golden_words) <= set(response_words)

Extra words in the response are free: this is a subset test, not equality.
Because the comparison is set-based, repeated words in the golden answer
collapse to one.

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

Usage:
    python word_overlap.py --responses my_model_english.csv
    python word_overlap.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"]

# Stripped from the edges of each token. Includes the Devanagari danda and
# double danda alongside ASCII punctuation.
PUNCTUATION = " \t\n\r.,;:!?\"'()[]{}<>/\\|`~@#$%^&*-_=+।॥"


def words(text):
    """Lowercase, split on whitespace, strip edge punctuation, drop empties."""
    tokens = (t.strip(PUNCTUATION) for t in str(text).lower().split())
    return {t for t in tokens if t}


def score_row(answer, response):
    """Return (is_correct, matching_word_count, golden_word_count)."""
    golden, given = words(answer), words(response)
    matching = golden & given
    # An empty golden answer is vacuously satisfied.
    return len(matching) == len(golden), len(matching), len(golden)


def report(df, label):
    """Print per-domain and combined accuracy, plus word recall."""
    per_domain = df.groupby("Domain").agg(
        correct=("is_correct", "sum"),
        total=("is_correct", "size"),
        matched=("matching_words", "sum"),
        golden=("total_golden_words", "sum"),
    )

    print(f"\n{label}\n")
    print(f"{'Domain':<20} {'Correct':>8} {'Total':>7} {'Accuracy':>10} {'Word recall':>13}")
    print("-" * 62)
    for domain, row in per_domain.iterrows():
        acc = row["correct"] / row["total"] * 100
        recall = row["matched"] / row["golden"] * 100 if row["golden"] else 0.0
        print(f"{domain:<20} {int(row['correct']):>8} {int(row['total']):>7} "
              f"{acc:>9.2f}% {recall:>12.2f}%")

    correct, total = int(df["is_correct"].sum()), len(df)
    matched = int(df["matching_words"].sum())
    golden = int(df["total_golden_words"].sum())
    recall = matched / golden * 100 if golden else 0.0
    blank = int((df["response"].fillna("").astype(str).str.strip() == "").sum())

    print("-" * 62)
    print(f"{'COMBINED':<20} {correct:>8} {total:>7} "
          f"{correct / total * 100:>9.2f}% {recall:>12.2f}%")
    print("\nCombined is the micro-average over all pooled questions, which is")
    print("identical to weighting each domain by its size.")
    print(f"Word recall: {matched}/{golden} golden words found. This is partial")
    print("credit that the binary accuracy above hides.")
    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)}")

    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 are vacuously satisfied and will score correct.", file=sys.stderr)

    scored = [score_row(a, r) for a, r in zip(df["answer"], df["response"])]
    df["is_correct"] = [s[0] for s in scored]
    df["matching_words"] = [s[1] for s in scored]
    df["total_golden_words"] = [s[2] for s in scored]

    report(df, f"Word overlap — {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()