File size: 8,094 Bytes
c266841 | 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 147 148 149 150 151 152 153 154 155 156 157 158 159 160 | '''
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):
sil = [r for r in load(os.path.join(ROOT, "analysis/silver_overlap.per_vowel.jsonl"))
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")
a = ap.parse_args()
systems = {}
for s in (1, 2, 3):
f, = glob.glob(os.path.join(ROOT, f"runs/final/seed{s}/eval/*.{a.split}.positions.jsonl"))
systems[f"seed{s}"] = attach_silver(load(f), a.split)
rb = os.path.join(ROOT, f"results/rule-based/rule-based.{a.split}.positions.jsonl")
if os.path.exists(rb):
systems["rule-based"] = attach_silver(load(rb), a.split)
# 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()
|