File size: 2,812 Bytes
464033f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""Baseline evaluation for PoetryMTEB/FSPC (holistic 5-class sentiment).



Metrics: accuracy, macro-F1, micro-F1.

Default probe: TF-IDF + LogisticRegression (no GPU required).



Usage:

  python evaluate_fspc.py

  python evaluate_fspc.py --repo PoetryMTEB/FSPC --max-features 50000

"""
from __future__ import annotations

import argparse
import json
from collections import Counter

from datasets import load_dataset
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, f1_score, classification_report
from sklearn.pipeline import Pipeline


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument("--repo", default="PoetryMTEB/FSPC")
    p.add_argument("--max-features", type=int, default=50000)
    p.add_argument("--seed", type=int, default=42)
    p.add_argument("--out-json", default="")
    args = p.parse_args()

    ds = load_dataset(args.repo)
    train, test = ds["train"], ds["test"]
    x_train = list(train["poem"])
    y_train = list(train["label"])
    x_test = list(test["poem"])
    y_test = list(test["label"])
    id2name = {}
    for lab, name in zip(train["label"], train["label_name"]):
        id2name[int(lab)] = name
    target_names = [id2name[i] for i in sorted(id2name)]

    clf = Pipeline(
        [
            (
                "tfidf",
                TfidfVectorizer(
                    analyzer="char",
                    ngram_range=(1, 3),
                    max_features=args.max_features,
                ),
            ),
            (
                "lr",
                LogisticRegression(
                    max_iter=2000,
                    random_state=args.seed,
                    multi_class="multinomial",
                ),
            ),
        ]
    )
    clf.fit(x_train, y_train)
    pred = clf.predict(x_test)

    metrics = {
        "accuracy": float(accuracy_score(y_test, pred)),
        "macro_f1": float(f1_score(y_test, pred, average="macro")),
        "micro_f1": float(f1_score(y_test, pred, average="micro")),
        "n_train": len(y_train),
        "n_test": len(y_test),
        "label_counts_test": dict(Counter(int(x) for x in y_test)),
        "report": classification_report(
            y_test, pred, target_names=target_names, digits=4
        ),
    }
    print(json.dumps({k: v for k, v in metrics.items() if k != "report"}, indent=2))
    print(metrics["report"])
    if args.out_json:
        Path = __import__("pathlib").Path
        Path(args.out_json).write_text(
            json.dumps(metrics, ensure_ascii=False, indent=2), encoding="utf-8"
        )


if __name__ == "__main__":
    main()