yacht's picture
OpenThai2.0-NLP-Core-Benchmark 1.1: test sets, scorers and system outputs for six Thai tasks.
0e6d825
Raw History Blame Contribute Delete
6.17 kB
"""Recompute every published number of this folder from the stored outputs.
python score.py check # every score and interval of README.md and results/expected.json, recomputed and checked
python score.py table # the results table of README.md, from results/expected.json
The first run builds the test set from its source (build_testsets.py). Three views, as in README.md: every text with
the 16 types; the texts that share no text with ThaiNER v2.2 train (data/views.json); and every text with the three
types PERSON, ORGANIZATION and LOCATION. Scores are entity F1 (micro, %); results/expected.json keeps two decimals,
README.md one (half to even, Python's round, once, from the unrounded score).
"""
from __future__ import annotations
import json
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from build_testsets import prepare # noqa: E402
from scoring.ner import bootstrap, counts, read # noqa: E402
SET = "thainer22-test"
OURS = "openthai2.0-nlp-core-lite"
THREE = {"PERSON", "ORGANIZATION", "LOCATION"}
VIEWS = ("all", "not-in-train", "three-types")
EXPECTED = HERE / "results" / "expected.json"
def views(gold: dict) -> dict:
v = json.loads((HERE / "data" / "views.json").read_text(encoding="utf-8"))
clean = set(gold) - set(v["in-train"])
return {"all": (None, None), "not-in-train": (clean, None), "three-types": (None, THREE)}
def restrict(rows: dict, ids, types) -> dict:
return {k: {**r, "entities": [e for e in r["entities"] if types is None or e[2] in types]}
for k, r in rows.items() if ids is None or k in ids}
def score(gold: dict, pred: dict, ids, types) -> tuple[dict, object]:
"""Entity F1 (micro, unrounded) of one system on one view, and its counts for the bootstrap."""
c, _, _ = counts(restrict(gold, ids, types), restrict(pred, ids, types))
tp, n_p, n_g = (int(x) for x in c.sum(axis=(0, 1)))
p = tp / n_p if n_p else 0.0
r = tp / n_g if n_g else 0.0
f = 2 * p * r / (p + r) if p + r else 0.0
return {"f1": 100 * f, "p": 100 * p, "r": 100 * r, "gold": n_g, "predicted": n_p, "correct": tp}, c
def read_outputs(path: Path, gold: dict) -> dict:
pred = read(path)
if set(pred) != set(gold):
raise SystemExit(f"{path}: {len(set(gold) - set(pred))} texts without a row, "
f"{len(set(pred) - set(gold))} rows of unknown ids")
return pred
def score_system(gold: dict, pred: dict) -> tuple[dict, dict]:
out, cs = {}, {}
for vn, (ids, types) in views(gold).items():
out[vn], cs[vn] = score(gold, pred, ids, types)
return out, cs
def recompute() -> dict:
gold = read(prepare())
exp = json.loads(EXPECTED.read_text(encoding="utf-8"))
res, cs = {}, {}
for name in exp["systems"]:
res[name], cs[name] = score_system(gold, read_outputs(HERE / "predictions" / name / f"{SET}.jsonl", gold))
pairs = {b: {vn: bootstrap(cs[OURS][vn], cs[b][vn]) for vn in VIEWS} for b in exp["compared"]}
return {"systems": res, "compared": pairs}
def fmt(x: float, row: dict, bold: bool) -> str:
s = f"{x:.1f}"
if row["learnt_test"]:
return f"({s})"
return f"**{s}**" if bold else s
def table_md(exp: dict) -> str:
"""The results table: ours, the other systems from raw text by score, those that learnt the test texts in
parentheses, then the reference rows. Bold: the best value of each column, among the rows in the comparison."""
rows = exp["systems"]
kinds = {"ours": 0, "rival": 1, "reference": 3}
order = sorted(rows, key=lambda n: (kinds[rows[n]["kind"]] + (1 if rows[n]["learnt_test"] else 0),
-rows[n]["f1"]["all"]))
compared = [n for n in rows if rows[n]["kind"] != "reference" and not rows[n]["learnt_test"]]
best = {vn: max(rows[n]["shown"][vn] for n in compared) for vn in VIEWS} # one decimal, rounded once
lines = ["| System | Input | All texts | Not in train | Three types |", "|---|---|---:|---:|---:|"]
for n in order:
r = rows[n]
name = f"**{r['display']}**" if r["kind"] == "ours" else r["display"]
if r["kind"] == "reference":
name += " (reference)"
cells = [fmt(r["shown"][vn], r, n in compared and r["shown"][vn] == best[vn])
for vn in VIEWS]
lines.append(f"| {name} | {r['input']} | " + " | ".join(cells) + " |")
lines += ["", "Bold: the best value of each column. Rows in parentheses and reference rows are left out of the "
"comparison (see below)."]
return "\n".join(lines)
def check() -> int:
exp = json.loads(EXPECTED.read_text(encoding="utf-8"))
got = recompute()
bad = []
for name, r in got["systems"].items():
for vn in VIEWS:
e = exp["systems"][name]
if round(r[vn]["f1"], 2) != e["f1"][vn] or round(r[vn]["f1"], 1) != e["shown"][vn]:
bad.append(f"{name} {vn}: {r[vn]['f1']:.4f}, expected {e['f1'][vn]} (shown {e['shown'][vn]})")
for b, r in got["compared"].items():
for vn in VIEWS:
e = exp["compared"][b][vn]
if (r[vn]["diff"], r[vn]["lo"], r[vn]["hi"]) != (e["diff"], e["lo"], e["hi"]):
bad.append(f"{OURS} minus {b} {vn}: {r[vn]}, expected {e}")
card = (HERE / "README.md").read_text(encoding="utf-8")
if table_md(exp) not in card:
bad.append("README.md: the table differs from results/expected.json")
for line in bad:
print(" ", line)
n = len(got["systems"]) * len(VIEWS) + len(got["compared"]) * len(VIEWS)
print(f"check: {n - len(bad)} of {n} numbers equal to results/expected.json"
+ ("" if bad else f" ({len(got['systems'])} systems, {len(VIEWS)} views, {len(got['compared'])} intervals each)"))
return 1 if bad else 0
def main() -> None:
cmd = sys.argv[1] if len(sys.argv) > 1 else "check"
if cmd == "check":
sys.exit(check())
if cmd == "table":
print(table_md(json.loads(EXPECTED.read_text(encoding="utf-8"))))
return
raise SystemExit(__doc__)
if __name__ == "__main__":
main()