Makron-code / analysis /error_analysis.py
Urdatorn's picture
Error analysis for the runs/final-v2 models with silver buckets from 5d737f8; previous version kept as *.final-880b94a.md
e08ea84 verified
Raw History Blame Contribute Delete
8.54 kB
'''
Error analysis on Norma test (or validation) for the three final seeds and the
rule-based grc-macronizer.
Inputs:
- runs/final/seed{1,2,3}/eval/*.<split>.positions.jsonl (evaluate.py)
- results/rule-based/rule-based.<split>.positions.jsonl (rule_based.py)
- analysis/silver_overlap.per_vowel.jsonl (silver_overlap.py run on
oga-macronized-no-norma vs Norma): for every gold dichronon, how often its
word form (lowercased, grave->acute) occurs in the silver data and how often
the silver labels mark that vowel short / long.
Silver buckets per gold position:
- labelled: the form occurs in silver and that vowel is labelled there
(split further by whether the silver majority label equals gold);
- unlabelled: the form occurs in silver, but the vowel is never labelled;
- unseen: the form never occurs in silver.
Period groups: Classical = Alcman to Plato; Hellenistic and later = the rest.
python analysis/error_analysis.py --split test > analysis/error_analysis.test.md
'''
import argparse, collections, glob, json, os, unicodedata
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
CLASSICAL = {"partheneion", "supplices", "oedipus", "cyclops", "acharnenses", "aristophanes",
"bacchylides", "thucydides", "cratylus"}
AUTHOR = {"partheneion": "Alcman, Partheneion", "supplices": "Aeschylus, Supplices",
"oedipus": "Sophocles, Oedipus", "cyclops": "Euripides, Cyclops",
"acharnenses": "Aristophanes, Acharnenses", "aristophanes": "Aristophanes (lyrics)",
"bacchylides": "Bacchylides", "thucydides": "Thucydides", "cratylus": "Plato, Cratylus",
"dioscorides": "Dioscorides", "enchiridion": "Epictetus, Enchiridion",
"plutarchus": "Plutarch", "contracelsum": "Origen, Contra Celsum",
"quintus": "Quintus Smyrnaeus", "dionysiaca": "Nonnus, Dionysiaca"}
ORDER = ["partheneion", "supplices", "bacchylides", "oedipus", "cyclops", "thucydides",
"acharnenses", "aristophanes", "cratylus", "dioscorides", "enchiridion", "plutarchus",
"contracelsum", "quintus", "dionysiaca"]
def load(path):
return [json.loads(l) for l in open(path, encoding="utf-8")]
def bare(ch):
return unicodedata.normalize("NFD", ch)[0].lower()
def attach_silver(pos, split, overlap):
sil = [r for r in load(os.path.join(ROOT, overlap))
if r["split"] == split and r["gold"]]
# Line numbering differs between the two files, so align per source in order
# (both list the gold positions in text order); words must match up to apostrophes.
by = collections.defaultdict(list)
for r in sil:
by[r["source"]].append(r)
cnt = collections.Counter()
ap = str.maketrans({"'": "’", "᾽": "’", "ʼ": "’"})
for p in pos:
q = by[p["source"]][cnt[p["source"]]]
cnt[p["source"]] += 1
assert q["gold"] == p["gold"] and q["word"].translate(ap) in p["word"].translate(ap), (p, q)
p["vowel"] = bare(q["word"][q["pos"]])
if q["s_short"] + q["s_long"] > 0:
maj = "^" if q["s_short"] >= q["s_long"] else "_"
p["bucket"] = "labelled, majority = gold" if maj == p["gold"] else "labelled, majority ≠ gold"
elif q["f_norm"] > 0:
p["bucket"] = "seen, unlabelled"
else:
p["bucket"] = "unseen"
assert sum(len(v) for v in by.values()) == len(pos)
return pos
def acc(rows):
return 100 * sum(r["pred"] == r["gold"] for r in rows) / len(rows) if rows else float("nan")
def table(title, keyf, keys, systems, note=""):
names = list(systems)
out = [f"### {title}", "", note] if note else [f"### {title}", ""]
out += ["| group | n | " + " | ".join(names) + " |", "|---|---:|" + "---:|" * len(names)]
for k in keys:
rows = {s: [r for r in systems[s] if keyf(r) == k] for s in names}
n = len(rows[names[0]])
if n:
out.append(f"| {k} | {n} | " + " | ".join(f"{acc(rows[s]):.1f}" for s in names) + " |")
out.append(f"| **all** | {len(systems[names[0]])} | " +
" | ".join(f"{acc(systems[s]):.1f}" for s in names) + " |")
return "\n".join(out) + "\n"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--split", default="test")
ap.add_argument("--runs", default="runs/final", help="dir with seed{1,2,3}/eval, relative to the repo root")
ap.add_argument("--overlap", default="analysis/silver_overlap.per_vowel.jsonl",
help="silver_overlap.py per_vowel output for the silver data the models were trained on")
ap.add_argument("--rule_dir", default="results/rule-based-a949b76",
help="rule_based.py output dir, relative to the repo root")
a = ap.parse_args()
systems = {}
for s in (1, 2, 3):
f, = glob.glob(os.path.join(ROOT, f"{a.runs}/seed{s}/eval/*.{a.split}.positions.jsonl"))
systems[f"seed{s}"] = attach_silver(load(f), a.split, a.overlap)
rb = os.path.join(ROOT, a.rule_dir, f"rule-based.{a.split}.positions.jsonl")
if os.path.exists(rb):
systems["rule-based"] = attach_silver(load(rb), a.split, a.overlap)
# per-position mean over seeds as an extra column
seeds = [systems[f"seed{s}"] for s in (1, 2, 3)]
names = list(systems)
period = lambda r: "Classical (Alcman–Plato)" if r["source"] in CLASSICAL else "Hellenistic and later"
label = lambda r: {"^": "short", "_": "long"}[r["gold"]]
buckets = ["labelled, majority = gold", "labelled, majority ≠ gold", "seen, unlabelled", "unseen"]
print(f"# Error analysis, Norma {a.split}\n")
print("Mixed accuracy (%) of the three Makron seeds and the rule-based grc-macronizer; "
"an unmarked position counts as wrong.\n")
print(table("By silver bucket", lambda r: r["bucket"], buckets, systems,
"Labelled: the vowel carries a silver label in that word form; majority = the most "
"frequent silver label. Seen, unlabelled: the form occurs in silver, the vowel is never "
"labelled. Unseen: the form never occurs in silver.\n"))
print(table("By gold label", label, ["long", "short"], systems))
for lab in ("long", "short"):
sub = {k: [r for r in v if label(r) == lab] for k, v in systems.items()}
print(table(f"By silver bucket, gold {lab}", lambda r: r["bucket"], buckets, sub))
print(table("By vowel", lambda r: r["vowel"], ["α", "ι", "υ"], systems))
print(table("By period", period, ["Classical (Alcman–Plato)", "Hellenistic and later"], systems))
for lab in ("long", "short"):
sub = {k: [r for r in v if label(r) == lab] for k, v in systems.items()}
print(table(f"By period, gold {lab}", period,
["Classical (Alcman–Plato)", "Hellenistic and later"], sub))
print(table("By text", lambda r: AUTHOR[r["source"]], [AUTHOR[s] for s in ORDER], systems))
if "rule-based" in systems:
print("### Model vs rule-based, per position\n")
print("Agreement cells: how many positions each system gets right. Model = majority of the three seeds.\n")
rbr = systems["rule-based"]
cells = collections.Counter()
cells_b = collections.defaultdict(collections.Counter)
for i, r in enumerate(rbr):
m_ok = sum(sd[i]["pred"] == sd[i]["gold"] for sd in seeds) >= 2
r_ok = r["pred"] == r["gold"]
r_abst = r["pred"] is None
key = ("model ✓" if m_ok else "model ✗") + ", " + (
"rule ✓" if r_ok else ("rule abstains" if r_abst else "rule ✗"))
cells[key] += 1
cells_b[r["bucket"]][key] += 1
keys = ["model ✓, rule ✓", "model ✓, rule abstains", "model ✓, rule ✗",
"model ✗, rule ✓", "model ✗, rule abstains", "model ✗, rule ✗"]
print("| bucket | " + " | ".join(keys) + " |\n|---|" + "---:|" * len(keys))
for b in buckets + ["all"]:
c = cells if b == "all" else cells_b[b]
print(f"| {b} | " + " | ".join(str(c[k]) for k in keys) + " |")
print()
print("### Most frequent errors (seed 2)\n")
errs = collections.Counter((r["word"].strip(".,;·:!?'’()"), r["gold"], r["pred"]) for r in systems["seed2"]
if r["pred"] != r["gold"])
print("| word | gold | pred | count |\n|---|---|---|---:|")
for (w, g, p), c in errs.most_common(25):
print(f"| {w} | {g} | {p or '–'} | {c} |")
if __name__ == "__main__":
main()