Datasets:
Tasks:
Token Classification
Modalities:
Text
Formats:
json
Languages:
Thai
Size:
10K - 100K
ArXiv:
License:
Download score.py from iapp/OpenThai2.0-WordSeg-Benchmark: direct link, hf CLI and curl.
- Browser
- Download file 9.17 kB
-
https://huggingface.co/datasets/iapp/OpenThai2.0-WordSeg-Benchmark/resolve/main/score.py
- Command line
-
hf download hf://datasets/iapp/OpenThai2.0-WordSeg-Benchmark/score.py
-
curl -L -o score.py https://huggingface.co/datasets/iapp/OpenThai2.0-WordSeg-Benchmark/resolve/main/score.py
9.17 kB
| """Score Thai word segmentation on the benchmark. | |
| python score.py table # every published number, recomputed and checked | |
| python score.py units # the held-out choice of OpenThai2.0-LATTE-WordSeg-Lite's unit | |
| python score.py score SET PREDICTIONS.jsonl # your system: {"id", "tokens": [...]} per line of data/SET.jsonl | |
| python score.py score SET PREDS.jsonl --vs deepcut-0.7.0.0 # + paired bootstrap against a published system | |
| Two metrics, as in the LATTE paper, both corpus-level (counts summed over the lines of a set). Word F1 (%): a | |
| predicted word is correct when a gold word has the same two ends. Boundary F1 (%): a cut between two | |
| non-whitespace characters is correct when gold cuts there too; the cuts next to whitespace and the start of a | |
| line are given to every system and are not counted (khammoon's metric). Intervals: 1,000 paired bootstrap | |
| resamples of lines. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| import numpy as np | |
| HERE = Path(__file__).resolve().parent | |
| sys.path.insert(0, str(HERE)) | |
| from thaiws import boundary_counts, bootstrap_weights, f1, load_set, read_jsonl, word_counts # noqa: E402 | |
| SETS = [("tud", "TUD"), ("pud", "PUD"), ("ws160", "WS160"), ("vistec", "VISTEC"), ("bestdd", "BEST"), | |
| ("orchidndd", "ORCHID"), ("khm", "khammoon test")] | |
| PRODUCT = "openthai2.0-latte-wordseg-lite" | |
| # its three units, coarse to fine, named after the long and short unit words of BCCWJ and the smallest units under | |
| # them: long keeps compounds whole, short (the default) gives words, minimal gives morphemes | |
| UNITS = ("long", "short", "minimal") | |
| DEFAULT = "short" | |
| COMMERCIAL = ("tud", "pud", "ws160", "vistec") # the test sets whose licence allows commercial use | |
| # the unit of each test set: the convention each unit was trained on, else chosen on held-out data (`units`) | |
| RULE = {"tud": "short", "pud": "long", "ws160": "short", "vistec": "long", "bestdd": "short", "orchidndd": "long", | |
| "khm": "minimal", "khmdd": "minimal"} | |
| TOOLS = ["khammoon-0.1.0", "deepcut-0.7.0.0", "sefr-cut-1.1-best", "sefr-cut-1.1-ws1000", "attacut-1.0.6-sc", | |
| "attacut-1.0.6-c", "oskut-1.3-ws", "oskut-1.3-scads", "tltk-1.11", "nlpo3-1.4.0", "pythainlp-5.4.0-newmm"] | |
| def preds(system: str, s: str) -> list[dict]: | |
| return read_jsonl(HERE / "predictions" / system / f"{s}.words.jsonl.gz") | |
| def table() -> None: | |
| expected = json.loads((HERE / "results" / "expected.json").read_text()) | |
| rows = {f"{PRODUCT}-{u}": {s: f"{PRODUCT}-{u}" for s, _ in SETS} for u in UNITS} | |
| rows[f"{PRODUCT} (unit rule)"] = {s: f"{PRODUCT}-{RULE[s]}" for s, _ in SETS} | |
| rows.update({t: {s: t for s, _ in SETS} for t in TOOLS}) | |
| point, boot, cache, bpoint = {}, {}, {}, {} | |
| for k, (s, _) in enumerate(SETS): | |
| data = load_set(s) | |
| W = bootstrap_weights(len(data), 12345 + k) | |
| for name, systems in rows.items(): | |
| sy = systems[s] | |
| if sy not in cache: | |
| p = preds(sy, s) | |
| c = word_counts(data, p) | |
| cache[sy] = (float(f1(c.sum(0))), f1(W @ c), float(f1(boundary_counts(data, p).sum(0)))) | |
| point[(name, s)], boot[(name, s)], bpoint[(name, s)] = cache[sy] | |
| cache.clear() | |
| bad = [] | |
| def check(what, got, want): | |
| if abs(got - want) > 5e-4: | |
| bad.append(f"{what}: {got:.4f} vs expected {want:.4f}") | |
| def averages(vals): | |
| """Mean of all seven sets, of the four commercial-use sets, and of the six sets other than BEST.""" | |
| by_set = dict(zip([s for s, _ in SETS], vals)) | |
| return (float(np.mean(vals)), float(np.mean([by_set[s] for s in COMMERCIAL])), | |
| float(np.mean([v for s, v in by_set.items() if s != "bestdd"]))) | |
| head = ("| System | " + " | ".join(h for _, h in SETS) + " | Average, all 7 sets | Average, 4 commercial-use sets |\n|---|" | |
| + "---|" * (len(SETS) + 2)) | |
| print(head) | |
| for name in rows: | |
| vals = [point[(name, s)] for s, _ in SETS] | |
| avg7, avg4, avg6 = averages(vals) | |
| print(f"| {name} | " + " | ".join(f"{v:.2f}" for v in vals) + f" | {avg7:.2f} | {avg4:.2f} |") | |
| for (s, _), v in zip(SETS, vals): | |
| check(f"word F1 {name} {s}", v, expected["word_f1"][name][s]) | |
| check(f"average {name}", avg7, expected["averages"][name]["avg7"]) | |
| check(f"average of the commercial-use sets {name}", avg4, expected["averages"][name]["avg4_commercial"]) | |
| check(f"average without BEST {name}", avg6, expected["averages"][name]["avg6_without_best"]) | |
| print("\nboundary F1 (%), the second metric:") | |
| print(head) | |
| for name in rows: | |
| vals = [bpoint[(name, s)] for s, _ in SETS] | |
| avg7, avg4, avg6 = averages(vals) | |
| print(f"| {name} | " + " | ".join(f"{v:.2f}" for v in vals) + f" | {avg7:.2f} | {avg4:.2f} |") | |
| want = expected["boundary_f1_sets"][name] | |
| for (s, _), v in zip(SETS, vals): | |
| check(f"boundary F1 {name} {s}", v, want[s]) | |
| check(f"boundary average {name}", avg7, want["avg7"]) | |
| check(f"boundary average of the commercial-use sets {name}", avg4, want["avg4_commercial"]) | |
| check(f"boundary average without BEST {name}", avg6, want["avg6_without_best"]) | |
| print("\nother PyThaiNLP tokenisers (word F1 %):") | |
| for sy, want in expected.get("extra_word_f1", {}).items(): | |
| vals = [] | |
| for s, _ in SETS: | |
| v = float(f1(word_counts(load_set(s), preds(sy, s)).sum(0))) | |
| check(f"word F1 {sy} {s}", v, want[s]) | |
| vals.append(v) | |
| print(f" {sy:30s} " + " ".join(f"{v:6.2f}" for v in vals)) | |
| print("\nkhammoon's metric (boundary F1 %, lines):") | |
| for s in ("khm", "khmdd"): | |
| if s == "khmdd" and not (HERE / "data" / "khmdd.jsonl").is_file(): | |
| print(" khmdd skipped: not built (it needs khammoon's training text: python fetch_sources.py)") | |
| continue | |
| data = load_set(s) | |
| for sy in [f"{PRODUCT}-minimal"] + TOOLS: | |
| v = float(f1(boundary_counts(data, preds(sy, s)).sum(0))) | |
| check(f"boundary F1 {sy} {s}", v, expected["boundary_f1"][s][sy]) | |
| print(f" {s:5s} {sy:32s} {v:.2f}") | |
| avg_b = {n: np.mean([boot[(n, s)] for s, _ in SETS], axis=0) for n in rows} | |
| d = avg_b[f"{PRODUCT}-{DEFAULT}"] - avg_b["sefr-cut-1.1-best"] | |
| print(f"\naverage, `{DEFAULT}` on every set, minus SEFR CUT: {np.mean([point[(f'{PRODUCT}-{DEFAULT}', s)] for s, _ in SETS]) - np.mean([point[('sefr-cut-1.1-best', s)] for s, _ in SETS]):+.2f} " | |
| f"[{np.percentile(d, 2.5):+.2f}, {np.percentile(d, 97.5):+.2f}]") | |
| print("\nCHECK:", "every number equals the published one" if not bad else f"{len(bad)} differences:\n " + "\n ".join(bad)) | |
| sys.exit(1 if bad else 0) | |
| def units() -> None: | |
| expected = json.loads((HERE / "results" / "expected.json").read_text())["unit_choice"] | |
| pud = load_set("pud") | |
| halves = {h: [r["src_id"] for r in load_set(f"pud{h}")] for h in "AB"} | |
| bad = [] | |
| for name in ("bestdev", "orchiddev", "pudA", "pudB"): | |
| scores = {} | |
| for u in UNITS: | |
| if name.startswith("pud"): | |
| p = preds(f"{PRODUCT}-{u}", "pud") | |
| ids = halves[name[-1]] | |
| rows, pp = [pud[i] for i in ids], [p[i] for i in ids] | |
| else: | |
| rows, pp = load_set(name), preds(f"{PRODUCT}-{u}", name) | |
| scores[u] = float(f1(word_counts(rows, pp).sum(0))) | |
| best = max(scores.values()) | |
| chosen = DEFAULT if scores[DEFAULT] == best else max(scores, key=scores.get) | |
| print(f"{name:10s} " + " ".join(f"{u} {v:.2f}" for u, v in scores.items()) + f" -> {chosen}") | |
| if chosen != expected["chosen"][name] or any(abs(scores[u] - expected["heldout_f1"][name][u]) > 5e-4 for u in scores): | |
| bad.append(name) | |
| print("CHECK:", "same choices and scores as published" if not bad else f"differences: {bad}") | |
| sys.exit(1 if bad else 0) | |
| def score(s: str, path: str, vs: str | None) -> None: | |
| data = load_set(s) | |
| mine = read_jsonl(Path(path)) | |
| c = word_counts(data, mine) | |
| print(f"{s}: word F1 {float(f1(c.sum(0))):.2f} (P {100 * c[:, 0].sum() / max(c[:, 1].sum(), 1):.2f}, " | |
| f"R {100 * c[:, 0].sum() / max(c[:, 2].sum(), 1):.2f})") | |
| print(f"{s}: boundary F1 {float(f1(boundary_counts(data, mine).sum(0))):.2f} (khammoon's metric)") | |
| if vs: | |
| r = word_counts(data, preds(vs, s)) | |
| W = bootstrap_weights(len(data), 20261114) | |
| d = f1(W @ c) - f1(W @ r) | |
| print(f"minus {vs}: {float(f1(c.sum(0)) - f1(r.sum(0))):+.2f} [{np.percentile(d, 2.5):+.2f}, {np.percentile(d, 97.5):+.2f}]") | |
| if __name__ == "__main__": | |
| ap = argparse.ArgumentParser() | |
| sub = ap.add_subparsers(dest="cmd", required=True) | |
| sub.add_parser("table") | |
| sub.add_parser("units") | |
| p = sub.add_parser("score") | |
| p.add_argument("set") | |
| p.add_argument("predictions") | |
| p.add_argument("--vs", default=None) | |
| a = ap.parse_args() | |
| {"table": lambda: table(), "units": lambda: units(), "score": lambda: score(a.set, a.predictions, a.vs)}[a.cmd]() | |