File size: 1,726 Bytes
f78cbef
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from __future__ import annotations
import argparse
import csv
import json
from pathlib import Path
from sklearn.metrics import accuracy_score, f1_score


def read_rows(path: str):
    with open(path, encoding="utf-8", newline="") as f:
        return list(csv.DictReader(f))


def prediction_map(path: str):
    rows = read_rows(path)
    required = {"id", "prediction"}
    if not rows or not required.issubset(rows[0]):
        raise ValueError("Prediction CSV must contain columns: id,prediction")
    return {row["id"]: row["prediction"] for row in rows}


def save_or_print(metrics, output):
    text = json.dumps(metrics, ensure_ascii=False, indent=2)
    print(text)
    if output:
        Path(output).write_text(text + "\n", encoding="utf-8")


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--gold", required=True)
    parser.add_argument("--predictions", required=True)
    parser.add_argument("--output")
    args = parser.parse_args()
    gold_rows = read_rows(args.gold)
    preds = prediction_map(args.predictions)
    missing = [row["id"] for row in gold_rows if row["id"] not in preds]
    if missing:
        raise ValueError(f"Missing predictions for {len(missing)} IDs; first: {missing[:5]}")
    y_true = [row["label_id"] for row in gold_rows]
    y_pred = [str(preds[row["id"]]).strip() for row in gold_rows]
    if True:
        y_true = [int(x) for x in y_true]
        y_pred = [int(x) for x in y_pred]
    metrics = {
        "n_examples": len(y_true),
        "accuracy": accuracy_score(y_true, y_pred),
        "macro_f1": f1_score(y_true, y_pred, average="macro", zero_division=0),
    }
    save_or_print(metrics, args.output)


if __name__ == "__main__":
    main()