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
3.81 kB
"""Run a named entity system on the test set and score it beside the published systems.
from benchmark import evaluate
evaluate(my_ner, name="my-ner") # my_ner(text) -> [(start, end, type), ...] for one text
python benchmark.py --module my_package:ner --name my-ner
python benchmark.py --predictions FILE --name my-ner # outputs you already have, in the format of predictions/
The function gets one test text at a time, as written, and returns its entities as character offsets into that text,
end exclusive, each with one of the types of the set (README.md). The outputs go to outputs/NAME/thainer22-test.jsonl
and the scores to results-NAME.json; the three views are printed next to the published systems.
"""
from __future__ import annotations
import argparse
import importlib
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 score import EXPECTED, SET, VIEWS, read_outputs, score_system # noqa: E402
from scoring.ner import read # noqa: E402
def check_entities(rid: str, text: str, ents) -> list[list]:
out = []
for e in ents:
a, b, t = e
if not (isinstance(a, int) and isinstance(b, int) and isinstance(t, str) and 0 <= a < b <= len(text)):
raise ValueError(f"{rid}: {e!r} is not (start, end, type) with 0 <= start < end <= len(text)")
out.append([a, b, t])
return out
def run(fn, gold: dict) -> dict:
return {k: {"id": k, "entities": check_entities(k, gold[k]["text"], fn(gold[k]["text"]))} for k in sorted(gold)}
def write(rows: dict, path: Path) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8", newline="\n") as f:
for k in sorted(rows):
f.write(json.dumps({"id": k, "entities": rows[k]["entities"]}, ensure_ascii=False) + "\n")
def evaluate(fn=None, name: str = "my-system", predictions: str | Path | None = None) -> dict:
"""Score a function (or a file of outputs) on the three views and print it beside the published rows."""
gold = read(prepare())
if predictions is not None:
pred = read_outputs(Path(predictions), gold)
else:
pred = run(fn, gold)
write(pred, HERE / "outputs" / name / f"{SET}.jsonl")
res, _ = score_system(gold, pred)
exp = json.loads(EXPECTED.read_text(encoding="utf-8"))
print(f"{'Entity F1 (%)':52s} " + " ".join(f"{v:>13s}" for v in VIEWS))
for n, r in sorted(exp["systems"].items(), key=lambda x: -x[1]["f1"]["all"]):
label = f"{r['display']}, {r['input']}"[:52]
print(f"{label:52s} " + " ".join(f"{r['f1'][v]:13.2f}" for v in VIEWS))
print(f"{name[:52]:52s} " + " ".join(f"{res[v]['f1']:13.2f}" for v in VIEWS) + " <- yours")
out = {"name": name, "set": SET, "f1": {v: round(res[v]["f1"], 2) for v in VIEWS},
"p": {v: round(res[v]["p"], 2) for v in VIEWS}, "r": {v: round(res[v]["r"], 2) for v in VIEWS}}
(HERE / f"results-{name}.json").write_text(json.dumps(out, ensure_ascii=False, indent=1) + "\n", encoding="utf-8")
return out
def main() -> None:
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--module", help="package.module:function, called with one text")
ap.add_argument("--predictions", help="a file of outputs, one line per test text")
ap.add_argument("--name", required=True)
a = ap.parse_args()
if bool(a.module) == bool(a.predictions):
raise SystemExit("give --module or --predictions")
fn = None
if a.module:
mod, _, attr = a.module.partition(":")
fn = getattr(importlib.import_module(mod), attr)
evaluate(fn, a.name, a.predictions)
if __name__ == "__main__":
main()