Algorithmcore
Maximum spanning tree dependency parsing
Also called MST parser, graph-based dependency parsing.
Score every possible arc and take the maximum spanning arborescence by Chu-Liu-Edmonds, which allows non-projective trees.
- Solves
- Dependency parsing
- Time
- O(n^3) worstΘ(n^2) best
- Space
- O(n^3) extra
- Where
- n = the number of words of the sentence
- Model
- Word RAM
- Properties
- deterministicofflinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Ryan McDonald, Fernando Pereira, Kiril Ribarov, Jan Hajič, 2005
Maximum spanning tree (MST) dependency parsing finds the best dependency tree of a sentence, projective or not, when the score of a tree is the sum of the scores of its arcs. The words and the artificial root are the nodes of a complete directed graph, each possible arc carries the score , and a dependency tree is exactly a spanning arborescence rooted at the root. So the parser takes a maximum spanning arborescence, with the algorithm of Chu and Liu (1965) and Edmonds (1967). Each word first takes its best head. If that makes a cycle, the cycle is contracted into one node, the arcs into it are rescored, and the smaller problem is solved; then the cycle is opened at the one word that takes a head from outside. McDonald, Pereira, Ribarov and Hajič (2005) introduced this view of parsing. The simple recursive form runs in time for words, and Tarjan's form in , which is optimal for a dense score matrix. Unlike the Eisner algorithm, it can return crossing arcs.
In plain words
Every word must choose one word it belongs to, or the start symbol, and each choice has a score. First let each word take its best choice alone. If the choices lead back to the start without loops, they form a tree and nothing can do better. If some words choose each other in a loop, at least one of them must look outside the loop instead. Treat the loop as one big word. Price each outside choice by how much it would cost the loop to accept it, that is, its score minus the score of the loop link it replaces. Solve this smaller problem in the same way. Then open the loop: the winning outside choice tells which word leaves the loop, and the other words keep their loop links.
The problem
The words are and 0 is the root. The input is a matrix of arc scores , real numbers of any sign, for , , . For labeled parsing, take and keep the best label of each arc. The output is a head list that forms a tree rooted at 0 and maximizes , over all trees, projective or not. In the main version the root may have any number of children. In the single-root version it has exactly one; the page shows how to enforce that below.
The algorithm
The recursion works on a general directed graph with node set , root and arc scores . At the top level , and .
CLE(V, rho, w) ▷ returns a head for every v in V other than rho- 1
for each v in V, v != rho: best[v] <- argmax over u of w(u, v) - 2
look for a cycle C in the arcs best[v] -> v - 3
if there is none then return best - 4
add a new node c that stands for C; S <- sum over v in C of w(best[v], v) - 5
build w' on V' = (V - C) + {c}: for u outside C: w'(u, c) <- max over v in C of w(u, v) - w(best[v], v) + Sfor d outside C: w'(c, d) <- max over v in C of w(v, d)arcs between nodes outside C keep their scores- 6
head' <- CLE(V', rho, w') - 7
map head' back: the arc u -> c becomes u -> v for the v in C that gave its maximum, an arc c -> d becomes v -> d for the v in C that gave its maximum, others stay- 8
every v in C that got no head in L7 keeps best[v] - 9
return the heads
The parser calls CLE({0, ..., n}, 0, s). Each maximum in line L5 also records which cycle node gave it, so that line L7 can undo the contraction.
One child of the root. For the single-root version, run CLE times. In run , delete every root arc except . Return the best of the trees. Each run gives the best tree in which the root has the single child , so the best of them is the best single-root tree. Deleting the extra root arcs from the unconstrained tree does not work.
Example
Take John saw Mary, words 1 to 3, with the scores (row , column )
| 1 John | 2 saw | 3 Mary | |
|---|---|---|---|
| 0 root | 9 | 10 | 9 |
| 1 John | 20 | 3 | |
| 2 saw | 30 | 30 | |
| 3 Mary | 11 | 0 |
Line L1. The best head of John is saw (30), of saw is John (20), and of Mary is saw (30).
Line L2. John and saw head each other: the cycle , with .
Line L5. Contract into . The scores into :
- from the root: through John, ; through saw, . So , entering at saw.
- from Mary: through John, ; through saw, . So , entering at John.
The scores out of : , leaving from saw. The root arc stays.
Line L6. In the graph on , the best head of is the root (40 against 31) and the best head of Mary is (30 against 9). There is no cycle, and the score is .
Lines L7 and L8. The arc came through saw, so saw takes the root as head and the cycle arc John saw is dropped. The arc came from saw, so Mary takes saw. John got no head from L7 and keeps saw. The result is the head list [-1, 2, 0, 2] with score , the same as the value of the contracted problem. This tree is projective, so the Eisner algorithm finds it too.
A non-projective answer. With four words and the scores and 0 for all other arcs, CLE returns [-1, 4, 0, 2, 2] with score 40. The arc passes over word 2, the head of 4, so the tree is not projective, and the best projective tree scores less. The tests check both facts.
Correctness
Line L1 gives an upper bound: every word gets its best entering arc, and no tree can score more than the sum of these. If these arcs have no cycle, they form a tree, and the bound is met. If there is a cycle , a short exchange argument shows that some best tree contains all arcs of but one: take a best tree, find the first node of on its path from the root, and give every other node of its cycle arc; the result is still a tree and does not score less, since each new arc is the best into its node. The trees with this form correspond one to one to the trees of the contracted graph, and the rescoring of line L5 makes the scores equal: a tree that enters at from scores plus its other arcs, which is plus the same arcs. So the best tree of the contracted graph, mapped back, is a best tree of the original graph. Induction on the number of nodes completes the proof, which is in the correctness proof. The single-root version is correct because the runs cover all trees with one root child, each run exactly.
Proof: Chu-Liu-Edmonds returns a maximum spanning arborescence, and the parser returns a best dependency treefull
Let be a directed graph with node set , a root and real arc scores , in which every node other than has at least one entering arc and no arc enters . An arborescence of is a set of arcs that gives every exactly one entering arc, its head , such that the chain reaches . Its score is . The claim is that returns an arborescence of largest score when one exists. For the parser, , , the graph is complete, and the arborescences are exactly the dependency trees.
Lemma 1 (no cycle). Let be the arcs of line L1. If has no cycle, is a maximum arborescence.
Proof. Each has one head in . Follow the heads from . The nodes are finite and no node repeats, because a repeat would be a cycle of ; the only node without a head is , so the chain ends at . So is an arborescence. Any arborescence has for each , so .
Now let be a cycle of , found in line L2. Then , because has no head in . Write and, for , , the score of the arcs of other than the one into .
Lemma 2 (exchange). Some maximum arborescence contains all the arcs of but one.
Proof. Let be a maximum arborescence. Let be a node of whose path in from contains no other node of . Such a node exists: take any node of , its path in from , and the first node of on that path. Let be with the head of every , , changed to . Each node still has one head. Every node reaches in : the path from to in uses no node of other than , so no head on it changed; each node of reaches along the cycle backwards, through heads that are in ; and a node follows its chain in , whose heads did not change until the chain meets , if it does. So is an arborescence. Each changed head became the best head of its node, so , and is maximum. contains every arc of except possibly the one into ; it cannot contain that one too, since then would be a cycle in .
Let be the set of arborescences of that contain all arcs of but one. Let be the graph of line L5, on , with the scores
for , where a maximum is over the for which the arc exists. Note . Every node of other than has an entering arc in : a node keeps its entering arcs, with those from merged into one arc from , and has an entering arc because some arc enters from outside (otherwise no node of could reach in , and would have no arborescence; in the complete graph of the parser the root arcs always exist).
Lemma 3 (contraction). (a) Every maps to an arborescence of with . (b) Every arborescence of is mapped by lines L7 and L8 to some with .
Proof. (a) Let omit the arc of into , and let . Then : otherwise every node of would have its head in , and the chains from the nodes of would never leave and never reach . Replace the nodes of by : the arc becomes , each arc with , becomes , and the arcs inside disappear. Every node of other than gets one head, and chains to in map to chains in , so is an arborescence. Its score is at least of the other arcs, because each is a maximum over the choices that include the one made; and is exactly plus the same other arcs. (b) Let be an arborescence of and let be its arc into . Line L7 replaces it by for the that gave the maximum , replaces each by for the that gave the maximum , and keeps the other arcs. Line L8 gives every its head . Every node of other than now has one head. Every node reaches : a node outside follows its chain in , reading as a passage through , which works because each node of reaches along the cycle and goes to . So is an arborescence in , and its score is plus the other arcs, which equals by the choice of the maximizers.
Theorem 4. returns a maximum arborescence of .
Proof. By induction on . If line L2 finds no cycle, Lemma 1 applies. Otherwise because , so by induction line L6 returns a maximum arborescence of . By Lemma 3(b) the returned is an arborescence with . Let be a maximum arborescence of in , which exists by Lemma 2. By Lemma 3(a) it maps to an arborescence of of score at least , so . Hence is maximum.
Termination. Each call either returns at line L3 or makes one recursive call on a graph with fewer nodes, and every line does finite work. So there are at most nested calls.
Corollary 5 (the parser). With , and on all arcs , , , CLE returns a highest scoring dependency tree. In the single-root version, run keeps only the root arc ; its arborescences are exactly the dependency trees whose only root child is , every node still has an entering arc, and Theorem 4 gives the best of them. Every single-root tree is counted in exactly one run, so the best of the results is a best single-root tree.
Complexity
Time. Lines L1 to L5 and L7 to L8 touch each arc once, which is for a dense graph. Each contraction removes at least one node, since a cycle has at least two nodes, so there are at most levels of recursion, on graphs of nodes. The total is in the worst case, for example when every level finds a cycle of two nodes. The best case is : reading the score matrix already costs that, and if the best heads form a tree, the algorithm stops after one level. Tarjan (1977) organizes the contractions so that the whole run takes for dense graphs, which matches the input size. The single-root version by runs multiplies the time by .
Space. The score matrix of each level is a new graph, and the recursion keeps all levels until it returns, so the simple form uses extra space in the worst case. Overwriting the scores in place and storing only the cycle of each level, as Tarjan's form does, brings it down to .
Properties
- Exact over all trees. It returns a tree of largest score among all trees, projective or not; the tests compare it with a search over all trees for small .
- Deterministic. Ties in line L1 are broken by the first head in the order of the nodes.
- Arc-factored only. The proof needs the score of a tree to be the sum of independent arc scores. With second-order scores, non-projective parsing is NP-hard (McDonald and Pereira 2006; McDonald and Satta 2007).
- Recursive. Each contraction calls the algorithm on a smaller graph.
- Not online. The best head of each word depends on words to its right.
- Sums are a determinant. The sum over all trees of the product of arc weights is the determinant of a Laplacian minor, by the matrix-tree theorem, and its derivatives give the arc marginals. The code computes both exactly with fractions, with and without the single-root rule, and the tests check them against a sum over all trees.
Variants and improvements
- Tarjan's implementation. for dense graphs, and for arcs; the version of Gabow, Galil, Spencer and Tarjan takes .
- The root constraint in one run. Faster methods than separate runs exist for the single-root version; Zmigrod, Vieira and Cotterell (2020) give an method for dependency parsing.
- K best trees. Camerini, Fratta and Maffioli give an algorithm for the best arborescences, used for reranking.
- Training. McDonald et al. (2005) trained the arc scores with an online large-margin method, with CLE as the decoder in each update. The matrix-tree theorem gives the marginals needed for conditional training of a log-linear model over trees (Koo, Globerson, Carreras and Collins 2007), and the same holds for neural arc scorers such as the biaffine parser.
- Approximate second order. McDonald and Pereira (2006) take the best projective second-order tree from the Eisner chart and then change heads one at a time, as long as the score rises and the result stays a tree.
When to use it
Use MST parsing when the arc scores are arc-factored and the trees may have crossing arcs, as in languages with free word order or in treebanks with many non-projective arcs, and when an exact decoder is wanted. With a neural arc scorer it is the standard decoder. When the trees must be projective, use the Eisner algorithm. When the score must depend on pairs of arcs, exact non-projective search is NP-hard, and approximate search or a transition-based parser such as the swap system is the usual choice.
Pitfalls
- The root as a dependent. The root must have no entering arc. Leave out the column of the root, or give it the score minus infinity.
- Minimum or maximum. Edmonds' algorithm is often stated for the minimum arborescence. Negate the scores, or take maxima everywhere; rescoring by subtraction must then use the maximum form of line L5.
- Several root children. The unconstrained answer may attach several words to the root. If the treebank requires one, use the single-root version; removing the extra arcs afterwards gives a tree that is not the best single-root tree.
- Forgetting the map back. The arcs into and out of must remember which cycle node gave their maximum. Without this record, the expansion attaches the wrong word.
- Nested cycles. A contracted node can lie on a new cycle at the next level. The recursion handles this, but an implementation that contracts only once does not; the tests include such a graph.
- Ties in floating point. With nearly equal scores, the cycle found can change with rounding; the score of the result is still optimal up to rounding, but the tree may differ between runs on different machines.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mst-dependency-parsing/. The authors are listed in prov/Z4H7TB.jsonl.
"""Graph-based dependency parsing with the Chu-Liu-Edmonds algorithm.
The words are 1..n and 0 is the artificial root. scores[h][d] is the score of
the arc h -> d in an (n + 1) x (n + 1) matrix; column 0 and the diagonal are
not read. A tree is a head list heads with heads[0] = -1 and heads[d] the head
of word d. The score of a tree is the sum of its arc scores.
mst_parse() returns a maximum spanning arborescence rooted at 0, so the tree
can be non-projective. This plain recursive version takes O(n^3) time; Tarjan's
implementation takes O(n^2) on a dense graph. With single_root=True the root
gets exactly one child: the code solves one problem per possible root child.
partition_function() and arc_marginals() use the matrix-tree theorem with exact
Fractions, for weights w[h][d] > 0 (for example exp of the scores, or small
integers in the tests).
"""
from fractions import Fraction
from typing import Dict, List, Sequence, Tuple
Arc = Tuple[int, int]
def _check(m: Sequence[Sequence]) -> int:
n = len(m) - 1
if n < 0 or any(len(row) != n + 1 for row in m):
raise ValueError("the matrix must be (n + 1) x (n + 1)")
return n
def _find_cycle(head: Dict[int, int]):
"""Return the list of nodes of a cycle in the graph v -> head[v], or None."""
color: Dict[int, int] = {}
for start in head:
if start in color:
continue
path = []
v = start
while v in head and v not in color:
color[v] = 1
path.append(v)
v = head[v]
if v in color and color[v] == 1:
return path[path.index(v):]
for u in path:
color[u] = 2
return None
def chu_liu_edmonds(nodes: List[int], root: int, w: Dict[Arc, object]) -> Dict[int, int]:
"""Return a maximum spanning arborescence of the graph (nodes, w) rooted at root.
w maps an arc (h, d) to its score; every node other than root must have at
least one entering arc. The result maps each non-root node to its head.
"""
best: Dict[int, int] = {}
for d in nodes: # @line L1
if d == root:
continue
cands = [(h, d) for h in nodes if (h, d) in w]
if not cands:
raise ValueError(f"node {d} has no entering arc")
best[d] = max(cands, key=lambda a: w[a])[0]
cycle = _find_cycle(best) # @line L2
if cycle is None:
return best # @line L3
in_cycle = set(cycle)
c = max(nodes) + 1 # the new node that stands for the cycle # @line L4
cycle_score = sum(w[(best[v], v)] for v in cycle)
w2: Dict[Arc, object] = {}
enter: Dict[int, int] = {} # for an arc (u, c): the cycle node it enters
leave: Dict[int, int] = {} # for an arc (c, v): the cycle node it leaves
for (h, d), s in w.items(): # @line L5
if h in in_cycle and d in in_cycle:
continue
if d in in_cycle:
s2 = s - w[(best[d], d)] + cycle_score
if (h, c) not in w2 or s2 > w2[(h, c)]:
w2[(h, c)], enter[h] = s2, d
elif h in in_cycle:
if (c, d) not in w2 or s > w2[(c, d)]:
w2[(c, d)], leave[d] = s, h
else:
w2[(h, d)] = s
nodes2 = [v for v in nodes if v not in in_cycle] + [c]
sub = chu_liu_edmonds(nodes2, root, w2) # @line L6
heads: Dict[int, int] = {}
for d, h in sub.items(): # @line L7
if d == c:
heads[enter[h]] = h
elif h == c:
heads[d] = leave[d]
else:
heads[d] = h
for v in cycle: # @line L8
if v not in heads:
heads[v] = best[v]
return heads # @line L9
def mst_parse(scores: Sequence[Sequence], single_root: bool = False) -> Tuple[object, List[int]]:
"""Return (score, heads) of a highest scoring dependency tree, projective or not."""
n = _check(scores)
if n == 0:
return 0, [-1]
nodes = list(range(n + 1))
full = {(h, d): scores[h][d] for h in nodes for d in range(1, n + 1) if h != d}
if not single_root:
options = [full]
else:
options = []
for m in range(1, n + 1):
options.append({a: s for a, s in full.items() if a[0] != 0 or a[1] == m})
best_score, best_heads = None, None
for w in options:
sol = chu_liu_edmonds(nodes, 0, w)
heads = [-1] + [sol[d] for d in range(1, n + 1)]
s = tree_score(scores, heads)
if best_score is None or s > best_score:
best_score, best_heads = s, heads
return best_score, best_heads
def tree_score(scores: Sequence[Sequence], heads: Sequence[int]):
total = 0
for d in range(1, len(heads)):
total = total + scores[heads[d]][d]
return total
def is_tree(heads: Sequence[int]) -> bool:
"""Return True if every word reaches the root 0 by following heads, with no cycle."""
n = len(heads) - 1
if n < 0 or heads[0] != -1:
return False
for d in range(1, n + 1):
if not 0 <= heads[d] <= n or heads[d] == d:
return False
for d in range(1, n + 1):
x, steps = d, 0
while x != 0:
x, steps = heads[x], steps + 1
if steps > n:
return False
return True
# The matrix-tree theorem (Koo, Globerson, Carreras and Collins 2007).
def _det_and_inverse(a: List[List[Fraction]]):
"""Return (det a, inverse of a) by Gauss-Jordan elimination over Fractions."""
n = len(a)
m = [list(row) + [Fraction(int(i == j)) for j in range(n)] for i, row in enumerate(a)]
det = Fraction(1)
for col in range(n):
piv = next((r for r in range(col, n) if m[r][col] != 0), None)
if piv is None:
return Fraction(0), None
if piv != col:
m[col], m[piv] = m[piv], m[col]
det = -det
p = m[col][col]
det *= p
m[col] = [x / p for x in m[col]]
for r in range(n):
if r != col and m[r][col] != 0:
f = m[r][col]
m[r] = [x - f * y for x, y in zip(m[r], m[col])]
return det, [row[n:] for row in m]
def _laplacian(w: Sequence[Sequence], single_root: bool):
"""The n x n matrix of Koo et al.: rows and columns are the words 1..n.
Without single_root, L[d][d] = sum of w[h][d] over all heads h (root included)
and L[h][d] = -w[h][d]. With single_root, the root weights leave the
diagonal and the first row becomes w[0][d].
"""
n = len(w) - 1
L = [[Fraction(0)] * n for _ in range(n)]
for d in range(1, n + 1):
for h in range(0, n + 1):
if h == d:
continue
if h > 0:
L[h - 1][d - 1] -= Fraction(w[h][d])
if h > 0 or not single_root:
L[d - 1][d - 1] += Fraction(w[h][d])
if single_root:
L[0] = [Fraction(w[0][d]) for d in range(1, n + 1)]
return L
def partition_function(w: Sequence[Sequence], single_root: bool = False) -> Fraction:
"""Return Z = sum over all trees of the product of w[h][d] over their arcs."""
n = _check(w)
if n == 0:
return Fraction(1)
det, _ = _det_and_inverse(_laplacian(w, single_root))
return det
def arc_marginals(w: Sequence[Sequence], single_root: bool = False) -> List[List[Fraction]]:
"""Return mu[h][d], the total weight of the trees that contain h -> d, divided by Z.
mu[h][d] = w[h][d] times the derivative of log Z with respect to w[h][d], and
d log det L / d L[a][b] = (L^-1)[b][a].
"""
n = _check(w)
L = _laplacian(w, single_root)
det, inv = _det_and_inverse(L)
if det == 0:
raise ValueError("the total weight of the trees is 0")
mu = [[Fraction(0)] * (n + 1) for _ in range(n + 1)]
for d in range(1, n + 1):
for h in range(0, n + 1):
if h == d:
continue
# (row, column, coefficient) of each entry of L that contains w[h][d]
entries = []
if single_root:
if h == 0:
entries.append((0, d - 1, 1))
else:
if d - 1 != 0:
entries.append((d - 1, d - 1, 1))
if h - 1 != 0:
entries.append((h - 1, d - 1, -1))
else:
entries.append((d - 1, d - 1, 1))
if h > 0:
entries.append((h - 1, d - 1, -1))
g = sum(c * inv[b][a] for a, b, c in entries)
mu[h][d] = Fraction(w[h][d]) * g
return mu
test_mst_dependency_parsing.py 133 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mst-dependency-parsing/. The authors are listed in prov/Z4H7TB.jsonl.
import itertools
import random
from fractions import Fraction as F
import pytest
from mst_dependency_parsing import (
arc_marginals,
chu_liu_edmonds,
is_tree,
mst_parse,
partition_function,
tree_score,
)
JOHN_SAW_MARY = [
[0, 9, 10, 9],
[0, 0, 20, 3],
[0, 30, 0, 30],
[0, 11, 0, 0],
]
def all_trees(n):
out = []
for hs in itertools.product(range(n + 1), repeat=n):
heads = [-1] + list(hs)
if is_tree(heads):
out.append(heads)
return out
TREES = {n: all_trees(n) for n in range(1, 6)}
def root_children(heads):
return sum(1 for h in heads[1:] if h == 0)
def product_weight(w, heads):
p = F(1)
for d in range(1, len(heads)):
p *= w[heads[d]][d]
return p
def test_tree_counts_by_enumeration_and_matrix_tree():
assert [len(TREES[n]) for n in range(1, 6)] == [1, 3, 16, 125, 1296]
for n in range(1, 8):
ones = [[1] * (n + 1) for _ in range(n + 1)]
assert partition_function(ones) == (n + 1) ** (n - 1)
assert partition_function(ones, single_root=True) == n ** (n - 1)
def test_example_john_saw_mary():
score, heads = mst_parse(JOHN_SAW_MARY)
assert (score, heads) == (70, [-1, 2, 0, 2])
# The greedy choice of the best head per word has the cycle John <-> saw.
best_in = {d: max(range(4), key=lambda h: JOHN_SAW_MARY[h][d] if h != d else -1) for d in (1, 2, 3)}
assert best_in == {1: 2, 2: 1, 3: 2}
@pytest.mark.parametrize("single_root", [False, True])
def test_against_brute_force(single_root):
rng = random.Random(5)
for n in range(1, 6):
pool = [t for t in TREES[n] if not single_root or root_children(t) == 1]
for _ in range(25 if n < 5 else 8):
s = [[rng.randint(-10, 10) for _ in range(n + 1)] for _ in range(n + 1)]
best = max(tree_score(s, t) for t in pool)
score, heads = mst_parse(s, single_root=single_root)
assert score == best
assert is_tree(heads) and tree_score(s, heads) == score
if single_root:
assert root_children(heads) == 1
def test_finds_non_projective_tree():
n = 4
s = [[0] * (n + 1) for _ in range(n + 1)]
s[0][2] = s[2][4] = s[4][1] = s[2][3] = 10
assert mst_parse(s) == (40, [-1, 4, 0, 2, 2])
def test_general_graph_with_nested_cycles():
# Two cycles; after the first contraction a second cycle appears.
w = {(0, 1): 1, (1, 2): 10, (2, 1): 10, (2, 3): 9, (3, 4): 10, (4, 3): 10, (4, 1): 9, (0, 3): 2}
heads = chu_liu_edmonds([0, 1, 2, 3, 4], 0, w)
total = sum(w[(h, d)] for d, h in heads.items())
best = None
for hs in itertools.product(range(5), repeat=4):
cand = [-1] + list(hs)
if is_tree(cand) and all((cand[d], d) in w for d in range(1, 5)):
t = sum(w[(cand[d], d)] for d in range(1, 5))
best = t if best is None else max(best, t)
assert total == best
def test_ties_and_negative_scores():
rng = random.Random(9)
for _ in range(40):
n = rng.randint(1, 5)
s = [[rng.choice([-3, -1, 0, 0, 2]) for _ in range(n + 1)] for _ in range(n + 1)]
score, heads = mst_parse(s)
assert score == max(tree_score(s, t) for t in TREES[n])
@pytest.mark.parametrize("single_root", [False, True])
def test_partition_and_marginals_against_brute_force(single_root):
rng = random.Random(13)
for n in range(1, 5):
w = [[F(rng.randint(1, 6), rng.randint(1, 3)) for _ in range(n + 1)] for _ in range(n + 1)]
pool = [t for t in TREES[n] if not single_root or root_children(t) == 1]
z = sum(product_weight(w, t) for t in pool)
assert partition_function(w, single_root=single_root) == z
mu = arc_marginals(w, single_root=single_root)
for d in range(1, n + 1):
for h in range(n + 1):
if h == d:
continue
exact = sum(product_weight(w, t) for t in pool if t[d] == h) / z
assert mu[h][d] == exact
assert sum(mu[h][d] for h in range(n + 1) if h != d) == 1
def test_small_inputs():
assert mst_parse([[0]]) == (0, [-1])
assert mst_parse([[0, 4], [0, 0]]) == (4, [-1, 0])
with pytest.raises(ValueError):
mst_parse([[0, 1]])
History
Chu and Liu (1965) and Edmonds (1967) found the optimum branching algorithm independently, and Tarjan (1977) gave fast implementations. In parsing, Eisner's (1996) cubic chart had made projective arc-factored parsing exact, and transition-based parsers handled non-projective trees with pseudo-projective transformations. McDonald, Pereira, Ribarov and Hajič (2005) observed that dropping projectivity turns the arc-factored problem into a maximum spanning arborescence, which can be solved in , and showed good results on Czech. McDonald and Pereira (2006) and McDonald and Satta (2007) then showed that non-projective parsing becomes NP-hard as soon as the scores look at pairs of arcs. In 2007 several groups, among them Koo, Globerson, Carreras and Collins, used the matrix-tree theorem for the partition function. With neural arc scores, as in the biaffine parser of Dozat and Manning (2017), the arborescence decoder remains in common use.
References
- Ryan McDonald, Fernando Pereira, Kiril Ribarov and Jan Hajič, Non-projective dependency parsing using spanning tree algorithms, HLT-EMNLP 2005, the reduction to the maximum spanning arborescence, the Chu-Liu-Edmonds algorithm in the maximum form, and online large-margin training
- Sandra Kübler, Ryan McDonald and Joakim Nivre, Dependency Parsing, Synthesis Lectures on Human Language Technologies, Morgan and Claypool, 2009, Chapter 4, Graph-Based Parsing (arc-factored models and the maximum spanning tree algorithm)
- Jack Edmonds, Optimum branchings, Journal of Research of the National Bureau of Standards 71B(4) (1967), 233-240, the contraction of cycles of best entering arcs
- Y. J. Chu and T. H. Liu, On the shortest arborescence of a directed graph, Scientia Sinica 14 (1965), 1396-1400, the same algorithm, found independently
- Robert E. Tarjan, Finding optimum branchings, Networks 7(1) (1977), 25-35, the O(n^2) implementation for dense graphs
- Terry Koo, Amir Globerson, Xavier Carreras and Michael Collins, Structured prediction models via the matrix-tree theorem, EMNLP-CoNLL 2007, the partition function and the arc marginals of non-projective trees, with and without one child of the root
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag Z4H7TB Edit this page History Report an error Markdown