AI Wiki中文/EN

Dependency parsing: choose parents that form a tree

依存句法分析

Derive a projective chart parser from fixed arc scores, enforce a single root child, and check cycles, crossing arcs and attachment metrics.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Good-looking arrows can make a bad structure

Imagine assigning arrows in the invented sentence Ada reads books. A simple dependency analysis can use reads as the head of both Ada and books. Add an artificial root outside the sentence and attach reads to it. The arrows express relations between tokens rather than introducing the phrase nodes used in constituency parsing.

Now suppose a scoring model independently prefers token 1 as the parent of token 2 and token 2 as the parent of token 1. Each token has exactly one parent, but following those parents never reaches the root. The result is a cycle, not a dependency tree. Local scores need a global structural constraint.

This chapter takes the arc scores as given and solves that structural problem. It does not train a scorer or infer relation labels. The distinction matters: a correct search algorithm can still select a linguistically poor tree when its scores are poor. Arc-factored parsing separates scoring from constrained search. Spanning-tree formulation, §2.1

Arc scores, projectivity and the single-root constraint can change the winning tree. These are the exact head arrays returned by the program below.
Arc scores, projectivity and the single-root constraint can change the winning tree. These are the exact head arrays returned by the program below.

Define the allowed trees before maximizing a score

Heads, the artificial root and projectivity

Number tokens 1,…,n and place artificial root 0 to their left. Store a head h_d for each dependent d. Every non-root token has exactly one head; it cannot head itself. No arc enters 0, parent chains must reach 0, and cycles are forbidden. Our default additionally requires exactly one token with head 0. That one token is the sentence’s syntactic root. The artificial root and its one child are different nodes.

Some graph formulations permit the artificial root to have multiple children. We expose that as single_root=False; it is still one connected tree including 0, but it has several sentence tokens directly attached to 0. Do not call such a tree single-root under the default one-child convention. Empty input is handled separately and has no sentence root child.

A tree is projective here when its arcs, drawn above the ordered tokens including 0, do not cross. Arcs sharing an endpoint do not count as crossings. An equivalent view for these rooted trees is that every node together with all its descendants occupies a contiguous region. The root arc participates in the check. Dropping it can make a nonprojective tree appear acceptable.

Eisner’s paper develops a bottom-up cubic parsing method using spans and signatures. The original paper places an EOS root on the right and discusses joint probabilistic models. Our fixed-score chart uses root 0 on the left, explicit one-root-child control and a max-sum objective; it is not a replication of those probabilistic models. Eisner, parsing algorithm

Add arc scores, not independent parent decisions

Let s(h,d) be a real score for arc h→d. A disallowed arc has score negative infinity. Score a complete tree by:

S(h)=∑d=1ns(hd,d),h∗=arg max⁡h∈Tproj,1S(h).S(h)=\sum_{d=1}^{n}s(h_d,d),\qquad h^*=\operatorname*{arg\,max}_{h\in\mathcal T_{\mathrm{proj},1}}S(h).

The subscript denotes the projective tree set with one artificial-root child. Scores need not be probabilities and need not normalize. McDonald and colleagues describe the same edge-additive objective over directed trees and distinguish projective from unrestricted spanning-tree search. Spanning-tree formulation, §2

Independently taking the best incoming arc maximizes the sum only if the resulting assignments satisfy all required structural constraints. It can create a cycle, multiple root children or crossings. Deleting a bad arc afterward also leaves a token without a parent unless a valid replacement is chosen. Constrained decoding must compare complete alternatives.

Complete and incomplete span states

Use inclusive endpoint intervals [i,j], including root 0 where needed. This differs from the half-open phrase spans in the constituency chapter. Each interval has two orientations. R means its head is the left endpoint i; L means its head is the right endpoint j.

A complete state C has finished the dependents within this span on the relevant side of its endpoint head. An incomplete state I contains the new arc connecting the two endpoints but will still be combined with another span. “Incomplete” names a chart state, not an invalid final tree. These four state types let us build a projective tree without enumerating every head assignment.

Initialize C^R_i,i=C^L_i,i=0. Other entries start at negative infinity. First create an incomplete item by splitting into a left-rooted complete piece and a right-rooted complete piece, then add the endpoint arc:

Ii,jR=s(i,j)+max⁡i≤k<j{Ci,kR+Ck+1,jL},Ii,jL=s(j,i)+max⁡i≤k<j{Ci,kR+Ck+1,jL}.I^R_{i,j}=s(i,j)+\max_{i\le k<j}\{C^R_{i,k}+C^L_{k+1,j}\},\qquad I^L_{i,j}=s(j,i)+\max_{i\le k<j}\{C^R_{i,k}+C^L_{k+1,j}\}.

Next finish a side by joining an incomplete item to another complete item:

Ci,jR=max⁡i<k≤j{Ii,kR+Ck,jR},Ci,jL=max⁡i≤k<j{Ci,kL+Ik,jL}.C^R_{i,j}=\max_{i<k\le j}\{I^R_{i,k}+C^R_{k,j}\},\qquad C^L_{i,j}=\max_{i\le k<j}\{C^L_{i,k}+I^L_{k,j}\}.

The pieces in the completion step share the boundary head but do not duplicate an arc. Fill intervals in increasing width, create their incomplete items first, then their complete items. Store the maximizing splits and recover the final head array from C^R_0,n. Every added arc is recorded exactly once during recovery. This is the particular max-sum implementation used below; the original span/signature treatment motivates the decomposition. Eisner

Enforce one root child inside the recurrence

For I^R_0,j, allow only split k=0:

I0,jR=s(0,j)+C0,0R+C1,jL.I^R_{0,j}=s(0,j)+C^R_{0,0}+C^L_{1,j}.

Then completing C^R_0,n chooses one root child j and combines that child’s left and right dependents. Allowing k>0 in the incomplete root item could carry earlier root children inside C^R_0,k and add another via 0→j. The restricted split prevents that construction instead of repairing it later. Incoming-root arcs are forbidden in both modes.

The chart is exact for the stated tree family and arc-additive scores. A score involving two siblings jointly would not fit the same independent arc decomposition; changing the scoring model may require additional states or another search algorithm.

A higher score can be outside the search space

Use four abstract tokens w1,…,w4. Assign scores 4 to 2→1, 5 to 0→2, 8 to 1→3 and 4 to 2→4; all other permitted arcs score zero. The independently preferred heads are [2,0,1,2], with score 21. This is an acyclic tree with one root child, but its arcs cross.

The best projective answer is [2,0,4,2], scoring 13. The decoder has not failed to find 21: that tree is excluded by its projectivity requirement. If the application’s gold structures contain necessary crossings, the model’s structural family sets an accuracy limit even with excellent scores. The independent tests enumerate all small parent assignments to confirm this example.

Unrestricted directed maximum-spanning-tree methods can search nonprojective trees under arc-additive scoring. Chu–Liu–Edmonds begins with preferred incoming arcs and handles cycles through contraction and reconstruction; it is not “greedy choices followed by deleting a cycle.” The cited paper distinguishes a naive cubic implementation from a more efficient quadratic dense-graph implementation. Our code implements neither MST routine. A one-root-child requirement must still be enforced explicitly in an unrestricted parser. Nonprojective search, §2.2.1

Run and inspect the parent arrays

Save the complete program as dependency.py and run python dependency.py with Python 3.12.4 and NumPy 1.26.4. Input is a square score matrix including row and column 0. The function copies it before masking diagonal and incoming-root entries, so decoding does not mutate the caller’s scores. It accepts finite scores or negative infinity and rejects NaN, positive infinity and arithmetic overflow.

"""Original arc-factored projective parser with an explicit single-root policy.

Input score[head, dependent] includes artificial root0. This is a max-sum
teaching chart, not the original paper's joint tagging/probability models.
"""
import json,math
import numpy as np


def checked_scores(scores,max_tokens):
    if type(max_tokens) is not int or max_tokens<1:raise ValueError('Positive token budget required')
    a=np.asarray(scores,dtype=float)
    if a.ndim!=2 or a.shape[0]!=a.shape[1] or not len(a):raise ValueError('Square scores including root0 required')
    if np.isnan(a).any() or np.isposinf(a).any():raise ValueError('Finite scores or negative infinity required')
    if len(a)-1>max_tokens:raise ValueError('Explicit token budget exceeded; no truncation')
    a=a.copy();a[:,0]=-np.inf;np.fill_diagonal(a,-np.inf);return a


def valid_tree(heads,single_root=True):
    if not isinstance(heads,(list,tuple)) or type(single_root) is not bool:raise ValueError('Parent list and Boolean root policy required')
    n=len(heads)
    if any(type(h) is not int or h<0 or h>n or h==i for i,h in enumerate(heads,1)):return False
    if not n:return True
    if single_root and heads.count(0)!=1:return False
    for node in range(1,n+1):
        seen=set()
        while node:
            if node in seen:return False
            seen.add(node);node=heads[node-1]
    return True


def projective(heads):
    if not valid_tree(heads,single_root=False):return False
    edges=[sorted((h,d)) for d,h in enumerate(heads,1)]
    return not any(a<c<b<d or c<a<d<b for a,b in edges for c,d in edges)


def decode(scores,single_root=True,max_tokens=60):
    if type(single_root) is not bool:raise ValueError('Boolean root policy required')
    a=checked_scores(scores,max_tokens);n=len(a)-1
    if not n:return {'status':'empty','heads':[],'score':0.,'candidates':0,'finite_complete':2,'finite_incomplete':0}
    complete=np.full((n+1,n+1,2),-np.inf);incomplete=complete.copy();back_c={};back_i={};attempts=0
    for i in range(n+1):complete[i,i,:]=0
    try:
        with np.errstate(over='raise',invalid='raise'):
            for width in range(1,n+1):
                for i in range(n+1-width):
                    j=i+width
                    for direction in (0,1):
                        edge=a[j,i] if direction==0 else a[i,j]
                        splits=[0] if single_root and i==0 and direction==1 else range(i,j)
                        for split in splits:
                            attempts+=1;value=complete[i,split,1]+complete[split+1,j,0]+edge
                            if value>incomplete[i,j,direction]:incomplete[i,j,direction]=value;back_i[i,j,direction]=split
                    for split in range(i,j):
                        attempts+=1;value=complete[i,split,0]+incomplete[split,j,0]
                        if value>complete[i,j,0]:complete[i,j,0]=value;back_c[i,j,0]=split
                    for split in range(i+1,j+1):
                        attempts+=1;value=incomplete[i,split,1]+complete[split,j,1]
                        if value>complete[i,j,1]:complete[i,j,1]=value;back_c[i,j,1]=split
    except FloatingPointError as error:raise ValueError('Chart score overflow') from error
    diagnostics={'candidates':attempts,'finite_complete':int(np.isfinite(complete).sum()),'finite_incomplete':int(np.isfinite(incomplete).sum())}
    value=float(complete[0,n,1])
    if not math.isfinite(value):return {'status':'impossible','heads':None,'score':None,**diagnostics}
    heads=[None]*n;stack=[('C',0,n,1)]
    while stack:
        kind,i,j,direction=stack.pop()
        if i==j:continue
        if kind=='I':
            split=back_i[i,j,direction];head,child=(j,i) if direction==0 else (i,j)
            if child==0 or heads[child-1] is not None:raise AssertionError('Invalid recovery')
            heads[child-1]=head;stack.extend([('C',i,split,1),('C',split+1,j,0)])
        else:
            split=back_c[i,j,direction]
            stack.extend([('C',i,split,0),('I',split,j,0)] if direction==0 else [('I',i,split,1),('C',split,j,1)])
    if not valid_tree(heads,single_root) or not projective(heads):raise AssertionError('Recovered invalid tree')
    return {'status':'ok','heads':heads,'score':value,**diagnostics}


def attachment(gold,predicted,gold_labels=None,predicted_labels=None,include=None):
    if len(gold)!=len(predicted) or not valid_tree(gold) or not valid_tree(predicted):raise ValueError('Aligned single-root trees required')
    n=len(gold);mask=[True]*n if include is None else include
    if not isinstance(mask,(list,tuple)) or len(mask)!=n or any(type(x) is not bool for x in mask):raise ValueError('One explicit Boolean per token required')
    labeled=gold_labels is not None or predicted_labels is not None
    if labeled and (not isinstance(gold_labels,(list,tuple)) or not isinstance(predicted_labels,(list,tuple)) or len(gold_labels)!=n or len(predicted_labels)!=n):raise ValueError('Aligned labels required')
    total=sum(mask);correct=sum(use and a==b for use,a,b in zip(mask,gold,predicted))
    joint=sum(use and a==b and x==y for use,a,b,x,y in zip(mask,gold,predicted,gold_labels,predicted_labels)) if labeled else None
    return {'evaluated_tokens':total,'correct_heads':correct,'uas':correct/total if total else None,
            'correct_labeled_arcs':joint,'las':joint/total if labeled and total else None}


def demo():
    # A nonprojective preferred tree: 2->1, root->2, 1->3, 2->4.
    a=np.zeros((5,5))
    for h,d,s in [(2,1,4),(0,2,5),(1,3,8),(2,4,4)]:a[h,d]=s
    preferred=[2,0,1,2];r=decode(a)
    roots=np.zeros((4,4));roots[0,1:]=9
    gold=[2,0,2,2];pred=[2,0,4,2]
    return {'tokens':['w1','w2','w3','w4'],'scores':a.tolist(),'preferred_nonprojective':{'heads':preferred,'valid':valid_tree(preferred),'projective':projective(preferred),'score':21},
            'best_projective':r,'single_root':decode(roots),'multiple_roots':decode(roots,False),
            'attachment_all':attachment(gold,pred,['subj','root','obj','punct'],['subj','root','obj','dep']),
            'attachment_without_last':attachment(gold,pred,['subj','root','obj','punct'],['subj','root','obj','dep'],[True,True,True,False]),
            'scope':'Original fixed arc scores with max-sum projective chart, root0 on the left and explicit one-root-child constraint. Not the original Eisner joint tagging models, a nonprojective MST parser, a UD evaluation script or a corpus benchmark. Diagonal and incoming-root scores are forbidden.'}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2,allow_nan=False))

The four-token crossing example returns the score-13 tree described above. A second example gives each root→word arc score 9 for three words, with every other permitted arc zero. The single-root mode returns [0,1,2] with score 9; the multiple-root-child mode returns [0,0,0] with score 27. These are tied-order choices where applicable, not linguistic demonstrations.

There are O(n²) span states and O(n) splits per state, giving O(n³) decoding time and O(n²) chart/backpointer space. The diagnostics count all attempted candidates, including those involving impossible scores. With n real tokens, the unrestricted loop tries:

2n(n+1)(n+2)3\frac{2n(n+1)(n+2)}3

candidates. Restricting the root split removes n(n−1)/2 of those attempts. For the four-token example this is 80−6=74. The formulas describe this implementation’s loops, not every possible optimized parser.

The default token budget is 60; larger input is rejected rather than truncated. An impossible constrained problem returns impossible with no heads or score. Empty input returns an empty head list and score zero under an explicit separate convention. Recovery rechecks reachability, root count and projectivity so a plausible score cannot hide a malformed tree.

Measure the head and the relation separately

Unlabeled attachment score, UAS, measures whether the head is correct. Labeled attachment score, LAS, requires both the head and the relation label to match. With an explicit inclusion mask m_d and M equal to its number of true entries:

UAS=∑dmd1[hd=h^d]M,LAS=∑dmd1[hd=h^d,  rd=r^d]M.\mathrm{UAS}=\frac{\sum_d m_d\mathbf1[h_d=\widehat h_d]}{M},\qquad \mathrm{LAS}=\frac{\sum_d m_d\mathbf1[h_d=\widehat h_d,\;r_d=\widehat r_d]}{M}.

Our scorer takes labels as an optional separate input; the parser does not predict them. It uses gold heads [2,0,2,2] and predicted heads [2,0,4,2]. Three heads match, so UAS=3/4. The supplied labels also disagree at the final token, leaving only two correct labeled arcs, so LAS=2/4. A correct label attached to the wrong head does not count toward LAS.

An explicit mask excluding the final token changes both scores to 2/3. The function does not decide which tokens are punctuation. It rejects misaligned arrays, requires valid single-root trees for this scoring interface, and returns null when no tokens are included. These are declared educational conventions, not a claim to reproduce an official dependency evaluation script.

Search accuracy is not language accuracy

The decoder sees no words, word classes or contextual representations beyond the supplied scores. A real scorer must be trained and evaluated on a declared treebank, head convention, relation inventory and tokenization policy. Two annotation schemes can choose different heads for the same construction; a comparison must not treat those systematic differences as accidental model errors.

This projective arc-factored parser has two deliberate limits: it excludes crossing trees and it adds individual arc scores. Nonprojective spanning-tree search expands the first choice without by itself adding sibling or grandparent interactions. Richer scoring features do not automatically expand the permitted tree set. Keep those choices separate when diagnosing an error. Spanning-tree formulation and projective comparison

Report token alignment, root policy, punctuation mask, sentence-length behavior and known failure cases along with UAS/LAS. For a downstream extractor, test whether predicted relations improve the actual task over a simpler baseline; a high attachment score alone does not prove that a particular relation path is trustworthy.

Finally, dependency arrows express syntactic analysis, not causal direction. An arrow from a verb to its subject does not claim that the verb caused that person. The graph’s semantics come from its task definition, not from the visual appearance of arrows.

Separate scores from constraints

  1. Understanding. Why does the head array [2,1] fail even though both words have one head and neither heads itself?

Answer: The two words form a cycle, 1→2→1, and neither parent chain reaches artificial root 0. One-parent assignments alone do not establish a rooted tree.

  1. Hand calculation. In the four-token example, what happens to the score when head 1 for dependent 3 is replaced by head 4, leaving all other heads unchanged?

Answer: The score-8 arc 1→3 is replaced by the score-0 arc 4→3, reducing 21 to 13. The replacement permits the projective tree [2,0,4,2]; the larger score belonged to an excluded crossing tree.

  1. Boundary case. Three root→word arcs score 9 and all other arcs score zero. Why do the two root modes attain 9 and 27?

Answer: Exactly one root child permits only one score-9 root arc; the remaining two arcs score zero. Multiple children permit all three root arcs, totaling 27. Both results connect to the artificial root, but only the first meets the one-child rule.

  1. Transfer. Add a constant c_d to every permitted incoming score for dependent d. Does the best tree change if the allowed tree set is held fixed?

Answer: No. Every complete tree uses exactly one incoming arc per dependent, so every tree gains the same sum of c_d. Rankings stay unchanged. This does not justify changing masks or root policy, because those operations change the allowed structures rather than applying a common score shift.

Two references answer different search questions

Jason M. Eisner’s 1996 paper, Three New Probabilistic Models for Dependency Parsing: An Exploration, supplies the span/signature algorithm context. The inspected method range is cached text 256–321, with physical page 4 viewed to check damaged OCR. This chapter does not reproduce its joint tagging models or performance results. Original paper

Ryan McDonald, Fernando Pereira, Kiril Ribarov and Jan Hajič’s 2005 paper supplies the edge-additive and directed-spanning-tree comparison. The inspected scope covers §2.1, the relevant §2.2.1 graph/cycle discussion and §2.2.2 opening. No large-margin training or Czech benchmark was reproduced. Spanning-tree paper

The original tests use parent-assignment enumeration and a descendant-based projectivity check independent of the chart’s crossing check. They verify best scores, one versus multiple root children, impossible nonprojective-only inputs, cycles, column-shift invariance, candidate counts, input preservation and attachment metrics. That is evidence for the stated decoder and examples, not a complete NLP system.

Make a prediction, then check

An acyclic single-root tree scores21 but has crossing arcs. The projective parser returns score13. What does this establish?

Choose one answer

Learning objectives

  • Validate parent arrays, root policy, cycles and projectivity.
  • Derive complete/incomplete chart recurrences from arc scores.
  • Distinguish projective decoding from unrestricted directed MST search.
  • Compute head and labeled attachment scores with explicit token masks.

Prerequisites & connections

Explore related knowledge →

References

  1. Three New Probabilistic Models for Dependency Parsing: An Exploration
    Jason M. Eisner · 1996
  2. Non-Projective Dependency Parsing using Spanning Tree Algorithms
    Ryan McDonald; Fernando Pereira; Kiril Ribarov; Jan Hajič · 2005

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-12 · Codex single-AI-author technical check: scoped Eisner and McDonald arc-factored/projectivity methods; six paired equations and four explained exercises. Fixed arc max-sum projective chart with left root and explicit single-root condition differs from source probabilistic training. Independent parent enumeration/subtree projectivity, forbidden arcs, root policy reversal, overflow, UAS/LAS and filtered denominators. MST described but not implemented; no benchmark reproduction.

  • Codex single-AI-author technical check: scoped Eisner and McDonald arc-factored/projectivity methods; six paired equations and four explained exercises. Fixed arc max-sum projective chart with left root and explicit single-root condition differs from source probabilistic training. Independent parent enumeration/subtree projectivity, forbidden arcs, root policy reversal, overflow, UAS/LAS and filtered denominators. MST described but not implemented; no benchmark reproduction.
  • Four original SVGs bind the exact MDX program. Nine figure tests validate numeric results, encodings and dependency arc geometry. Thirty standalone language/width cases and four fallback fonts passed; ten desktop/mobile screenshots were actually inspected. The original false arc crossing and its correction evidence are preserved. Complete article browser acceptance is separate; no human peer review or upstream execution.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.