Download code/experiments/scripts/compare.py from Nalarin/nalarin-multimodal-data: direct link, hf CLI and curl.
- Browser
- Download file 5.66 kB
-
https://huggingface.co/datasets/Nalarin/nalarin-multimodal-data/resolve/main/code/experiments/scripts/compare.py
- Command line
-
hf download hf://datasets/Nalarin/nalarin-multimodal-data/code/experiments/scripts/compare.py
-
curl -L -o compare.py https://huggingface.co/datasets/Nalarin/nalarin-multimodal-data/resolve/main/code/experiments/scripts/compare.py
5.66 kB
| """Bandingkan hasil beberapa run: macro-F1, per bahasa, CI, McNemar. | |
| Contoh: | |
| python experiments/scripts/compare.py a1_text_s42 b0_concat_s42 m1_late_s42 | |
| python experiments/scripts/compare.py --out experiments/results/comparison a1_text_s42 ... | |
| Semua run harus memakai test yang sama; skrip memeriksa `segment_id` dan `y_true` | |
| sebelum menghitung McNemar. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from itertools import combinations | |
| from pathlib import Path | |
| import numpy as np | |
| import pandas as pd | |
| ROOT = Path(__file__).resolve().parents[2] | |
| sys.path.insert(0, str(ROOT / "experiments")) | |
| import common # noqa: E402 | |
| def load_run(run_id: str) -> tuple[pd.DataFrame, dict]: | |
| directory = common.EXP / "runs" / run_id | |
| pred_path = directory / "predictions_test.parquet" | |
| if not pred_path.exists(): | |
| raise SystemExit(f"tidak ada {pred_path}") | |
| frame = pd.read_parquet(pred_path).sort_values("segment_id").reset_index(drop=True) | |
| metrics_path = directory / "metrics.json" | |
| metrics = json.loads(metrics_path.read_text(encoding="utf-8")) if metrics_path.exists() else {} | |
| return frame, metrics | |
| def codes(values: pd.Series, names: list[str]) -> np.ndarray: | |
| mapping = {name: index for index, name in enumerate(names)} | |
| return np.array([mapping[value] for value in values], dtype=np.int64) | |
| def main() -> int: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("run_ids", nargs="+") | |
| parser.add_argument("--out", type=Path, default=common.EXP / "results" / "comparison") | |
| args = parser.parse_args() | |
| if not args.run_ids: | |
| raise SystemExit("beri minimal satu run_id") | |
| names = common.labels() | |
| loaded = {run_id: load_run(run_id) for run_id in args.run_ids} | |
| reference = loaded[args.run_ids[0]][0] | |
| for run_id, (frame, _) in loaded.items(): | |
| if len(frame) != len(reference): | |
| raise SystemExit( | |
| f"{run_id}: {len(frame)} segmen != {len(reference)} pada {args.run_ids[0]}" | |
| ) | |
| if not (frame["segment_id"].to_numpy() == reference["segment_id"].to_numpy()).all(): | |
| raise SystemExit(f"{run_id}: himpunan segment_id berbeda dari {args.run_ids[0]}") | |
| if not (frame["y_true"].to_numpy() == reference["y_true"].to_numpy()).all(): | |
| raise SystemExit(f"{run_id}: y_true berbeda dari {args.run_ids[0]}") | |
| rows = [] | |
| for run_id, (frame, metrics) in loaded.items(): | |
| truth = codes(frame["y_true"], names) | |
| pred = codes(frame["y_pred"], names) | |
| language = frame["language"].to_numpy() | |
| id_mask = language == "id" | |
| overall = common.classification_metrics(truth, pred) | |
| id_only = common.classification_metrics(truth[id_mask], pred[id_mask]) | |
| ci = metrics.get("ci95") or {} | |
| rows.append({ | |
| "run_id": run_id, | |
| "n": len(frame), | |
| "macro_f1": overall["macro_f1"], | |
| "accuracy": overall["accuracy"], | |
| "ci_low": ci.get("low"), | |
| "ci_high": ci.get("high"), | |
| "n_boot": ci.get("n_boot"), | |
| "id_n": int(id_mask.sum()), | |
| "id_macro_f1": id_only["macro_f1"], | |
| "id_accuracy": id_only["accuracy"], | |
| }) | |
| pairs = [] | |
| for left, right in combinations(args.run_ids, 2): | |
| frame_left = loaded[left][0] | |
| frame_right = loaded[right][0] | |
| result = common.mcnemar_test( | |
| codes(frame_left["y_true"], names), | |
| codes(frame_left["y_pred"], names), | |
| codes(frame_right["y_pred"], names), | |
| ) | |
| pairs.append({"model_a": left, "model_b": right, **result}) | |
| args.out.mkdir(parents=True, exist_ok=True) | |
| summary = pd.DataFrame(rows) | |
| summary.to_csv(args.out / "summary.csv", index=False) | |
| mcnemar = pd.DataFrame(pairs) | |
| mcnemar.to_csv(args.out / "mcnemar.csv", index=False) | |
| lines = [ | |
| "# Perbandingan Model", | |
| "", | |
| f"Test: **{len(reference):,} segmen**. Semua run memakai `segment_id` dan " | |
| "`y_true` yang sama.", | |
| "", | |
| "| run | n | macro-F1 | 95% CI | accuracy | id n | id macro-F1 |", | |
| "|---|---:|---:|---|---:|---:|---:|", | |
| ] | |
| for row in rows: | |
| ci = ( | |
| f"[{row['ci_low']:.4f}, {row['ci_high']:.4f}]" | |
| if isinstance(row["ci_low"], float) and isinstance(row["ci_high"], float) | |
| else "-" | |
| ) | |
| lines.append( | |
| f"| {row['run_id']} | {row['n']:,} | {row['macro_f1']:.4f} | {ci} | " | |
| f"{row['accuracy']:.4f} | {row['id_n']:,} | {row['id_macro_f1']:.4f} |" | |
| ) | |
| lines += ["", "## McNemar", "", "| A | B | b01 | b10 | p |", "|---|---|---:|---:|---:|"] | |
| for pair in pairs: | |
| lines.append( | |
| f"| {pair['model_a']} | {pair['model_b']} | {pair['b01']} | {pair['b10']} | " | |
| f"{pair['p_value']:.4g} |" | |
| ) | |
| boots = sorted({row["n_boot"] for row in rows if row["n_boot"]}) | |
| lines += [ | |
| "", | |
| "CI = cluster bootstrap per `group_id`" | |
| + (f" ({boots[0]:,} resample)".replace(",", ".") if boots else " (tidak dijalankan)") + ".", | |
| "Angka `id` dilaporkan terpisah karena `en` hanya 23 segmen test.", | |
| "McNemar memakai prediksi berpasangan per `segment_id`.", | |
| ] | |
| (args.out / "comparison.md").write_text("\n".join(lines), encoding="utf-8") | |
| print(summary.to_string(index=False)) | |
| print(f"\nhasil: {args.out / 'comparison.md'}") | |
| return 0 | |
| if __name__ == "__main__": | |
| raise SystemExit(main()) | |