File size: 5,663 Bytes
6389ac1 | 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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 | """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())
|