Structured Prediction and Parsing Evaluation › Implementation: Decoders, Scorers, and Metrics
Language AI HandbookAll chapters The rest of the chapter builds the pieces. The examples are small enough to trace the arithmetic. The two exact chart decoders are compared with exhaustive enumeration on their small fixtures.
Setting Up
The examples use Python 3.11, NumPy 2.4.2, and Matplotlib 3.10.8 in the book's locked environment. They train no model and download no corpus. The synthetic experiment uses its own default_rng(seed=7); the hidden shared plotting setup is seeded once before the chapter runs. The cells below calculate the implementation outputs and simulation values; the preceding 11-word table is a separate hand calculation. The later corpus pools that fixture with three other sentences, so its aggregate scores use 35 words.
Counting the Search Space
Before running the exact chart decoders, it helps to see how fast the space grows. The recurrence for projective trees counts a projective forest on each side of the root. The empty forest gives . If , the series for nonempty trees is , with marking the root. A forest is empty or starts with a tree followed by a forest, so . Set , so . Here is the coefficient of in , and is a dummy variable for the coefficient extraction. For , Lagrange inversion gives . Stirling’s formula gives the growth scale. The recurrences for the coefficients are:
where:
- : the number of projective dependency trees on tokens
- : the number of projective forests on nodes
- : the root position, splitting the sentence into left and right forests
- : the size of the leftmost tree in the forest decomposition
PythonIn [10]Expand
def projective_tree_counts(nmax):
P = [1] # P[0] = 1 by convention
A = [1] # A[0] = 1, empty forest
for n in range(1, nmax + 1):
p = sum(A[r] * A[n - 1 - r] for r in range(n))
P.append(p)
a = sum(P[m] * A[n - m] for m in range(1, n + 1))
A.append(a)
return P, A
P, A = projective_tree_counts(20)ConsoleOut [11]Expand
n= 3 unlabeled trees: all= 9 projective= 7 n= 5 unlabeled trees: all= 625 projective= 143 n=10 unlabeled trees: all= 1,000,000,000 projective= 690,690 n=15 unlabeled trees: all= 29,192,926,025,390,625 projective= 5,225,264,024 n=20 unlabeled trees: all=5,242,880,000,000,000,000,000,000 projective= 47,365,474,641,870
For a 20-token sentence there are about unlabeled dependency trees, of which about are projective. Both counts motivate efficient search; the dynamic programs also require the factorizations and sufficient states described above.
VisualizationOut [13]Expand

A Dependency Decoder
The implementation below follows the four Eisner recurrences and stores backpointers for reconstruction. A computed nonfinite total from adding finite reachable scores raises FloatingPointError. If chart construction and root scoring finish without an arithmetic exception but find no finite full-sentence completion, the decoder raises ValueError before reconstruction. Rounding can change which tree wins even when all reachable score sums stay finite. A sum just above the finite range can also round to a finite value. Backtracking is recursive, so a sufficiently deep reconstruction can exceed Python's recursion limit.
PythonIn [14]Expand
def eisner(score, forbidden=frozenset()):
"""Best projective dependency tree under an arc-factored score."""
score = np.asarray(score, dtype=float)
if score.ndim != 2 or score.shape[0] != score.shape[1] or not len(score):
raise ValueError("score must be a nonempty square matrix")
if np.isnan(score).any() or np.isposinf(score).any():
raise ValueError("scores may be finite or negative infinity")
n = score.shape[0]
C = np.full((n, n, 2), NEG)
I = np.full((n, n, 2), NEG)
Cb = np.full((n, n, 2), -1, dtype=int)
Ib = np.full((n, n, 2), -1, dtype=int)
for i in range(n):
C[i, i, 0] = 0.0
C[i, i, 1] = 0.0
def arc(h, d):
return NEG if (h, d) in forbidden else score[h, d]
def add_scores(left, right):
if left == NEG or right == NEG:
return NEG
total = float(left) + float(right)
if not np.isfinite(total):
raise FloatingPointError(
"Accumulated score exceeds floating-point range"
)
return total
for width in range(1, n):
for i in range(n - width):
j = i + width
best, arg = NEG, -1
for k in range(i, j):
v = add_scores(C[i, k, 0], C[k + 1, j, 1])
if v > best:
best, arg = v, k
I[i, j, 0] = add_scores(arc(i, j), best)
Ib[i, j, 0] = arg
best, arg = NEG, -1
for k in range(i + 1, j + 1):
v = add_scores(C[i, k - 1, 0], C[k, j, 1])
if v > best:
best, arg = v, k
I[i, j, 1] = add_scores(arc(j, i), best)
Ib[i, j, 1] = arg
best, arg = NEG, -1
for k in range(i + 1, j + 1):
v = add_scores(I[i, k, 0], C[k, j, 0])
if v > best:
best, arg = v, k
C[i, j, 0] = best
Cb[i, j, 0] = arg
best, arg = NEG, -1
for k in range(i, j):
v = add_scores(C[i, k, 1], I[k, j, 1])
if v > best:
best, arg = v, k
C[i, j, 1] = best
Cb[i, j, 1] = arg
best_root, best_score = -1, NEG
for r in range(n):
v = add_scores(C[0, r, 1], C[r, n - 1, 0])
if v > best_score:
best_score, best_root = v, r
def bt_C(i, j, d):
if i == j:
return []
k = Cb[i, j, d]
if d == 0:
return bt_I(i, k, 0) + bt_C(k, j, 0)
return bt_C(i, k, 1) + bt_I(k, j, 1)
def bt_I(i, j, d):
k = Ib[i, j, d]
if d == 0:
return [(i, j)] + bt_C(i, k, 0) + bt_C(k + 1, j, 1)
return [(j, i)] + bt_C(i, k - 1, 0) + bt_C(k, j, 1)
if best_root < 0 or not np.isfinite(best_score):
raise ValueError(
"No feasible projective tree satisfies the arc constraints"
)
arcs = bt_C(0, best_root, 1) + bt_C(best_root, n - 1, 0)
return best_score, arcsPythonIn [15]Expand
best_score, arcs = eisner(score)
print(f"best score: {best_score:.2f}")
print("arcs:", sorted(arcs, key=lambda a: a[1]))ConsoleOut [15]Expand
best score: 9.70 arcs: [(np.int64(1), np.int64(0)), (4, np.int64(1)), (np.int64(3), np.int64(2)), (np.int64(1), np.int64(3))]
The decoder finds the tree "ran" → "dog" → "the", "dog" → "barked" → "that", for a total of 9.70. It breaks the greedy cycle by choosing ran as the root instead of attaching it to the. The other four head choices stay the same.
Validating the Decoder Against Brute Force
Any new decoder should be checked against exhaustive search on small inputs. Here is the full enumeration of projective trees for five tokens, using the forest decomposition from earlier.
PythonIn [16]Expand
def all_projective_trees(n):
@lru_cache(maxsize=None)
def forest(i, j):
if i > j:
return ((frozenset(), ()),)
out = []
for k in range(i, j + 1):
for tarcs, troot in tree(i, k):
for farcs, froots in forest(k + 1, j):
out.append((tarcs | farcs, (troot,) + froots))
return tuple(out)
@lru_cache(maxsize=None)
def tree(i, j):
out = []
for r in range(i, j + 1):
for larcs, lroots in forest(i, r - 1):
for rarcs, rroots in forest(r + 1, j):
arcs = larcs | rarcs
for x in lroots:
arcs = arcs | {(r, x)}
for x in rroots:
arcs = arcs | {(r, x)}
out.append((arcs, r))
return tuple(out)
return [arcs for arcs, _ in tree(0, n - 1)]
trees = all_projective_trees(n)
brute_scores = [sum(score[h, d] for h, d in t) for t in trees]
best_i = int(np.argmax(brute_scores))ConsoleOut [17]Expand
projective trees on 5 tokens: 143 brute-force best score: 9.70 Eisner best score: 9.70 agree: True
The two scores match to machine precision. To test a decoder, generate random matrices with small integer scores and enumerate trees for . Keep the sums in the exact range and compare the maximum scores. For floating-point tests, state the score tolerance and how you handle ties. A boundary bug may show up at only one width or root. Vary the masks and include tie cases. Use these regression tests alongside a correctness argument that covers all sentence lengths.
Constrained Decoding
The example passes a forbidden arc to the decoder, which treats its score as negative infinity during lookup. Here we forbid the arc "dog" → "barked", which was the model's preferred attachment.
PythonIn [18]Expand
forbidden = {(1, 3)}
con_score, con_arcs = eisner(score, forbidden=forbidden)
print(f"unconstrained: {best_score:.2f} {sorted(arcs, key=lambda a: a[1])}")
print(f"constrained: {con_score:.2f} {sorted(con_arcs, key=lambda a: a[1])}")
print(f"score drop: {best_score - con_score:.2f}")ConsoleOut [18]Expand
unconstrained: 9.70 [(np.int64(1), np.int64(0)), (4, np.int64(1)), (np.int64(3), np.int64(2)), (np.int64(1), np.int64(3))] constrained: 8.70 [(np.int64(1), np.int64(0)), (4, np.int64(1)), (np.int64(3), np.int64(2)), (4, np.int64(3))] score drop: 1.00
The constrained tree attaches "barked" to "ran" instead of "dog", and the score drops by exactly the difference between those two arc scores. The constraint is respected exactly, and the decoder still returns the best tree that satisfies it. For a forbidden arc, a mask enforces the exclusion when an exact decoder has a finite-score feasible tree. A finite penalty may still let the forbidden arc win. To require a lexical arc, also exclude its dependent from the root candidates, as described above.
CKY with Lexical and Production Scores
Now the constituency side. We use a tiny binary grammar with hand-set additive scores so the arithmetic is transparent. These numbers are not normalized PCFG rule probabilities. The sentence "the cat saw the dog with a telescope" is the classic PP-attachment ambiguity: "with a telescope" can modify the verb "saw" or the noun "dog".
PythonIn [19]Expand
words = ["the", "cat", "saw", "the", "dog", "with", "a", "telescope"]
tags = ["Det", "N", "V", "Det", "N", "P", "Det", "N"]
lex = {
("Det", "the"): -0.1,
("Det", "a"): -0.1,
("N", "cat"): -0.1,
("N", "dog"): -0.1,
("N", "telescope"): -0.1,
("V", "saw"): -0.1,
("P", "with"): -0.1,
}
rules = {
("S", "NP", "VP"): -0.5,
("VP", "V", "NP"): -0.2,
("VP", "VP", "PP"): -0.3,
("NP", "Det", "N"): -0.1,
("NP", "NP", "PP"): -0.8,
("PP", "P", "NP"): -0.3,
}PythonIn [20]Expand
def cky(words, tags, lex, rules):
if len(words) != len(tags) or not words:
raise ValueError(
"CKY requires nonempty words and one supplied tag per word"
)
n = len(words)
chart = [[{} for _ in range(n + 1)] for _ in range(n + 1)]
back = [[{} for _ in range(n + 1)] for _ in range(n + 1)]
for i, (w, t) in enumerate(zip(words, tags)):
chart[i][i + 1][t] = lex.get((t, w), NEG)
back[i][i + 1][t] = None
for width in range(2, n + 1):
for i in range(n - width + 1):
j = i + width
for k in range(i + 1, j):
for (A, B, C), r in rules.items():
if B in chart[i][k] and C in chart[k][j]:
v = r + chart[i][k][B] + chart[k][j][C]
if v > chart[i][j].get(A, NEG):
chart[i][j][A] = v
back[i][j][A] = (k, B, C)
return chart, back
chart, back = cky(words, tags, lex, rules)Before reconstruction, require a finite full-span S score. In a multiword span, a candidate scored cannot create an S entry because the update requires a score above the default. For one token tagged S, a missing lexical score can seed an S entry at . The guard checks the completed start item; it does not detect every internal arithmetic overflow.
PythonIn [21]Expand
def build(i, j, A, back):
entry = back[i][j][A]
if entry is None:
return (A, None)
k, B, C = entry
return (A, [build(i, k, B, back), build(k, j, C, back)])
best_label = "S"
if not np.isfinite(chart[0][len(words)].get(best_label, NEG)):
raise ValueError("CKY reconstruction requires a finite full-span S score")
best_tree = build(0, len(words), best_label, back)ConsoleOut [22]Expand
S
NP
Det
N
VP
VP
V
NP
Det
N
PP
P
NP
Det
N
best score: -2.40The parser chooses the verb-attachment reading, where "with a telescope" modifies "saw". With the supplied scores, noun attachment scores half a point lower. With every other score fixed, exact arithmetic gives a tie when the noun-attachment rule rises from to , and gives noun attachment the higher score above . Floating-point sums can still tie close to that threshold. The choice depends on how the model scores the two attachments.
Enumerating the Ambiguity
For this fixture, enumerate the two licensed full-span parses and compare their scores. With missing lexical scores the helper can also return candidates at , since the final filter only checks the root category.
PythonIn [23]Expand
def enumerate_parses(i, j):
if j - i == 1:
t = tags[i]
return [(lex.get((t, words[i]), NEG), (t, None))]
out = []
for k in range(i + 1, j):
left = enumerate_parses(i, k)
right = enumerate_parses(k, j)
for (A, B, C), r in rules.items():
for sl, tl in left:
if tl[0] != B:
continue
for sr, tr in right:
if tr[0] != C:
continue
out.append((r + sl + sr, (A, [tl, tr])))
return out
parses = [p for p in enumerate_parses(0, len(words)) if p[1][0] == "S"]ConsoleOut [24]Expand
number of parses: 2
score -2.40
S
NP
Det
N
VP
VP
V
NP
Det
N
PP
P
NP
Det
N
score -2.90
S
NP
Det
N
VP
V
NP
NP
Det
N
PP
P
NP
Det
NThere are exactly two parses, differing only in where the prepositional phrase attaches. CKY found the higher-scoring one. The best enumerated score on this fixture matches chart[0][len(words)]["S"].
Scoring Constituents
The function below extracts a multiset of labeled half-open spans. It counts an internal root and skips every preterminal, including a preterminal root in a one-token tree. Repeated identical labeled spans in a unary chain retain their multiplicity through Counter. The toy grammar has no unary rules. Both trees in this comparison have internal roots and positive constituent counts, so precision and recall are defined. With positive total constituent count, the count formula for F1 gives zero when no constituents match.
PythonIn [25]Expand
def constituents(tree, start=0):
label, kids = tree
if kids is None:
return Counter(), start + 1
out = Counter()
j = start
for kid in kids:
spans, j = constituents(kid, j)
out.update(spans)
out[(start, j, label)] += 1
return out, j
pred_spans, _ = constituents(best_tree)
gold_spans, _ = constituents(parses_sorted[-1][1]) # the lower-scoring reading
tp = sum((pred_spans & gold_spans).values())
pred_count = sum(pred_spans.values())
gold_count = sum(gold_spans.values())
precision = tp / pred_count
recall = tp / gold_count
f1 = 2 * tp / (pred_count + gold_count)
exact = pred_spans == gold_spansConsoleOut [26]Expand
predicted constituents: 7 gold constituents: 7 matched: 6 precision=0.857 recall=0.857 F1=0.857 exact match: False
The parser gets six of seven constituents right and still produces the wrong structure. F1 is 0.857, while exact match is zero. The metric records one missing gold span and one spurious predicted span, while exact match records the difference in scored constituents. The fixture illustrates partial credit; it does not measure the downstream cost of that semantic distinction.
Attachment Scores on a Small Corpus
Now the dependency metrics on a hand-built, fixed-tokenization corpus, using the same zero-based/self-root convention and literal legacy-style labels as the worked table. It is a scoring fixture, not a measured parser benchmark or a UD conversion. The predictions are written to exhibit specific error types:
- The preposition "on" attaches to "cat" instead of "sat".
- The relative clause headed by "lives" attaches to "reads" instead of "man".
- A label confusion between
dobjandobj. - A passive-versus-active subject confusion.
PythonIn [27]Expand
corpus = [
{
"tokens": ["The", "cat", "sat", "on", "the", "mat", "."],
"gold": [
(1, "det"),
(2, "nsubj"),
(2, "root"),
(2, "prep"),
(5, "det"),
(3, "pobj"),
(2, "punct"),
],
"pred": [
(1, "det"),
(2, "nsubj"),
(2, "root"),
(1, "prep"),
(5, "det"),
(3, "pobj"),
(2, "punct"),
],
},
{
"tokens": ["She", "gave", "him", "a", "book", "about", "birds", "."],
"gold": [
(1, "nsubj"),
(1, "root"),
(1, "iobj"),
(4, "det"),
(1, "dobj"),
(4, "prep"),
(5, "pobj"),
(1, "punct"),
],
"pred": [
(1, "nsubj"),
(1, "root"),
(1, "iobj"),
(4, "det"),
(1, "dobj"),
(1, "prep"),
(5, "pobj"),
(1, "punct"),
],
},
{
"tokens": [
"The",
"old",
"man",
"who",
"lives",
"next",
"door",
"reads",
"many",
"books",
".",
],
"gold": [
(2, "det"),
(2, "amod"),
(7, "nsubj"),
(4, "nsubj"),
(2, "rcmod"),
(6, "amod"),
(4, "npadvmod"),
(7, "root"),
(9, "amod"),
(7, "dobj"),
(7, "punct"),
],
"pred": [
(2, "det"),
(2, "amod"),
(7, "nsubj"),
(4, "nsubj"),
(7, "rcmod"),
(6, "amod"),
(4, "npadvmod"),
(7, "root"),
(9, "amod"),
(7, "obj"),
(7, "punct"),
],
},
{
"tokens": [
"They",
"were",
"seen",
"by",
"the",
"committee",
"in",
"June",
".",
],
"gold": [
(2, "nsubjpass"),
(2, "auxpass"),
(2, "root"),
(2, "prep"),
(5, "det"),
(3, "pobj"),
(2, "prep"),
(6, "pobj"),
(2, "punct"),
],
"pred": [
(2, "nsubj"),
(2, "auxpass"),
(2, "root"),
(2, "prep"),
(5, "det"),
(3, "pobj"),
(5, "prep"),
(6, "pobj"),
(2, "punct"),
],
},
]PythonIn [28]Expand
def corpus_uas_las(corpus):
total = uas_ok = las_ok = 0
for sent in corpus:
if len(sent["gold"]) != len(sent["pred"]) or len(sent["gold"]) != len(
sent["tokens"]
):
raise ValueError("Fixed-token evaluation requires aligned arrays")
for g, p in zip(sent["gold"], sent["pred"]):
total += 1
if g[0] == p[0]:
uas_ok += 1
if g[1] == p[1]:
las_ok += 1
if total == 0:
raise ValueError("Attachment fractions require scored words")
return uas_ok / total, las_ok / total, total
uas, las, total_tokens = corpus_uas_las(corpus)ConsoleOut [29]Expand
evaluated tokens: 35 UAS = 0.8857 LAS = 0.8286 label-only error fraction (UAS - LAS) = 0.0571
Out of 35 tokens, 4 heads are wrong and 2 more have the right head with the wrong label. UAS is 0.886 and LAS is 0.829. The 5.7 percentage-point gap counts the two label-only errors in this fixture.
Per-Relation Precision, Recall, and F1
Micro-averaged scores hide which relations are failing. This breakdown computes precision, recall, and F1 per label. Pass matching gold and predicted lists for each sentence, with one head and relation pair per scored word in the same order.
PythonIn [30]Expand
def label_prf(corpus):
tp, fp, fn = Counter(), Counter(), Counter()
for sent in corpus:
for g, p in zip(sent["gold"], sent["pred"]):
if g == p:
tp[g[1]] += 1
else:
fn[g[1]] += 1
fp[p[1]] += 1
rows = []
for L in sorted(set(tp) | set(fp) | set(fn)):
prec = tp[L] / (tp[L] + fp[L]) if tp[L] + fp[L] else 0.0
rec = tp[L] / (tp[L] + fn[L]) if tp[L] + fn[L] else 0.0
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
rows.append((L, tp[L], fp[L], fn[L], prec, rec, f1))
return rows
rows = label_prf(corpus)ConsoleOut [31]Expand
label TP FP FN P R F1 amod 3 0 0 1.00 1.00 1.00 auxpass 1 0 0 1.00 1.00 1.00 det 5 0 0 1.00 1.00 1.00 dobj 1 0 1 1.00 0.50 0.67 iobj 1 0 0 1.00 1.00 1.00 npadvmod 1 0 0 1.00 1.00 1.00 nsubj 4 1 0 0.80 1.00 0.89 nsubjpass 0 0 1 0.00 0.00 0.00 obj 0 1 0 0.00 0.00 0.00 pobj 4 0 0 1.00 1.00 1.00 prep 1 3 3 0.25 0.25 0.25 punct 4 0 0 1.00 1.00 1.00 rcmod 0 1 1 0.00 0.00 0.00 root 4 0 0 1.00 1.00 1.00
The prep relation has both false positives and false negatives, because three of the head errors involve a prep arc. The dobj relation has a false negative with no compensating false positive, because the model predicted obj instead. The nsubj relation is contaminated by the passive construction, where the gold label is nsubjpass but the model predicted nsubj.
None of this is visible in the aggregate LAS.
Simulating a Parser to Study Error Structure
The four-sentence fixture shows the calculations; the next simulation supplies more attachment decisions for grouped diagnostics. To study error patterns by attachment distance and label, we simulate explicit error rules: head-change attempts use a distance-dependent probability capped at 0.8, and label changes follow a fixed confusion pattern.
PythonIn [32]Expand
LABELS = ["det", "amod", "nsubj", "dobj", "prep", "pobj", "aux"]
LABEL_P = np.array([0.24, 0.16, 0.20, 0.16, 0.10, 0.10, 0.04])
LABEL_P = LABEL_P / LABEL_P.sum()
CONFUSABLE = {
"det": "amod",
"amod": "det",
"nsubj": "dobj",
"dobj": "nsubj",
"prep": "pobj",
"pobj": "prep",
"aux": "prep",
}
def random_projective_parents(n, rng):
parent = [-1] * n
stack = [(0, n - 1, -1)]
while stack:
i, j, h = stack.pop()
if i > j:
continue
r = int(rng.integers(i, j + 1))
parent[r] = h
stack.append((i, r - 1, r))
stack.append((r + 1, j, r))
return parent
def creates_cycle(parent, d, new_head):
x = new_head
while x != -1:
if x == d:
return True
x = parent[x]
return FalsePythonIn [33]Expand
def simulate(n_sents=400, seed=7):
rng = np.random.default_rng(seed)
gold_all, pred_all = [], []
for _ in range(n_sents):
n = int(rng.integers(6, 16))
parent = random_projective_parents(n, rng)
labels = [
"root" if parent[d] == -1 else str(rng.choice(LABELS, p=LABEL_P))
for d in range(n)
]
gold_all.append((parent, labels))
pparent = parent[:]
for d in range(n):
if parent[d] == -1:
continue
dist = abs(parent[d] - d)
p_err = min(0.8, 0.03 + 0.05 * dist)
if rng.random() < p_err:
cands = [x for x in range(n) if x != d and x != pparent[d]]
rng.shuffle(cands)
for c in cands:
if not creates_cycle(pparent, d, c):
pparent[d] = c
break
plabels = []
for d in range(n):
if pparent[d] == -1:
plabels.append("root")
elif rng.random() < 0.18:
plabels.append(CONFUSABLE.get(labels[d], labels[d]))
else:
plabels.append(labels[d])
pred_all.append((pparent, plabels))
return gold_all, pred_all
gold_all, pred_all = simulate()PythonIn [34]Expand
def corpus_scores(gold_all, pred_all):
total = uas_ok = las_ok = 0
if len(gold_all) != len(pred_all):
raise ValueError("Gold and prediction corpora must align")
for (gp, gl), (pp, pl) in zip(gold_all, pred_all):
if not (len(gp) == len(gl) == len(pp) == len(pl)):
raise ValueError("Head and label arrays must align")
for gh, gL, ph, pL in zip(gp, gl, pp, pl):
total += 1
if gh == ph:
uas_ok += 1
if gL == pL:
las_ok += 1
if total == 0:
raise ValueError("Attachment fractions require scored words")
return uas_ok / total, las_ok / total, total
sim_uas, sim_las, sim_tokens = corpus_scores(gold_all, pred_all)ConsoleOut [35]Expand
simulated tokens: 4,230 UAS = 0.8901 LAS = 0.7475 gap = 0.1426
This simulation is not a trained parser or an empirical model of a language. Its recursive generator samples a restricted binary family of projective trees, not uniformly from every projective tree. Given a sampled tree, each non-root gold label is drawn independently from the chosen frequencies; the gold root label is fixed. The root is always preserved. Head-change attempts follow the distance-based probability in the code and are accepted only if they avoid a cycle; predicted trees need not remain projective. These deliberate assumptions make it possible to trace a diagnostic pattern to its generating mechanism, but they do not establish that real parser errors follow the same pattern. For distance bucketing, pass gold and predicted head lists aligned by sentence and word, with one prediction for each gold word.
PythonIn [36]Expand
EDGES = [(1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 8), (9, math.inf)]
def accuracy_by_distance(gold_all, pred_all, edges):
stats = {e: [0, 0] for e in edges}
for (gp, _), (pp, _) in zip(gold_all, pred_all):
for d, gh in enumerate(gp):
if gh == -1:
continue
dist = abs(gh - d)
for lo, hi in edges:
if lo <= dist <= hi:
stats[(lo, hi)][1] += 1
if pp[d] == gh:
stats[(lo, hi)][0] += 1
break
else:
raise ValueError(
"Distance buckets must cover every non-root arc"
)
return stats
dist_stats = accuracy_by_distance(gold_all, pred_all, EDGES)
dist_acc = [
correct / total if total else np.nan
for correct, total in dist_stats.values()
]
dist_labels = [
f"{lo}+" if math.isinf(hi) else f"{lo}" if lo == hi else f"{lo}-{hi}"
for lo, hi in EDGES
]
non_root_correct = sum(v[0] for v in dist_stats.values())
non_root_total = sum(v[1] for v in dist_stats.values())
non_root_uas = non_root_correct / non_root_total if non_root_total else np.nanVisualizationOut [37]Expand

The longer-distance buckets have lower accuracy under this selected error process. The buckets cover every positive gold attachment distance, including distances above 99. An empty bucket has undefined accuracy (np.nan), shown without a bar; a corpus with no non-root arcs also has undefined non_root_uas. For a positive non-root total, weighting only occupied-bucket accuracies by their denominators recovers non_root_uas; the earlier sim_uas also includes perfectly preserved root words. This distinction matters when making a plot agree with an aggregate metric. On real outputs, compute bucket counts and inspect uncertainty before drawing a conclusion about particular constructions such as coordination or relative clauses.
For the confusion matrix, align the gold and predicted relation lists by sentence and word. Include each observed gold or predicted relation exactly once in labels.
PythonIn [38]Expand
def confusion_matrix(gold_all, pred_all, labels):
idx = {L: i for i, L in enumerate(labels)}
M = np.zeros((len(labels), len(labels)), dtype=int)
for (_, gl), (_, pl) in zip(gold_all, pred_all):
for g, p in zip(gl, pl):
M[idx[g], idx[p]] += 1
return M
CONF_LABELS = ["root"] + LABELS
M = confusion_matrix(gold_all, pred_all, CONF_LABELS)
def prf_from_matrix(M, labels):
rows = []
for i, L in enumerate(labels):
tp = M[i, i]
fp = M[:, i].sum() - tp
fn = M[i, :].sum() - tp
prec = tp / (tp + fp) if tp + fp else 0.0
rec = tp / (tp + fn) if tp + fn else 0.0
f1 = 2 * prec * rec / (prec + rec) if prec + rec else 0.0
rows.append((L, prec, rec, f1))
return rows
label_prf_rows = prf_from_matrix(M, CONF_LABELS)
def attachment_prf(gold_all, pred_all, labels):
corpus_scores(gold_all, pred_all) # Validate the aligned arrays.
tp, fp, fn = Counter(), Counter(), Counter()
for (gh, gl), (ph, pl) in zip(gold_all, pred_all):
for gold_head, gold_label, pred_head, pred_label in zip(gh, gl, ph, pl):
if gold_head == pred_head and gold_label == pred_label:
tp[gold_label] += 1
else:
fn[gold_label] += 1
fp[pred_label] += 1
rows = []
for label in labels:
precision = (
tp[label] / (tp[label] + fp[label])
if tp[label] + fp[label]
else 0.0
)
recall = (
tp[label] / (tp[label] + fn[label])
if tp[label] + fn[label]
else 0.0
)
f1 = (
2 * tp[label] / (2 * tp[label] + fp[label] + fn[label])
if tp[label] + fp[label] + fn[label]
else 0.0
)
rows.append((label, precision, recall, f1))
return rows
prf_rows = attachment_prf(gold_all, pred_all, CONF_LABELS)VisualizationOut [39]Expand

VisualizationOut [41]Expand

The off-diagonal label confusions follow the declared mapping: nsubj/dobj, prep/pobj, and det/amod, plus the one-way replacement aux → prep. This is a check of the generator and diagnostic, not evidence about the linguistic cause of errors in a real system. The paired F1 bars distinguish label-only agreement from attachment-aware relation correctness. An arc-factored scorer may use rich contextual input representations, so first-order output factorization does not imply that it cannot distinguish a particular relation pair.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!