| 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"] 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() |
|
|