Algorithmcore
Head rules
Also called head percolation table, Magerman-Collins head rules.
A table that picks the head child of each phrase type, used to lexicalize trees and to convert constituency trees to dependencies.
- Time
- O(s l) worstΘ(s) best
- Space
- Θ(s) extra
- Where
- l = the length of the longest priority list of the table; n = the number of words; s = the number of nodes of the tree
- Model
- Word RAM
- Properties
- deterministicofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David M. Magerman, Michael Collins, 1995
Head rules pick, for each phrase in a parse tree, the one child that is its head: the verb phrase in a sentence, the noun in a noun phrase, the preposition in a prepositional phrase. The rules are a table indexed by the parent label. Each entry gives a scan direction and a priority list of child labels. Once every phrase has a head child, each phrase gets a head word passed up from below. This is what a lexicalized PCFG needs, and it also turns a constituency tree into a dependency tree: the head word of each non-head child depends on the head word of the phrase. Magerman used such a table in 1995 and Collins published the version that most later work copies in his 1999 thesis. The conversion is linear in the size of the tree. The table itself is a heuristic: it encodes linguistic choices, and other tables give other heads.
In plain words
A phrase such as "the big dog" is about one word, "dog", its head. If we know the head of every phrase, we know which word each other word attaches to: "the" and "big" attach to "dog", and "dog" attaches to whatever word heads the phrase above it.
The head rules find the head with a short recipe for each kind of phrase. For a prepositional phrase, look from the right for a preposition. For a verb phrase, look from the left for a verb, then a modal, then another verb phrase, and so on down a list. If nothing in the list is found, take the first child on the side where the search starts. Noun phrases have their own recipe, which looks for the last noun.
Applied from the bottom of the tree to the top, this gives every word one head word: a dependency tree.
The problem
The input is a constituency tree over the words , such as a tree of the Penn treebank: internal nodes carry phrase labels (S, NP, VP, PP, ...), preterminals carry part-of-speech tags, and the leaves are the words. The output has two parts.
- For each internal node with children , an index , the head child. The head word is the word of itself if is a preterminal, and otherwise.
- The dependency tree : for every word , its head , with 0 the artificial root. At each node and each child with , the word gets the head . The head word of the whole tree gets the head 0, so the root has exactly one child.
There is no single correct answer to part 1. A head table is a convention, and the problem is to apply a given table exactly. The rest of this page uses the table of Collins (1999), with the labels of the Penn Treebank. Function tags and indices are removed before lookup, so NP-SBJ-1 is looked up as NP.
The algorithm
A table entry is a pair (dir, list). "Left" means the children are scanned from the left, "right" from the right. The outer loop goes through the list in priority order and the inner loop through the children, so a label early in the list beats a label that is closer to the start. Part of the Collins table:
| parent | dir | priority list |
|---|---|---|
| S | left | TO IN VP S SBAR ADJP UCP NP |
| VP | left | TO VBD VBN MD VBZ VB VBG VBP VP ADJP NN NNS NP |
| PP | right | IN TO VBG VBN RP FW |
| SBAR | left | WHNP WHPP WHADVP WHADJP IN DT S SQ SINV SBAR FRAG |
| ADJP | left | NNS QP NN $ ADVP JJ VBN VBG ADJP JJR NP JJS DT FW RBR RBS SBAR RB |
| ADVP | right | RB RBR RBS FW ADVP TO CD JJR JJ IN NP JJS NN |
| PRN | left | (empty) |
| FRAG | right | (empty) |
The implementation holds the full table, with 24 entries and the NP rule. NP has its own rule, NP-HEAD, which goes by position within a set of labels: the first child from the right that is a noun tag, not the noun with the highest priority.
HEAD-CHILD(X, Y1 … Ym) ▷ X: parent label; Y1 … Ym: child labels- 1
if m = 1 then return 1 - 2
if X = NP then return NP-HEAD(Y1 … Ym) - 3
(dir, list) ← table[X], or (left, empty list) if X has no entry - 4
order ← 1, 2, …, m if dir = left, else m, m-1, …, 1 - 5
for each label Z in list, in priority order do - 6
for each k in order do - 7
if Yk = Z then return k - 8
return the first index of order DEPENDENCIES(t) ▷ t: a tree over the words w1 … wn- 9
for each node v of t, children before parents do - 10
if v is a preterminal over word i then head(v) ← i - 11
else c ← HEAD-CHILD(label of v, labels of its children u1 … um); head(v) ← head(uc) - 12
for each k ≠ c do h(head(uk)) ← head(v) - 13
h(head(root)) ← 0 - 14
return h NP-HEAD(Y1 … Ym)- 15
if Ym = POS then return m - 16
for each step (dir, set) in the list below, in order do - 17
for each k in the order of dir do - 18
if Yk ∈ set then return k - 19
return m
The steps of line L16 are: from the right, any of NN NNP NNPS NNS NX POS JJR; from the left, NP; from the right, any of $ ADJP PRN; from the right, CD; from the right, any of JJ JJS RB QP. Line L15 makes the possessive marker the head of a possessive NP such as "John 's", so that the whole phrase can attach to the noun it modifies. Line L8 is the fallback when no child label is in the list; for the entries with an empty list, such as PRN and FRAG, it is the only rule. Lines L9 to L12 visit the tree children first, so the head words of the children are known when line L11 needs them. The implementation keeps them on a stack instead of using recursion, because treebank trees can be deep.
Example
Take the tree
with the words numbered 1 to 9: The, company, will, sell, its, assets, to, investors, ".". The preterminals are DT NN, MD, VB, PRP$ NNS, TO, NNS and the period. The walk finishes the phrases in this order.
| step | node | child labels | rule that fires | head child | head word | arcs written |
|---|---|---|---|---|---|---|
| 1 | NP-SBJ | DT NN | NP-HEAD, first step | NN | company | The → company |
| 2 | NP | PRP$ NNS | NP-HEAD, first step | NNS | assets | its → assets |
| 3 | NP | NNS | line L1 | NNS | investors | none |
| 4 | PP | TO NP | PP, right: no IN, then TO | TO | to | investors → to |
| 5 | VP | VB NP PP | VP, left: VB is the first label of the list present | VB | sell | assets → sell, to → sell |
| 6 | VP | MD VP | VP, left: MD comes before VP in the list | MD | will | sell → will |
| 7 | S | NP-SBJ VP . | S, left: no TO or IN, then VP | VP | will | company → will, . → will |
Line L13 gives "will" the head 0. The result, with for , is . Step 6 shows a choice of the table: Collins makes the modal the head of the verb group, so the main verb "sell" depends on "will". Universal Dependencies makes the opposite choice. The tests check this tree and the sentence of Figure 1 of Klein and Manning (2004), "Factory payrolls fell in September", whose result matches the dependencies in that figure.
Correctness
Whatever the table says, the output is a dependency tree in the sense of the area: every word has exactly one head, the root 0 has exactly one child, there is no cycle, and the tree is projective. Each constituent is a connected piece of it: exactly one word of its span, the head word, has its head outside the span.
The key invariant is about a finished node : every word of its span except has its final head inside the span and reaches by following heads. A new node keeps the invariant because line L12 attaches the head words of the other children to the head word of the head child, and no later step touches a word of the span except . Projectivity follows because an arc written at joins two words of the span of , every word between them is in that span, and every word of the span is below . The full proof is in the correctness proof.
This is a theorem about the shape of the output. That the heads are linguistically right is a different claim, and it is only a heuristic.
Proof: Head rules turn every constituency tree into a projective dependency tree in which each constituent is a connected piece headed by its head wordfull
We use the pseudocode HEAD-CHILD and DEPENDENCIES of the page. The input is a finite ordered tree whose leaves are the words , left to right, with . Each internal node has at least one child. The head table can be any table: the proof uses only that HEAD-CHILD returns one index between 1 and the number of children. That is the part we prove. Whether the chosen heads are good linguistic heads is a separate question, and the table is a heuristic for it.
For a node , is the set of the positions of the words below . For a word , is the value that DEPENDENCIES writes for , with 0 standing for the artificial root. A word is a descendant of a word when following from reaches after zero or more steps.
Lemma 1: HEAD-CHILD returns a valid index
For a node with children, HEAD-CHILD returns an index with .
Proof. Line L1 returns 1 when . Line L7 returns an index of the scan order of line L4, which lists in some order. Line L8 returns the first index of that order. The NP branch is the same: lines L15 to L19 return , an index found by a scan of , or .
Lemma 2: yields are intervals
For every node , is an interval of positions, and the yields of the children of , in order, are consecutive intervals that cover it.
Proof. The words are numbered in the left-to-right order of the leaves, and the leaves below a node are a contiguous run of that order, since the tree is ordered.
Lemma 3: the invariant of the walk
DEPENDENCIES visits the nodes children first. When it has finished a node , it has set , and:
- every word with has an arc, and ;
- following from any word of reaches after at most steps;
- no arc is written for yet, and no arc written later changes for a word other than .
Proof. By induction on the height of . A preterminal over word gets at line L10 and writes no arc, so parts 1 and 2 hold. For part 3, see the last paragraph.
Let have the children , which are finished before because the walk is children first. Line L11 picks , a valid index by Lemma 1, and sets . Line L12 writes for each . These words lie in disjoint yields by Lemma 2, so each gets one arc here.
Part 1: a word of other than has by part 1 for . The word with now has .
Part 2: from a word of , part 2 for reaches in at most steps, and one more step reaches if . The total is at most when , since has at least one word outside .
Part 3: line L12 at a node writes arcs only for the head words of the children of . If is a proper ancestor of , the only word of that is the head word of a child of is , because the head word of a node is passed up only from its head child. If is not an ancestor of and not below it, its yield is disjoint from . So after is finished, the only word of that can still get an arc is .
Theorem
The list returned by DEPENDENCIES is a dependency tree on the words with the root 0: exactly one word has , every other word has a head among the words, and following from any word reaches 0. The tree is projective. For every node of , exactly one word of , namely , has its head outside or at 0, and every other word of reaches through words of .
Proof. Apply Lemma 3 to the root , whose yield is all of . Every word except has a head among the words (part 1), and line L13 sets . By part 2 every word reaches , and then 0, so there is no cycle.
Constituents: fix a node . By part 3 the arcs of the words of other than are final when is finished. By part 1 their heads lie in , and by part 2 they reach inside . The word gets its head later at an ancestor, outside because the yields of the other children are disjoint from it, or 0 at line L13.
Projectivity: take an arc with , written at line L12 while processing a node . Then , and both and are in , which is an interval by Lemma 2. So every word strictly between them is in , and by part 2 for it reaches . Every word between and is thus a descendant of , which is the definition of a projective arc.
The subtree of in the final tree can be larger than : when is the head child of its parent, the heads of its siblings attach to too.
Termination and cost
Each node is pushed once unfinished and once finished, so the walk of line L9 runs times for a tree of nodes. HEAD-CHILD on a node with children scans at most children once for each of the at most labels of the priority list, so its cost is , and the sum of over all nodes is . The total time is , which is linear for a fixed table.
Complexity
Time. For a node with children, HEAD-CHILD runs the loop of lines L5 to L7 at most times, where is the length of the longest priority list. The sum of over all nodes is for a tree of nodes, so the time is on the word RAM. With a fixed table, is a constant and the time is . If the first label of each list matches at once, every node costs after its children, which gives the best case .
Space. The explicit stack of the walk and the stack of head words hold entries, and the output has entries.
Properties
- Deterministic and total. Every node gets exactly one head child, because line L8 always has an answer.
- The output is projective. No conversion by head rules can produce crossing arcs. Non-projective structure in a treebank lives in its traces and empty elements, which head rules ignore.
- One root child. The root gets exactly one dependent, the head word of the top node.
- Local. The head of a node depends only on its own label and the labels of its children, not on the words.
- The list order beats the child order. The outer loop runs over the list, so a VP with the children NN VBD picks VBD, the second child, because VBD comes before NN in the list.
Variants and improvements
- Coordination. Collins also moves the head in a coordinated phrase: when the child just before the chosen head is CC, the head moves to the conjunct before it. The CoreNLP implementation does this in a separate step. The code on this page leaves it out.
- Other tables. Some later converters choose content words as heads, so the main verb heads a verb group and the noun heads a prepositional phrase. Universal Dependencies follows this choice. The algorithm stays the same; only the table changes, and the code takes the table as an argument.
- Lexicalization. In a lexicalized PCFG, each nonterminal carries its head word and tag. The head rules decide which child passes its head up, and the model generates the other children as dependents of that head.
When to use it
Use a head table when a treebank has only phrase-structure trees and you need head words: to train a lexicalized parser, to make gold dependencies for dependency parsing or an attachment score, or to evaluate an unsupervised model such as the dependency model with valence. Use the same table for training and evaluation, and name it. If the treebank already has dependency annotation, use that instead.
Pitfalls
- Priority order and position order mixed up. Lines L5 and L6 loop over the list first and the children second. Swapping them makes line L7 return the first child in the scan whose label is anywhere in the list. For a VP with the children NN VBD, the swapped loops return NN, while the right answer is VBD, which comes earlier in the list.
- Function tags not stripped. The Penn Treebank writes NP-SBJ, PP-LOC or NP-1. Looking these up without removing the suffix makes line L3 miss the entry and fall back to the leftmost child.
- Empty elements and traces. Remove -NONE- preterminals and their empty parents before line L9, or they become words of the dependency tree.
- Different tables give different scores. Klein and Manning (2004) report that making determiners the heads of noun phrases changes the directed accuracy of their model on WSJ10 from 43.2% to 55.7%. This is a measurement. An attachment score is only comparable with the same head table.
- Deep trees. A recursive walk can hit Python's recursion limit on long right-branching phrases. Line L9 needs an explicit stack.
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/head-rules/. The authors are listed in prov/EXAQEX.jsonl.
"""Head rules: pick the head child of each phrase and turn a tree into dependencies.
A tree is (label, children). A preterminal is (tag, word) with word a string.
An internal node is (label, list of trees). The table is the head table of
Collins (1999, appendix A) in the form used by the Stanford CollinsHeadFinder,
without its extra AUX and NX entries for the parent. Function tags such as the
"-SBJ" in "NP-SBJ" are removed before a label is looked up.
The words are numbered 1 to n from the left. to_dependencies returns the list
h with h[i] the head of word i, h[0] unused, and 0 for the word that heads the
whole sentence.
"""
from typing import Dict, List, Sequence, Tuple, Union
Tree = Tuple[str, Union[str, list]]
LEFT, RIGHT = "left", "right"
# label -> (direction, priority list). "left" scans the children from the left,
# "right" from the right, once for each label of the list in order.
COLLINS: Dict[str, Tuple[str, Tuple[str, ...]]] = {
"ADJP": (LEFT, ("NNS", "QP", "NN", "$", "ADVP", "JJ", "VBN", "VBG", "ADJP", "JJR",
"NP", "JJS", "DT", "FW", "RBR", "RBS", "SBAR", "RB")),
"ADVP": (RIGHT, ("RB", "RBR", "RBS", "FW", "ADVP", "TO", "CD", "JJR", "JJ", "IN",
"NP", "JJS", "NN")),
"CONJP": (RIGHT, ("CC", "RB", "IN")),
"FRAG": (RIGHT, ()),
"INTJ": (LEFT, ()),
"LST": (RIGHT, ("LS", ":")),
"NAC": (LEFT, ("NN", "NNS", "NNP", "NNPS", "NP", "NAC", "EX", "$", "CD", "QP",
"PRP", "VBG", "JJ", "JJS", "JJR", "ADJP", "FW")),
"PP": (RIGHT, ("IN", "TO", "VBG", "VBN", "RP", "FW")),
"PRN": (LEFT, ()),
"PRT": (RIGHT, ("RP",)),
"QP": (LEFT, ("$", "IN", "NNS", "NN", "JJ", "RB", "DT", "CD", "NCD", "QP", "JJR",
"JJS")),
"RRC": (RIGHT, ("VP", "NP", "ADVP", "ADJP", "PP")),
"S": (LEFT, ("TO", "IN", "VP", "S", "SBAR", "ADJP", "UCP", "NP")),
"SBAR": (LEFT, ("WHNP", "WHPP", "WHADVP", "WHADJP", "IN", "DT", "S", "SQ", "SINV",
"SBAR", "FRAG")),
"SBARQ": (LEFT, ("SQ", "S", "SINV", "SBARQ", "FRAG")),
"SINV": (LEFT, ("VBZ", "VBD", "VBP", "VB", "MD", "VP", "S", "SINV", "ADJP", "NP")),
"SQ": (LEFT, ("VBZ", "VBD", "VBP", "VB", "MD", "VP", "SQ")),
"UCP": (RIGHT, ()),
"VP": (LEFT, ("TO", "VBD", "VBN", "MD", "VBZ", "VB", "VBG", "VBP", "VP", "ADJP",
"NN", "NNS", "NP")),
"WHADJP": (LEFT, ("CC", "WRB", "JJ", "ADJP")),
"WHADVP": (RIGHT, ("CC", "WRB")),
"WHNP": (LEFT, ("WDT", "WP", "WP$", "WHADJP", "WHPP", "WHNP")),
"WHPP": (RIGHT, ("IN", "TO", "FW")),
"X": (RIGHT, ()),
}
# The NP rule of Collins: a list of (direction, label set) steps. Within one step
# the scan goes by position and stops at the first child whose label is in the set.
NP_STEPS = (
(RIGHT, frozenset(("NN", "NNP", "NNPS", "NNS", "NX", "POS", "JJR"))),
(LEFT, frozenset(("NP",))),
(RIGHT, frozenset(("$", "ADJP", "PRN"))),
(RIGHT, frozenset(("CD",))),
(RIGHT, frozenset(("JJ", "JJS", "RB", "QP"))),
)
def base_label(label: str) -> str:
"""Return the label without function tags and indices: NP-SBJ-1 gives NP."""
if label.startswith("-"):
return label # -NONE-, -LRB-, -RRB-
for sep in "-=":
k = label.find(sep)
if k > 0:
label = label[:k]
return label
def _order(direction: str, m: int) -> range:
return range(m) if direction == LEFT else range(m - 1, -1, -1)
def np_head(labels: Sequence[str]) -> int:
"""Return the 0-based index of the head child of an NP with these child labels."""
m = len(labels)
if labels[m - 1] == "POS": # @line L15
return m - 1
for direction, wanted in NP_STEPS: # @line L16
for k in _order(direction, m): # @line L17
if labels[k] in wanted: # @line L18
return k
return m - 1 # @line L19
def head_child(label: str, child_labels: Sequence[str], table=None) -> int:
"""Return the 0-based index of the head child of a node.
label is the parent label and child_labels the labels of its children, in
order. An unknown parent label scans from the left with an empty list, so
its head is the leftmost child.
"""
if table is None:
table = COLLINS
labels = [base_label(x) for x in child_labels]
m = len(labels)
if m == 0:
raise ValueError("a node without children has no head child")
if m == 1: # @line L1
return 0
x = base_label(label)
if x == "NP" and table is COLLINS: # @line L2
return np_head(labels)
direction, priority = table.get(x, (LEFT, ())) # @line L3
order = _order(direction, m) # @line L4
for z in priority: # @line L5
for k in order: # @line L6
if labels[k] == z: # @line L7
return k
return order[0] # @line L8
def is_preterminal(t: Tree) -> bool:
return isinstance(t[1], str)
def words(t: Tree) -> List[str]:
"""Return the words of t, left to right."""
out: List[str] = []
stack = [t]
while stack:
u = stack.pop()
if is_preterminal(u):
out.append(u[1])
else:
stack.extend(reversed(u[1]))
return out
def to_dependencies(t: Tree, table=None) -> List[int]:
"""Return h with h[i] the head word of word i (1-based) and 0 for the root word.
Each node passes up the head word of its head child. Every other child
attaches its head word to that word. The walk is iterative, children first.
"""
n = len(words(t))
h = [0] * (n + 1)
heads: List[int] = [] # lexical heads of the finished subtrees, left to right
position = 0
stack: List[Tuple[Tree, bool]] = [(t, False)]
while stack: # @line L9
u, done = stack.pop()
if is_preterminal(u):
position += 1
heads.append(position) # @line L10
continue
kids = u[1]
if not kids:
raise ValueError("an internal node has no children")
if not done:
stack.append((u, True))
for c in reversed(kids):
stack.append((c, False))
continue
m = len(kids)
child_heads = heads[len(heads) - m:]
del heads[len(heads) - m:]
c = head_child(u[0], [k[0] for k in kids], table) # @line L11
for k in range(m): # @line L12
if k != c:
h[child_heads[k]] = child_heads[c]
heads.append(child_heads[c])
h[heads[0]] = 0 # @line L13
return h # @line L14
def read_tree(s: str) -> Tree:
"""Read a tree in Penn Treebank bracket form, such as (S (NP (NN dogs)) (VP (VBP bark)))."""
tokens = s.replace("(", " ( ").replace(")", " ) ").split()
pos = 0
def parse() -> Tree:
nonlocal pos
if tokens[pos] != "(":
raise ValueError("expected (")
pos += 1
label = tokens[pos]
pos += 1
if tokens[pos] not in ("(", ")"):
word = tokens[pos]
pos += 1
if tokens[pos] != ")":
raise ValueError("expected ) after a word")
pos += 1
return (label, word)
kids = []
while tokens[pos] == "(":
kids.append(parse())
if tokens[pos] != ")":
raise ValueError("expected )")
pos += 1
return (label, kids)
tree = parse()
if pos != len(tokens):
raise ValueError("text after the tree")
return tree
test_head_rules.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/head-rules/. The authors are listed in prov/EXAQEX.jsonl.
import random
from head_rules import (COLLINS, base_label, head_child, np_head, read_tree,
to_dependencies, words)
def deps(s):
return to_dependencies(read_tree(s))
def test_klein_manning_figure() -> None:
# Klein and Manning (2004), Figure 1: Factory payrolls fell in September.
s = "(S (NP (NN Factory) (NNS payrolls)) (VP (VBD fell) (PP (IN in) (NP (NN September)))))"
assert deps(s) == [0, 2, 3, 0, 3, 4]
def test_page_example() -> None:
s = ("(S (NP-SBJ (DT The) (NN company)) (VP (MD will) (VP (VB sell) "
"(NP (PRP$ its) (NNS assets)) (PP (TO to) (NP (NNS investors))))) (. .))")
t = read_tree(s)
assert words(t) == ["The", "company", "will", "sell", "its", "assets", "to", "investors", "."]
assert to_dependencies(t) == [0, 2, 3, 0, 3, 6, 4, 4, 7, 3]
def test_np_rule() -> None:
assert np_head(["DT", "JJ", "NN"]) == 2
assert np_head(["NP", "PP"]) == 0
assert np_head(["NNP", "POS"]) == 1
assert np_head(["NP", "NN"]) == 1
assert np_head(["CD", "NNS"]) == 1
assert np_head(["DT", "CD"]) == 1
assert np_head(["DT", "JJ"]) == 1
assert np_head(["DT", "DT"]) == 1
assert np_head(["NN", "NN", "PP"]) == 1
assert np_head(["NP", ",", "NP", ","]) == 0
# possessive: John 's dog. The inner NP is headed by 's, the outer by dog.
assert deps("(NP (NP (NNP John) (POS 's)) (NN dog))") == [0, 2, 3, 0]
def test_table_rules() -> None:
assert head_child("PP", ["IN", "NP"]) == 0
assert head_child("PP", ["TO", "NP"]) == 0
assert head_child("PP", ["NP", "IN"]) == 1
assert head_child("SBAR", ["IN", "S"]) == 0
assert head_child("SBAR", ["WHNP", "S"]) == 0
assert head_child("VP", ["MD", "VP"]) == 0
assert head_child("VP", ["VB", "NP", "PP"]) == 0
assert head_child("VP", ["ADVP", "VBD", "NP"]) == 1
assert head_child("S", ["NP-SBJ", "VP", "."]) == 1
assert head_child("ADVP", ["RB", "RB"]) == 1 # right to left
assert head_child("ADJP", ["RB", "JJ"]) == 1
# priority beats position: S lists VP before NP
assert head_child("S", ["VP", "NP"]) == 0
assert head_child("VP", ["NN", "VBD"]) == 1
# no match: the first child in the scan direction
assert head_child("ADJP", [",", "CC"]) == 0
assert head_child("ADVP", [",", "CC"]) == 1
assert head_child("FRAG", ["NP", "PP", "."]) == 2
assert head_child("PRN", ["-LRB-", "NP", "-RRB-"]) == 0
# unknown label: leftmost
assert head_child("ZZZ", ["A", "B", "C"]) == 0
# single child
assert head_child("NP", ["PRP"]) == 0
def test_labels() -> None:
assert base_label("NP-SBJ-1") == "NP"
assert base_label("PP-LOC=2") == "PP"
assert base_label("-NONE-") == "-NONE-"
assert base_label("-LRB-") == "-LRB-"
assert head_child("PP-LOC", ["IN", "NP-1"]) == 0
def test_custom_table() -> None:
table = {"PP": ("left", ("NP",))}
assert head_child("PP", ["IN", "NP"], table) == 1
assert deps("(PP (IN in) (NP (NN May)))") == [0, 0, 1]
assert to_dependencies(read_tree("(PP (IN in) (NP (NN May)))"), table) == [0, 2, 0]
LABELS = sorted(COLLINS) + ["NP", "NP", "NX", "ZZ"]
TAGS = ["NN", "NNS", "NNP", "VB", "VBD", "MD", "IN", "TO", "DT", "JJ", "RB", "CD", "POS", ",", ".", "CC"]
def random_tree(rng, n):
"""A random tree with n words (preterminals) and random labels."""
nodes = [(rng.choice(TAGS), "w") for _ in range(n)]
while len(nodes) > 1:
a = rng.randrange(len(nodes))
b = rng.randrange(a + 1, min(len(nodes), a + 4) + 1)
kids = nodes[a:b]
nodes[a:b] = [(rng.choice(LABELS), kids)]
if rng.random() < 0.2:
nodes[a] = (rng.choice(LABELS), [nodes[a]]) # a unary node
if not isinstance(nodes[0][1], list):
nodes[0] = ("S", [nodes[0]])
return nodes[0]
def reference(t, start, h):
"""Recursive reference: return the head word of t, whose first word is start."""
if isinstance(t[1], str):
return start
heads = []
pos = start
for c in t[1]:
heads.append(reference(c, pos, h))
pos += len(words(c))
c = head_child(t[0], [k[0] for k in t[1]])
for k, x in enumerate(heads):
if k != c:
h[x] = heads[c]
return heads[c]
def spans(t, start, out):
"""Collect the (first word, last word) of every internal node."""
n = len(words(t))
if not isinstance(t[1], str):
out.append((start, start + n - 1))
pos = start
for c in t[1]:
spans(c, pos, out)
pos += len(words(c))
return out
def ancestors(h, i):
out = set()
while i != 0:
i = h[i]
if i in out or len(out) > len(h):
raise AssertionError("cycle")
out.add(i)
return out
def test_random_trees() -> None:
rng = random.Random(7)
for trial in range(600):
n = rng.randint(1, 12)
t = random_tree(rng, n)
h = to_dependencies(t)
assert len(h) == n + 1
ref = [0] * (n + 1)
root = reference(t, 1, ref)
ref[root] = 0
assert h == ref
# a tree: one root word and no cycle
assert sum(1 for i in range(1, n + 1) if h[i] == 0) == 1
anc = {i: ancestors(h, i) for i in range(1, n + 1)}
# projective: every word strictly between a head and its dependent is
# a descendant of the head
for d in range(1, n + 1):
if h[d] == 0:
continue
lo, hi = sorted((d, h[d]))
for x in range(lo + 1, hi):
assert h[d] in anc[x]
# every constituent is a subtree: exactly one word of its span has
# its head outside the span
for a, b in spans(t, 1, []):
outside = [i for i in range(a, b + 1) if not a <= h[i] <= b]
assert len(outside) == 1
def test_deep_tree() -> None:
# a right-branching tree 3000 levels deep: the walk is iterative
t = ("NN", "w")
for _ in range(3000):
t = ("NP", [("DT", "w"), t])
h = to_dependencies(t)
assert h[3001] == 0
assert all(h[i] == 3001 for i in range(1, 3001))
def test_read_tree_errors() -> None:
for bad in ["(S (NP", "(S (NN a b))", "(S (NN a)) x", "NN"]:
try:
read_tree(bad)
except (ValueError, IndexError):
continue
raise AssertionError(bad)
History
Head words entered statistical parsing in the early 1990s, when parsers began to condition rule choices on lexical items. Magerman (1995) passed head words up the trees of his decision-tree parser with a table of this kind. Collins revised the table for his parsers of the late 1990s and printed it in appendix A of his 1999 thesis, together with the special NP rule. That table, as implemented in tools such as the CollinsHeadFinder of Stanford CoreNLP, became the standard way to read dependencies off the Penn Treebank, and it was used to make the gold dependencies of many papers, for example the WSJ10 evaluation of Klein and Manning (2004).
References
- Michael Collins, Head-Driven Statistical Models for Natural Language Parsing, PhD thesis, Appendix A, the head table and the special rule for NP
- David M. Magerman, Statistical Decision-Tree Models for Parsing, ACL 1995, pp. 276 to 283
- Michael Collins, Head-Driven Statistical Models for Natural Language Parsing, Computational Linguistics 29(4), 2003, pp. 589 to 637, the head-driven models that use the head table
- Dan Klein and Christopher D. Manning, Corpus-Based Induction of Syntactic Structure, Models of Dependency and Constituency, ACL 2004, the evaluation section, gold dependencies read off the Penn Treebank with the Collins head rules, and the change of the NP head to the determiner
- Stanford CoreNLP, CollinsHeadFinder, an implementation of the head finder of the Collins thesis, the table nonTerminalInfo and the coordination fix in postOperationFix
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 EXAQEX Edit this page History Report an error Markdown