File size: 2,338 Bytes
fdd86d9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# -*- coding: utf-8 -*-
"""Baseline evaluation for PoetryMTEB/MultilingualPoetryThemeClassification.



Usage:

  python evaluate_theme.py --test-config silver

  python evaluate_theme.py --test-config gold

"""
from __future__ import annotations

import argparse
import json
from collections import Counter
from pathlib import Path

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


def main() -> None:
    p = argparse.ArgumentParser()
    p.add_argument(
        "--repo",
        default="PoetryMTEB/MultilingualPoetryThemeClassification",
    )
    p.add_argument("--test-config", default="silver", choices=["silver", "gold"])
    p.add_argument("--out-json", default="")
    args = p.parse_args()

    train_ds = load_dataset(args.repo, "train", split="train")
    test_ds = load_dataset(args.repo, args.test_config, split="test")

    x_train = [r["poem"] for r in train_ds]
    x_test = [r["poem"] for r in test_ds]
    y_train = [int(r["label"]) for r in train_ds]
    y_test = [int(r["label"]) for r in test_ds]

    vec = TfidfVectorizer(analyzer="char_wb", ngram_range=(3, 5), min_df=2)
    xt = vec.fit_transform(x_train)
    xs = vec.transform(x_test)

    clf = LogisticRegression(max_iter=2000, n_jobs=-1)
    clf.fit(xt, y_train)
    pred = clf.predict(xs)

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


if __name__ == "__main__":
    main()