File size: 6,074 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
"""CP-4: Classical baselines on gold-test.

Baselines:
  - Random  (uniform 0/1)
  - Majority (always predict positive class)
  - RuleCue (any of: would, wish, should, could, need, please, if, hope, recommend, suggest, must, have to)
  - TF-IDF + Logistic Regression
  - TF-IDF + Linear SVM

Trains on gold_train (3-seed bootstrap), evaluates on gold_test.
Saves to work/results/classical.json
"""
from __future__ import annotations
import json, re
from pathlib import Path
import numpy as np
import pandas as pd
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.svm import LinearSVC
from sklearn.metrics import classification_report, f1_score, precision_score, recall_score, accuracy_score, confusion_matrix

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

RULE_PATTERN = re.compile(
    r"\b(would|wish(?:ed)?|should|could|need(?:s|ed)?|must|have to|please|hope(?:d)?|recommend(?:s|ed|ing)?|suggest(?:s|ed|ing)?|if|why don't|why not|why\s*(can't|aren't|isn't|doesn't|don't))\b",
    re.IGNORECASE
)


def load_splits():
    train = pd.read_csv(DATA / "gold_train.csv", low_memory=False)
    dev = pd.read_csv(DATA / "gold_dev.csv", low_memory=False)
    test = pd.read_csv(DATA / "gold_test.csv", low_memory=False)
    for df in (train, dev, test):
        df['text'] = df['text'].fillna('').astype(str)
        df['label'] = df['is_suggestion'].astype(int)
    return train, dev, test


def metrics(y_true, y_pred, label='pos'):
    return {
        'accuracy': float(accuracy_score(y_true, y_pred)),
        'macro_f1': float(f1_score(y_true, y_pred, average='macro', zero_division=0)),
        'pos_f1': float(f1_score(y_true, y_pred, pos_label=1, zero_division=0)),
        'pos_precision': float(precision_score(y_true, y_pred, pos_label=1, zero_division=0)),
        'pos_recall': float(recall_score(y_true, y_pred, pos_label=1, zero_division=0)),
        'confusion_matrix': confusion_matrix(y_true, y_pred).tolist(),
    }


def run_random(test, seed):
    rng = np.random.default_rng(seed)
    y_pred = rng.integers(0, 2, size=len(test))
    return metrics(test['label'].values, y_pred)


def run_majority(test):
    y_pred = np.ones(len(test), dtype=int)  # positive is majority by construction
    return metrics(test['label'].values, y_pred)


def run_rule(test):
    y_pred = test['text'].str.contains(RULE_PATTERN).astype(int).values
    return metrics(test['label'].values, y_pred)


def run_tfidf(train, test, model_kind='lr', seed=42):
    vec = TfidfVectorizer(ngram_range=(1, 3), min_df=2, max_df=0.9, sublinear_tf=True,
                          analyzer='word', max_features=80_000)
    X_train = vec.fit_transform(train['text'])
    X_test = vec.transform(test['text'])
    if model_kind == 'lr':
        clf = LogisticRegression(C=1.0, max_iter=2000, random_state=seed, n_jobs=-1)
    else:
        clf = LinearSVC(C=1.0, random_state=seed, max_iter=3000)
    clf.fit(X_train, train['label'])
    y_pred = clf.predict(X_test)
    m = metrics(test['label'].values, y_pred)
    # per-form F1 if test contains form info — we'll also evaluate per-form via the span_only positives
    return m, clf, vec


def per_form_f1(test, y_pred):
    res = {}
    for form in ['Direct imperative', 'Modal/deontic', 'Conditional', 'Optative',
                 'Interrogative', 'Comparative']:
        mask = (test['tier1_form'] == form) & (test['label'] == 1)
        # F1 on positives of this form: this is recall actually (since form is only set for positives)
        if mask.sum() > 0:
            res[form] = float((y_pred[mask.values] == 1).mean())
    return res


def main():
    print("=" * 70)
    print("CP-4: Classical baselines")
    print("=" * 70)
    train, dev, test = load_splits()
    print(f"Train {len(train)} / Dev {len(dev)} / Test {len(test)}; train pos rate {train['label'].mean():.3f}")

    results = {}
    seeds = [13, 42, 137]

    # Random
    rand_runs = [run_random(test, s) for s in seeds]
    results['Random'] = aggregate(rand_runs)

    # Majority
    results['Majority(pos)'] = run_majority(test)

    # Rule
    results['Rule(modal/wish/should/...)'] = run_rule(test)
    rule_pred = test['text'].str.contains(RULE_PATTERN).astype(int).values
    results['Rule(modal/wish/should/...)']['per_form_recall'] = per_form_f1(test, rule_pred)

    # TF-IDF + LR
    print("\nTF-IDF + LR (3 seeds)...")
    lr_runs = []
    for s in seeds:
        m, clf, vec = run_tfidf(train, test, 'lr', s)
        lr_runs.append(m)
    results['TFIDF+LR'] = aggregate(lr_runs)
    # Keep one model's per-form recall
    _, clf, vec = run_tfidf(train, test, 'lr', 42)
    y_pred = clf.predict(vec.transform(test['text']))
    results['TFIDF+LR']['per_form_recall'] = per_form_f1(test, y_pred)

    # TF-IDF + SVM
    print("TF-IDF + SVM (3 seeds)...")
    svm_runs = []
    for s in seeds:
        m, _, _ = run_tfidf(train, test, 'svm', s)
        svm_runs.append(m)
    results['TFIDF+SVM'] = aggregate(svm_runs)
    _, clf, vec = run_tfidf(train, test, 'svm', 42)
    y_pred = clf.predict(vec.transform(test['text']))
    results['TFIDF+SVM']['per_form_recall'] = per_form_f1(test, y_pred)

    print("\n--- Results ---")
    for name, m in results.items():
        if 'macro_f1_mean' in m:
            print(f"{name:30s}  macro-F1 {m['macro_f1_mean']:.3f}±{m['macro_f1_std']:.3f}  pos-F1 {m['pos_f1_mean']:.3f}")
        else:
            print(f"{name:30s}  macro-F1 {m['macro_f1']:.3f}  pos-F1 {m['pos_f1']:.3f}")

    # Save
    with (RES / "classical.json").open("w") as f:
        json.dump(results, f, indent=2)
    print(f"\nSaved {RES}/classical.json")
    print("CP-4 DONE.")


def aggregate(runs):
    keys = ['accuracy', 'macro_f1', 'pos_f1', 'pos_precision', 'pos_recall']
    out = {}
    for k in keys:
        vals = [r[k] for r in runs]
        out[f'{k}_mean'] = float(np.mean(vals))
        out[f'{k}_std'] = float(np.std(vals))
    return out


if __name__ == '__main__':
    main()