#@title 🔎 Self-check against scikit-learn — run me { display-mode: "form" }
from sklearn.metrics import (precision_score, recall_score, f1_score,
cohen_kappa_score)
# A small fixture with imbalance and a few mistakes — enough to catch bugs.
LAB = ["A1", "A2", "B1", "B2"]
g = ["A1", "A1", "A2", "A2", "B1", "B1", "B1", "B2", "B2", "B2"]
p = ["A1", "A2", "A2", "A2", "B1", "B1", "B2", "B2", "B2", "A2"]
ann_a = ["A1", "A2", "B1", "B1", "B2", "A1", "A2", "B2", "B1", "A1"]
ann_b = ["A1", "A2", "B1", "B2", "B2", "A2", "A2", "B2", "B1", "A1"]
TOL, results = 1e-9, []
def _chk(name, got, exp):
ok = abs(got - exp) < TOL
results.append(ok)
print(("✅" if ok else "❌"), f"{name:<22} yours={got:.6f} sklearn={exp:.6f}")
for label in LAB:
_chk(f"precision({label})", precision(g, p, label),
precision_score(g, p, labels=[label], average="micro", zero_division=0))
_chk(f"recall({label})", recall(g, p, label),
recall_score(g, p, labels=[label], average="micro", zero_division=0))
_chk(f"f1({label})", f1(g, p, label),
f1_score(g, p, labels=[label], average="micro", zero_division=0))
_chk("macro_f1", macro_f1(g, p, LAB),
f1_score(g, p, labels=LAB, average="macro", zero_division=0))
_chk("percent_agreement", percent_agreement(ann_a, ann_b),
sum(1 for x, y in zip(ann_a, ann_b) if x == y) / len(ann_a))
_chk("cohen_kappa", cohen_kappa(ann_a, ann_b), cohen_kappa_score(ann_a, ann_b))
print("-" * 55)
print(f"All {len(results)} checks passed ✅ — your metrics match scikit-learn."
if all(results) else
f"{results.count(False)} of {len(results)} checks FAILED — fix and re-run.")