File size: 8,552 Bytes
991f3b9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
"""CP-10: Slice evaluation — analyze per-form, per-modifier, per-borderline,
per-specificity, per-industry, and length-bucket performance.

Reads predictions from work/models/preds_*.csv (HF-LLM outputs) and the trained-encoder
predictions from work/models/<model>/test_predictions_seed*.csv.

Outputs work/results/slices.json, plus heatmaps in work/figures/.
"""
from __future__ import annotations
import json, ast, glob
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.metrics import f1_score, accuracy_score
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

ROOT = Path("/home/aniket/praxis-benchmark")
WORK = ROOT / "work"
DATA = WORK / "data"
RES = WORK / "results"
FIG = WORK / "figures"
MODELS = WORK / "models"


def parse_list(s):
    if isinstance(s, list): return s
    if pd.isna(s): return []
    try:
        x = ast.literal_eval(str(s))
        if isinstance(x, list): return x
    except Exception: pass
    return []


def load_test():
    g = pd.read_csv(DATA / "gold_test.csv", low_memory=False)
    g['is_suggestion'] = g['is_suggestion'].astype(str).str.lower().isin(['true','1'])
    g['borderline'] = g['borderline'].astype(str).str.lower().isin(['true','1'])
    g['true'] = g['is_suggestion'].astype(int)
    g['tier2_list'] = g['tier2_modifiers'].apply(parse_list)
    g['text'] = g['text'].fillna('').astype(str)
    g['n_words'] = g['text'].str.split().apply(len)
    # Use gold_id as the praxis_id (predictions are saved with this column renamed)
    if 'gold_id' in g.columns and 'praxis_id' not in g.columns:
        g['praxis_id'] = g['gold_id']
    return g


def find_preds():
    out = {}
    # Encoder predictions
    for f in glob.glob(str(MODELS / "*/test_predictions_seed*.csv")):
        p = Path(f)
        model = p.parent.name
        seed = p.stem.split('seed')[-1]
        try:
            df = pd.read_csv(p)
            out.setdefault(f"enc_{model}", []).append((seed, df))
        except Exception:
            pass
    # HF LLM predictions
    for f in glob.glob(str(MODELS / "preds_hf_*.csv")):
        p = Path(f)
        try:
            df = pd.read_csv(p)
            mname = p.stem.replace('preds_hf_', '')
            out[f"llm_{mname}"] = [('zs', df)]
        except Exception:
            pass
    return out


def macro_f1(true, pred):
    return float(f1_score(true, pred, average='macro', zero_division=0))


def per_form(g, preds):
    out = {}
    for form in ['Direct imperative', 'Modal/deontic', 'Conditional', 'Optative',
                 'Interrogative', 'Comparative']:
        sub = g[g['tier1_form'] == form]
        if len(sub) < 5: continue
        m = sub['praxis_id'].isin(preds.index) if 'praxis_id' in sub.columns else None
        # join on praxis_id
        merged = sub.merge(preds.reset_index(), on='praxis_id', how='inner')
        if len(merged) == 0: continue
        # Recall on positives of this form
        recall = float(((merged['pred'] == 1) & (merged['true'] == 1)).sum() /
                       max((merged['true'] == 1).sum(), 1))
        out[form] = {'n': int(len(merged)), 'recall': recall}
    return out


def per_modifier(g, preds):
    out = {}
    for mod in ['Frustrated', 'Hedged', 'Backhanded', 'Sarcastic']:
        mask = g['tier2_list'].apply(lambda l: mod in l)
        sub = g[mask & (g['true'] == 1)]
        merged = sub.merge(preds.reset_index(), on='praxis_id', how='inner')
        if len(merged) < 5: continue
        out[mod] = {'n': int(len(merged)),
                    'recall': float((merged['pred'] == 1).mean())}
    return out


def per_specificity(g, preds):
    out = {}
    for spec in ['Vague', 'Specific', 'Very specific']:
        sub = g[(g['tier3_specificity'] == spec) & (g['true'] == 1)]
        merged = sub.merge(preds.reset_index(), on='praxis_id', how='inner')
        if len(merged) < 5: continue
        out[spec] = {'n': int(len(merged)),
                     'recall': float((merged['pred'] == 1).mean())}
    return out


def per_borderline(g, preds):
    out = {}
    for label, val in [('borderline', True), ('clear', False)]:
        sub = g[(g['borderline'].astype(bool) == val) & (g['true'] == 1)]
        merged = sub.merge(preds.reset_index(), on='praxis_id', how='inner')
        if len(merged) < 5: continue
        out[label] = {'n': int(len(merged)),
                      'recall': float((merged['pred'] == 1).mean())}
    return out


def per_macro(g, preds):
    out = {}
    for macro in g['macro_domain'].dropna().unique():
        sub = g[g['macro_domain'] == macro]
        merged = sub.merge(preds.reset_index(), on='praxis_id', how='inner')
        if len(merged) < 20: continue
        out[macro] = {
            'n': int(len(merged)),
            'macro_f1': macro_f1(merged['true'], merged['pred']),
            'pos_f1': float(f1_score(merged['true'], merged['pred'], pos_label=1, zero_division=0)),
        }
    return out


def per_length(g, preds, n_buckets=4):
    out = {}
    qs = g['n_words'].quantile(np.linspace(0, 1, n_buckets + 1)).values
    for i in range(n_buckets):
        lo, hi = qs[i], qs[i + 1]
        sub = g[(g['n_words'] >= lo) & (g['n_words'] <= hi if i == n_buckets - 1 else g['n_words'] < hi)]
        merged = sub.merge(preds.reset_index(), on='praxis_id', how='inner')
        if len(merged) < 20: continue
        out[f'L{i+1}_[{int(lo)}-{int(hi)}]'] = {
            'n': int(len(merged)),
            'macro_f1': macro_f1(merged['true'], merged['pred']),
        }
    return out


def per_industry(g, preds, min_n=20):
    out = {}
    for ind, sub in g.groupby('industry'):
        merged = sub.merge(preds.reset_index(), on='praxis_id', how='inner')
        if len(merged) < min_n: continue
        if len(set(merged['true'])) < 2: continue
        out[ind] = {'n': int(len(merged)),
                    'macro_f1': macro_f1(merged['true'], merged['pred'])}
    return out


def main():
    print("=" * 70); print("CP-10: Slice evaluation"); print("=" * 70)
    g = load_test()
    preds_dict = find_preds()
    print(f"Loaded gold-test {len(g)} rows; preds for {len(preds_dict)} models")

    results = {}
    for model_name, runs in preds_dict.items():
        # Average per-row across seeds
        if len(runs) == 1:
            df = runs[0][1]
            df['true'] = df['is_suggestion'].astype(str).str.lower().isin(['true','1']).astype(int) \
                if 'is_suggestion' in df.columns else df.get('label', 0)
        else:
            # Combine seeds: majority vote per row by praxis_id
            seed_dfs = [r[1] for r in runs]
            base = seed_dfs[0][['praxis_id', 'is_suggestion']].copy()
            for i, sdf in enumerate(seed_dfs):
                base[f'pred_s{i}'] = sdf.set_index('praxis_id').loc[base['praxis_id']]['pred'].values
            base['pred'] = base[[f'pred_s{i}' for i in range(len(seed_dfs))]].mean(axis=1).round().astype(int)
            base['true'] = base['is_suggestion'].astype(str).str.lower().isin(['true','1']).astype(int)
            df = base[['praxis_id', 'true', 'pred']]

        # need pred + praxis_id + true for downstream
        if 'praxis_id' not in df.columns:
            print(f"  skip {model_name}: no praxis_id")
            continue
        df = df[['praxis_id', 'pred']].set_index('praxis_id')

        # Compute slices
        merged_full = g.merge(df.reset_index(), on='praxis_id', how='inner')
        if len(merged_full) == 0:
            print(f"  skip {model_name}: no overlap (test_n={len(g)})")
            continue

        results[model_name] = {
            'n_overlap': int(len(merged_full)),
            'overall': {
                'macro_f1': macro_f1(merged_full['true'], merged_full['pred']),
                'pos_f1': float(f1_score(merged_full['true'], merged_full['pred'], pos_label=1, zero_division=0)),
            },
            'per_form_recall': per_form(g, df),
            'per_modifier_recall': per_modifier(g, df),
            'per_specificity_recall': per_specificity(g, df),
            'per_borderline_recall': per_borderline(g, df),
            'per_macro': per_macro(g, df),
            'per_length': per_length(g, df),
            'per_industry': per_industry(g, df),
        }
        print(f"  {model_name}: macro-F1 {results[model_name]['overall']['macro_f1']:.4f}, n_overlap={len(merged_full)}")

    (RES / "slices.json").write_text(json.dumps(results, indent=2, default=str))
    print(f"\nSaved {RES}/slices.json")
    print("CP-10 DONE.")


if __name__ == '__main__':
    main()