Download conparse/scoring/metrics.py from iapp/OpenThai2.0-NLP-Core-Benchmark: direct link, hf CLI and curl.
- Browser
- Download file 8.64 kB
-
https://huggingface.co/datasets/iapp/OpenThai2.0-NLP-Core-Benchmark/resolve/main/conparse/scoring/metrics.py
- Command line
-
hf download hf://datasets/iapp/OpenThai2.0-NLP-Core-Benchmark/conparse/scoring/metrics.py
-
curl -L -o metrics.py https://huggingface.co/datasets/iapp/OpenThai2.0-NLP-Core-Benchmark/resolve/main/conparse/scoring/metrics.py
8.64 kB
| """Scores for UPOS tagging and dependency parsing, per sentence so they can be bootstrapped. | |
| Two settings: | |
| - gold words: the system received the treebank's words. UPOS accuracy, UPOS macro-F1 (as in Table 3 | |
| of the TUD paper), UAS and LAS over every word, punctuation included (the paper's evaluate.py). | |
| - raw text: the system received each sentence's text and chose its own words. Words are matched by | |
| their character span with whitespace removed, then Words/UPOS/UAS/LAS F1 follow the CoNLL 2018 | |
| shared task definitions (a head counts only if the system head word is the gold head word). | |
| Labels are compared on their universal part (`acl:relcl` -> `acl`), as in CoNLL 2018. TUD has no | |
| subtypes, so this changes nothing there. | |
| """ | |
| from __future__ import annotations | |
| from collections import Counter | |
| from dataclasses import dataclass, field | |
| from .conllu import Sentence | |
| def udep(label: str) -> str: | |
| return label.split(":", 1)[0] | |
| class SentCounts: | |
| """Counts of one sentence; summed over a corpus they give every score.""" | |
| gold: int = 0 | |
| system: int = 0 | |
| words: int = 0 # matched words (raw text); = gold = system with gold words | |
| upos: int = 0 | |
| uas: int = 0 | |
| las: int = 0 | |
| tag_tp: Counter = field(default_factory=Counter) | |
| tag_fp: Counter = field(default_factory=Counter) | |
| tag_fn: Counter = field(default_factory=Counter) | |
| def _nows_spans(sent: Sentence) -> list[tuple[int, int]]: | |
| """Spans of the words in the sentence text with all whitespace removed.""" | |
| text = sent.text | |
| offs = [] | |
| k = 0 | |
| for ch in text: | |
| offs.append(k) | |
| if not ch.isspace(): | |
| k += 1 | |
| offs.append(k) | |
| return [(offs[w.start], offs[w.end]) for w in sent.words] | |
| def sentence_counts(gold: Sentence, pred: Sentence, gold_words: bool) -> SentCounts: | |
| """Counts for one sentence. With gold_words the forms must be identical, word for word.""" | |
| c = SentCounts(gold=len(gold.words), system=len(pred.words)) | |
| if gold_words: | |
| if [w.form for w in gold.words] != [w.form for w in pred.words]: | |
| raise ValueError(f"word mismatch in sentence {gold.sent_id}") | |
| pairs = list(zip(gold.words, pred.words)) | |
| c.words = len(pairs) | |
| for g, p in pairs: | |
| ok_head = g.head == p.head | |
| c.uas += ok_head | |
| c.las += ok_head and udep(g.deprel) == udep(p.deprel) | |
| aligned = pairs | |
| else: | |
| if "".join(gold.text.split()) != "".join(pred.text.split()): | |
| raise ValueError(f"text mismatch in sentence {gold.sent_id}") | |
| gsp, psp = _nows_spans(gold), _nows_spans(pred) | |
| gidx = {sp: i for i, sp in enumerate(gsp)} | |
| aligned = [] | |
| p2g: dict[int, int] = {} | |
| for j, sp in enumerate(psp): | |
| i = gidx.get(sp) | |
| if i is not None: | |
| p2g[j] = i | |
| aligned.append((gold.words[i], pred.words[j])) | |
| c.words = len(aligned) | |
| for j, i in p2g.items(): | |
| g, p = gold.words[i], pred.words[j] | |
| # head match: both root, or the system head word is aligned to the gold head word | |
| if g.head == 0: | |
| ok_head = p.head == 0 | |
| else: | |
| ok_head = p.head > 0 and p2g.get(p.head - 1) == g.head - 1 | |
| c.uas += ok_head | |
| c.las += ok_head and udep(g.deprel) == udep(p.deprel) | |
| for g, p in aligned: | |
| if g.upos == p.upos: | |
| c.upos += 1 | |
| # tag counts for macro-F1 (gold words: every word is aligned, so fp/fn come from mismatches) | |
| if gold_words: | |
| for g, p in aligned: | |
| if g.upos == p.upos: | |
| c.tag_tp[g.upos] += 1 | |
| else: | |
| c.tag_fn[g.upos] += 1 | |
| c.tag_fp[p.upos] += 1 | |
| return c | |
| def corpus_counts(gold: list[Sentence], pred: list[Sentence], gold_words: bool) -> list[SentCounts]: | |
| if len(gold) != len(pred): | |
| raise ValueError(f"{len(gold)} gold sentences, {len(pred)} system sentences") | |
| return [sentence_counts(g, p, gold_words) for g, p in zip(gold, pred)] | |
| def macro_f1(tp: Counter, fp: Counter, fn: Counter, labels: list[str] | None = None) -> float: | |
| """Mean per-label F1 over `labels` (default: every label seen in gold or system).""" | |
| labels = labels if labels is not None else sorted(set(tp) | set(fp) | set(fn)) | |
| f1s = [] | |
| for t in labels: | |
| p_den, r_den = tp[t] + fp[t], tp[t] + fn[t] | |
| prec = tp[t] / p_den if p_den else 0.0 | |
| rec = tp[t] / r_den if r_den else 0.0 | |
| f1s.append(2 * prec * rec / (prec + rec) if prec + rec else 0.0) | |
| return sum(f1s) / len(f1s) if f1s else 0.0 | |
| def summarize(counts: list[SentCounts], gold_words: bool) -> dict[str, float]: | |
| """Corpus scores in percent (macro-F1 also in percent).""" | |
| G = sum(c.gold for c in counts) | |
| S = sum(c.system for c in counts) | |
| tot = {k: sum(getattr(c, k) for c in counts) for k in ("words", "upos", "uas", "las")} | |
| if gold_words: | |
| tp, fp, fn = Counter(), Counter(), Counter() | |
| for c in counts: | |
| tp.update(c.tag_tp), fp.update(c.tag_fp), fn.update(c.tag_fn) | |
| gold_labels = sorted(set(tp) | set(fn)) | |
| return { | |
| "words": G, | |
| "upos_acc": 100 * tot["upos"] / G, | |
| "upos_macro_f1": 100 * macro_f1(tp, fp, fn), | |
| "upos_macro_f1_gold_labels": 100 * macro_f1(tp, fp, fn, gold_labels), | |
| "uas": 100 * tot["uas"] / G, | |
| "las": 100 * tot["las"] / G, | |
| } | |
| def f1(k: str) -> float: | |
| p, r = tot[k] / S if S else 0.0, tot[k] / G if G else 0.0 | |
| return 100 * 2 * p * r / (p + r) if p + r else 0.0 | |
| return {"words": G, "sys_words": S, "words_f1": f1("words"), "upos_f1": f1("upos"), | |
| "uas_f1": f1("uas"), "las_f1": f1("las")} | |
| def paired_bootstrap(a: list[SentCounts], b: list[SentCounts], gold_words: bool, metric: str, | |
| n: int = 10000, seed: int = 112) -> dict[str, float]: | |
| """Difference a - b in `metric` with a 95% interval, resampling sentences with replacement. | |
| p is the two-sided share of resamples whose difference has the other sign (or is zero). | |
| """ | |
| import numpy as np | |
| rng = np.random.default_rng(seed) | |
| m = len(a) | |
| if gold_words and metric.startswith("upos_macro_f1"): | |
| # macro-F1 is not a sum: recompute it per resample from per-sentence tag counts | |
| labels = sorted({t for c in a + b for t in list(c.tag_tp) + list(c.tag_fn) + list(c.tag_fp)}) | |
| lab = {t: i for i, t in enumerate(labels)} | |
| def mat(cs: list[SentCounts]) -> np.ndarray: | |
| x = np.zeros((len(cs), 3, len(labels))) | |
| for i, c in enumerate(cs): | |
| for k, ctr in enumerate((c.tag_tp, c.tag_fp, c.tag_fn)): | |
| for t, v in ctr.items(): | |
| x[i, k, lab[t]] = v | |
| return x | |
| def mf1(x: np.ndarray, gold_only: bool) -> np.ndarray: | |
| tp, fp, fn = x[..., 0, :], x[..., 1, :], x[..., 2, :] | |
| with np.errstate(invalid="ignore", divide="ignore"): | |
| f = np.nan_to_num(2 * tp / (2 * tp + fp + fn)) | |
| present = (tp + fn > 0) if gold_only else (tp + fp + fn > 0) | |
| return (f * present).sum(-1) / np.maximum(present.sum(-1), 1) | |
| gold_only = metric.endswith("gold_labels") | |
| xa, xb = mat(a), mat(b) | |
| base = float(mf1(xa.sum(0), gold_only) - mf1(xb.sum(0), gold_only)) | |
| diffs = np.empty(n) | |
| for r in range(n): | |
| idx = rng.integers(0, m, m) | |
| diffs[r] = mf1(xa[idx].sum(0), gold_only) - mf1(xb[idx].sum(0), gold_only) | |
| else: | |
| key = {"upos_acc": "upos", "uas": "uas", "las": "las", "upos_f1": "upos", "uas_f1": "uas", | |
| "las_f1": "las", "words_f1": "words"}[metric] | |
| def arr(cs: list[SentCounts]) -> np.ndarray: | |
| return np.array([[getattr(c, key), c.gold, c.system] for c in cs], dtype=float) | |
| xa, xb = arr(a), arr(b) | |
| def score(x: np.ndarray) -> np.ndarray: | |
| k, g, s = x[..., 0], x[..., 1], x[..., 2] | |
| if gold_words: | |
| return k / g | |
| p, r = k / s, k / g | |
| return 2 * p * r / (p + r) | |
| base = float(score(xa.sum(0)) - score(xb.sum(0))) | |
| idx = rng.integers(0, m, (n, m)) | |
| diffs = score(xa[idx].sum(1)) - score(xb[idx].sum(1)) | |
| lo, hi = np.percentile(diffs, [2.5, 97.5]) | |
| if base > 0: | |
| p = 2 * float(np.mean(diffs <= 0)) | |
| elif base < 0: | |
| p = 2 * float(np.mean(diffs >= 0)) | |
| else: | |
| p = 1.0 | |
| return {"diff": 100 * base, "lo": 100 * float(lo), "hi": 100 * float(hi), "p": min(p, 1.0)} | |