# -*- coding: utf-8 -*- """Baseline eval for PoetryMTEB/ClassicalChinesePoetryThemeClassification.""" 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 from sklearn.pipeline import Pipeline def main() -> None: p = argparse.ArgumentParser() p.add_argument("--repo", default="PoetryMTEB/ClassicalChinesePoetryThemeClassification") 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"] clf = Pipeline( [ ("tfidf", TfidfVectorizer(analyzer="char", ngram_range=(1, 3), max_features=50000)), ( "lr", LogisticRegression( max_iter=2000, random_state=args.seed, multi_class="multinomial" ), ), ] ) clf.fit(list(train["poem"]), list(train["label"])) pred = clf.predict(list(test["poem"])) y_test = list(test["label"]) id2name = {int(a): b for a, b in zip(train["label"], train["label_name"])} target_names = [id2name[i] for i in sorted(id2name)] 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(train), "n_test": len(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(args.out_json).write_text( json.dumps(metrics, ensure_ascii=False, indent=2), encoding="utf-8" ) if __name__ == "__main__": main()