Algorithmcore
Hobbs algorithm
Also called Hobbs naive algorithm.
Resolve a pronoun by a fixed left-to-right, breadth-first walk of the parse trees of the current and earlier sentences, with agreement checks. A heuristic.
- Solves
- Coreference resolution
- Time
- O(n h) worst
- Space
- O(n) extra
- Where
- h = the height of the tree of the current sentence; n = the number of nodes in the parse trees
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jerry R. Hobbs, 1978
The Hobbs algorithm finds the antecedent of a third person pronoun by walking the parse trees of the text in a fixed order and taking the first noun phrase that agrees with the pronoun in gender, number and person. It uses no meaning and no world knowledge, only the shape of the trees, so Hobbs called it the naive algorithm. It is a heuristic: the order of the walk encodes preferences for subjects, for nearby sentences and against antecedents inside the pronoun's own clause, and nothing guarantees that the first match is right. It solves only part of coreference resolution: it handles pronouns and needs a parser, while the mention-pair model and the span-ranking model link all kinds of mentions. It remains a strong baseline for pronouns.
In plain words
Start at the pronoun in its sentence tree. Climb up the tree, and at each level look at what lies to the left, row by row and left to right, as the reader would have met it. Skip noun phrases that are too close to the pronoun in its own clause, because "John likes him" cannot mean that John likes John. If nothing fits in the sentence, go back one sentence at a time and read each tree row by row, left to right. The first noun phrase with the right gender and number wins. Because the walk goes row by row, a subject is found before an object, and a near sentence before a far one.
The problem
Input: the parse tree of the sentence that holds the pronoun, the parse trees of the earlier sentences, the NP node of the pronoun, and agreement features (gender, number, person) on the NP nodes. The trees follow Hobbs's grammar fragment, as given by Jurafsky and Martin: S → NP VP; NP → (Det) Nominal (PP | Rel)* or pronoun; Det → determiner or NP 's; PP → preposition NP; Nominal → noun (PP); Rel → wh-word S; VP → verb NP (PP). The Nominal node is the N-bar of the original paper: the head noun with its modifiers, below the determiner. Output: an NP node that is the proposed antecedent, or none.
The algorithm
HOBBS(π, T, T_1 .. T_q)- 1
step 1: start at the NP node π that dominates the pronoun; go up the tree to the first NP or S node - 2
step 2: call that node X and the path from X down to π the path p - 3
step 3: walk all branches below X to the left of p, breadth first and left to right; propose each NP that has an NP or S node between it and X - 4
step 4: if X is the highest S node of the sentence, walk the trees of the earlier sentences, the most recent first, each breadth first and left to right, propose each NP, and stop - 5
step 5: from X, go up to the first NP or S node; call it X and the path to it p - 6
step 6: if X is an NP and p does not pass through the Nominal node that X directly dominates, propose X - 7
step 7: walk all branches below X to the left of p, breadth first and left to right; propose each NP - 8
step 8: if X is an S node, walk all branches below X to the right of p, breadth first and left to right, but do not go below any NP or S node; propose each NP - 9
step 9: go to step 4 - 10
the answer is the first proposed NP that agrees with the pronoun in gender, number and person
The steps follow Jurafsky and Martin's statement of Hobbs (1978). A walk "below X to the left of p" passes through the path nodes but does not propose them, and it does not go below the node where the path ends; so each region of the tree is walked once. Hobbs also gave rules for reflexive pronouns and a semantic version with selectional constraints; the code and the steps above are the naive version.
Each step has a reason. Step 3 skips an NP that sits right next to the path in the smallest clause or NP around the pronoun: such an NP would be bound by the pronoun, which English allows only for reflexives. Step 6 does not propose an NP whose head part contains the pronoun, as "the Fords in his lot" for "his". Step 8 allows an antecedent to the right of the pronoun only in a higher clause and not inside a lower NP or S, which allows a few cases of cataphora.
Example
Jurafsky and Martin use this text: "Bob opened up a new dealership last week. John took a look at the Fords in his lot. He ended up buying one."
Take "his" in the second sentence. Its NP is the determiner of "his lot".
- Step 2: the first NP above the pronoun NP is "his lot". It is X, and the path goes through its Det node.
- Step 3: there is nothing to the left of the path below "his lot".
- Step 4: X is not the highest S. Step 5: climb through the PP "in his lot" and the Nominal "Fords in his lot" to the NP "the Fords in his lot", the new X.
- Step 6: the path passes through the Nominal of this NP, so it is not proposed. "The Fords in his lot" cannot be what "his" refers to.
- Step 7: below X to the left of the path there are only "the" and "Fords", no NP. Step 8: X is not an S.
- Back to step 4, then step 5: climb through the PP "at the Fords in his lot" and the VP to the S of the second sentence.
- Step 7: walk left of the path. The first row below S holds the NP "John" and the VP. "John" is proposed, it is masculine and singular like "his", and the algorithm returns it. A reader takes "his" to be Bob, whose dealership it is, so the algorithm errs here: its search prefers an NP of the same sentence and uses no knowledge of the world.
Now take "He" in the third sentence. It is the subject, so step 2 gives the S node, which is the highest S. Step 3 finds nothing to the left. Step 4 walks the second sentence breadth first: the first NP in the first row is "John", which agrees, so "He" is John. Jurafsky and Martin point out that the centering algorithm of Brennan, Friedman and Pollard picks Bob here instead (see centering theory); a reader picks John.
If the second sentence starts with "Mary" instead of "John", "his" no longer agrees with "Mary". The search proposes "Mary", then "a look" (neuter), and then it reaches step 4 at the top S and walks the first sentence, where the first NP is "Bob". For "John likes him" after "Bill arrived", the subject "John" is never proposed for "him", because step 3 needs an NP or S node between "John" and the S node, and there is none; the answer is "Bill". The test file checks all these cases.
Correctness
The algorithm is a heuristic, so the proof in proofs/correctness.md shows only what the search does: each walk is breadth first and left to right over exactly the region of its step, the search ends after at most one pass per level of the tree plus one walk of each earlier tree, no node is proposed twice, the pronoun itself is never proposed, and the two filters of steps 3 and 6 hold. The test file compares the walk with an independent order (by depth, then by preorder position) on random trees.
Proof: The Hobbs search ends, proposes each NP at most once, and never proposes the pronoun or an NP bound by itfull
The Hobbs algorithm is a heuristic: nothing guarantees that its answer is the true antecedent. What can be proved is that the search does what the nine steps say, that it ends, and that its order has the properties the page relies on. Fix the parse tree of the current sentence with root , the trees of the earlier sentences, and the NP node of the pronoun, with . The line numbers refer to the pseudocode on the page.
Claim 1: the walk of each step is breadth first, left to right, and covers exactly its region
For a node and a path down the tree, the region left of is the set of nodes below some , , in a subtree whose root is a child of to the left of ; the region right of is defined the same way with the children to the right. The walk side_of_path keeps a queue that starts with . When it takes a path node with , it appends the children on the chosen side and , in left-to-right order. When it takes it appends nothing. When it takes any other node, it yields it and appends its children. So the nodes yielded are exactly the nodes of the region, and every node of depth below enters the queue before any node of depth , because the queue receives nodes in the order of their parents. Among nodes of the same depth, a node enters the queue before every node to its right, since the parents are taken in left-to-right order and each parent appends its children left to right. This is the breadth-first, left-to-right order of steps 3, 7 and 8. Step 8 also does not append the children of an NP or S node, which is the rule "do not go below any NP or S node". The same argument gives the order of the plain walk bfs used in step 4. The test file compares bfs with an independent order, the sort by depth and then by preorder position.
Claim 2: the search ends
Each pass through lines L5 to L9 replaces by an NP or S node strictly above it, so moves up at each pass. The tree is finite, so after at most its height many passes , and line L4 then walks the earlier trees once each and stops. Each walk visits a finite tree once.
Claim 3: each NP is proposed at most once, and the pronoun never
Let be the node of line L2 and the nodes of line L5, with paths , where runs from down to (). Each region of step 3, 7 or 8 for lies below and outside the subtree of , because the end node of the path is not expanded. The subtrees of are nested, so the regions of different passes are disjoint, and in the same pass the left and right regions are disjoint by definition. A node proposed by line L6 is itself, which is in no region below and is outside every region of earlier passes, which lie below . A later pass sees only as an interior path node, which is not yielded. The earlier trees are disjoint from and from each other. Hence no node is proposed twice. The pronoun node is the end of the path and is not yielded by the walk of step 3; it is not an for ; so it is never proposed, and line L10 also skips it by identity.
Claim 4: the two syntactic filters
Step 3 proposes an NP below only if an NP or S node lies strictly between and . So an NP that is a sister of the path inside the smallest NP or S that holds the pronoun, such as the subject when the pronoun is the object in "John likes him", is never proposed in step 3. This is the effect Hobbs wanted: a non-reflexive pronoun is not bound inside its own clause. Step 6 proposes only if the path does not pass through the Nominal (N-bar) child of . So an NP whose head noun phrase contains the pronoun, such as "the Fords in his lot" for "his", is never proposed. The code tests the label of the first node of the path below , which is that child. Both properties follow from the code by reading lines L3 and L6, and the test file checks each on an example.
What is not claimed
The agreement test of line L10 uses the features given on the nodes; it is only as good as those features. Whether the first agreeing NP is the right antecedent depends on the text, and the accuracy figures on the page are measurements.
Complexity
Let be the number of nodes in the current and earlier trees and the height of the current tree. The regions of the walks are disjoint, so the walks visit each node at most once. Climbing from the pronoun to the root takes steps over all passes. The test of step 3, which looks for an NP or S between a candidate and X, costs per candidate in the code, so the total is ; carrying a flag down the walk makes it . In practice the search stops at the first agreeing NP, which is usually close. The parser that builds the trees costs far more than the search.
Properties
- Heuristic: the search order encodes three preferences (antecedents to the left, closer sentences first, subjects before objects through the breadth-first order) and two syntactic filters. It does not optimize any score.
- Deterministic and syntax only: it needs parse trees and agreement features, and no training data.
- Measured accuracy (a measurement): Hobbs evaluated the naive algorithm by hand on 300 pronouns, 100 from each of three texts, and reported 88.3% correct, and 91.7% when selectional constraints were added; these are the figures as summarized by Tetreault (2001), and other summaries give rounded or different numbers. On a manual of computer documentation, Lappin and Leass (1994) found that their own salience-based method did better than the Hobbs algorithm on the same pronouns. Tetreault (2001) found 80.1% for the Hobbs algorithm on a set of fiction texts. Numbers from different texts and parsers are not comparable.
- Correct parses assumed: the original evaluation used hand-built trees. With parser output, errors in the tree become errors in the search.
Variants and improvements
- Semantic constraints: Hobbs's own second method adds selectional checks, such as "the antecedent of it in it drove must be able to drive".
- Salience-based methods: Lappin and Leass (1994) give each candidate a weighted salience from its grammatical role, recency and parallelism, and pick the highest after filters.
- Centering: centering theory ranks the entities of the previous utterance by grammatical role and prefers the transition that keeps the same center; the algorithm of Brennan, Friedman and Pollard (1987) uses it for pronouns.
- Learned models: the Hobbs distance, the rank of a candidate in the Hobbs order, is a common feature of learned coreference models.
When to use it
Use it as a baseline for pronoun resolution when you have constituency parses, or as a feature in a learned model. It needs no training data. For full coreference over all mention types, use a learned model such as the span-ranking model.
Pitfalls
- Trees without Nominal nodes: Penn Treebank trees have no N-bar level, so steps 3 and 6 need a convention for where the head part of an NP begins. Without one, step 6 proposes NPs that contain the pronoun.
- Agreement features are not given: gender and number must come from a lexicon or a model, and errors there are common for names and organizations.
- Pleonastic "it": in "it is raining" the pronoun has no antecedent, but the algorithm will propose one. Detect such pronouns first.
- Reflexives: "himself" needs its antecedent inside its clause, the opposite of step 3. Treat reflexives with a separate rule.
- Comparing accuracy: the original numbers come from hand-checked trees on three texts; they are not comparable with numbers on parsed news text.
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/hobbs-algorithm/. The authors are listed in prov/3QNB55.jsonl.
"""The naive algorithm of Hobbs (1978) for resolving a pronoun.
The input is the parse tree of the sentence that holds the pronoun, the parse
trees of the earlier sentences (most recent last), and the NP node of the
pronoun. The trees follow Hobbs's grammar: S, NP, VP, PP, Det and Nominal
(his N-bar) nodes, with a Nominal child under each NP that has a noun head.
The algorithm proposes NP nodes in a fixed order. The first proposed NP that
agrees with the pronoun in gender, number and person is the answer. The
search is a heuristic: it has no guarantee of finding the right antecedent.
"""
from collections import deque
from typing import Dict, Iterator, List, Optional, Sequence
class Node:
"""A parse tree node. An NP may carry agreement features and a word for display."""
def __init__(self, label: str, children: Sequence["Node"] = (), word: str = "",
gender: Optional[str] = None, number: Optional[str] = None,
person: Optional[int] = None):
self.label = label
self.children = list(children)
self.word = word
self.feats = {"gender": gender, "number": number, "person": person}
def __repr__(self) -> str:
return "%s(%s)" % (self.label, self.text())
def text(self) -> str:
if self.word:
return self.word
return " ".join(c.text() for c in self.children)
def parents(root: Node) -> Dict[int, Node]:
"""Map id(node) to the parent node, for every node below root."""
out = {}
stack = [root]
while stack:
n = stack.pop()
for c in n.children:
out[id(c)] = n
stack.append(c)
return out
def agrees(a: Node, b: Node) -> bool:
"""True if no feature is set on both nodes with different values."""
for k in ("gender", "number", "person"):
x, y = a.feats[k], b.feats[k]
if x is not None and y is not None and x != y:
return False
return True
def bfs(root: Node, stop_below=lambda n: False) -> Iterator[Node]:
"""Breadth-first, left-to-right walk from root (excluded); do not expand nodes with stop_below."""
q = deque(root.children)
while q:
n = q.popleft()
yield n
if not stop_below(n):
q.extend(n.children)
def side_of_path(x: Node, path: List[Node], left: bool, stop_np_s: bool = False) -> Iterator[Node]:
"""Walk the branches below x to the left (or right) of the path, breadth first, left to right.
path[0] is x and path[-1] is the node the path ends at. Path nodes are walked
through but not yielded, and the end node is not expanded. Each yielded node
comes with nothing else; callers test its label.
"""
on_path = {id(n): k for k, n in enumerate(path)}
q = deque([x])
while q:
n = q.popleft()
k = on_path.get(id(n))
if k is not None:
if k == len(path) - 1:
continue
nxt = path[k + 1]
pos = next(i for i, c in enumerate(n.children) if c is nxt)
if left:
q.extend(n.children[:pos])
q.append(nxt)
else:
q.append(nxt)
q.extend(n.children[pos + 1:])
continue
yield n
if not (stop_np_s and n.label in ("NP", "S")):
q.extend(n.children)
def up_to_np_or_s(node: Node, par: Dict[int, Node]) -> Optional[List[Node]]:
"""Go up from node to the first NP or S above it. Return the path from that node down to node."""
path = [node]
n = node
while id(n) in par:
n = par[id(n)]
path.append(n)
if n.label in ("NP", "S"):
return path[::-1]
return None
def proposals(pron_np: Node, tree: Node, earlier: Sequence[Node]) -> Iterator[Node]:
"""Yield the NP nodes in the order the naive algorithm proposes them (no agreement test)."""
par = parents(tree)
path = up_to_np_or_s(pron_np, par) # @line L1
if path is None:
raise ValueError("the pronoun NP has no NP or S above it")
x = path[0] # @line L2
for n in side_of_path(x, path, left=True): # @line L3
if n.label == "NP":
m = par[id(n)]
between = False
while m is not x:
if m.label in ("NP", "S"):
between = True
break
m = par[id(m)]
if between:
yield n
while True:
if x is tree: # @line L4
for t in reversed(earlier):
for n in bfs(t):
if n.label == "NP":
yield n
return
path = up_to_np_or_s(x, par) # @line L5
if path is None:
raise ValueError("the root of the tree is not an S node")
x = path[0]
if x.label == "NP" and path[1].label != "Nominal": # @line L6
yield x
for n in side_of_path(x, path, left=True): # @line L7
if n.label == "NP":
yield n
if x.label == "S": # @line L8
for n in side_of_path(x, path, left=False, stop_np_s=True):
if n.label == "NP":
yield n
# @line L9: go back to step 4
def resolve(pron_np: Node, tree: Node, earlier: Sequence[Node] = ()) -> Optional[Node]:
"""Return the first proposed NP that agrees with the pronoun, or None."""
for n in proposals(pron_np, tree, earlier):
if n is not pron_np and agrees(n, pron_np): # @line L10
return n
return None
test_hobbs_algorithm.py 148 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hobbs-algorithm/. The authors are listed in prov/3QNB55.jsonl.
import random
from hobbs_algorithm import Node, agrees, bfs, parents, proposals, resolve
def name(w, g):
return Node("NP", [Node("NNP", word=w)], gender=g, number="sg", person=3)
def pron(w, g, num="sg"):
return Node("NP", [Node("PRP", word=w)], gender=g, number=num, person=3)
def common(det, noun, *pps, num="sg"):
"""NP -> Det Nominal, Nominal -> N PP*. Common nouns here are neuter."""
kids = [Node("Det", [Node("DT", word=det)])] if det else []
kids.append(Node("Nominal", [Node("N", word=noun)] + list(pps)))
return Node("NP", kids, gender="n", number=num, person=3)
def pp(p, np):
return Node("PP", [Node("P", word=p), np])
def s(subj, verb, *rest):
return Node("S", [subj, Node("VP", [Node("V", word=verb)] + list(rest))])
def jm_text(subj2="John", g2="m"):
"""Jurafsky and Martin's example: Bob opened up a new dealership last week.
John took a look at the Fords in his lot. He ended up buying one."""
bob = name("Bob", "m")
s1 = s(bob, "opened up", common("a", "new dealership"), common("", "last week"))
his = pron("his", "m")
his_lot = Node("NP", [Node("Det", [his]), Node("Nominal", [Node("N", word="lot")])],
gender="n", number="sg", person=3)
fords = common("the", "Fords", pp("in", his_lot), num="pl")
subj = name(subj2, g2)
s2 = s(subj, "took", common("a", "look"), pp("at", fords))
he = pron("He", "m")
s3 = s(he, "ended up", Node("VP", [Node("V", word="buying"), pron("one", "n")]))
return bob, s1, subj, his, fords, s2, he, s3
def test_jm_example():
bob, s1, john, his, fords, s2, he, s3 = jm_text()
assert resolve(he, s3, [s1, s2]) is john
assert resolve(his, s2, [s1]) is john
# "the Fords in his lot" is never proposed for "his": the path passes its Nominal.
assert fords not in list(proposals(his, s2, [s1]))
def test_agreement_moves_to_earlier_sentence():
bob, s1, mary, his, fords, s2, he, s3 = jm_text("Mary", "f")
order = list(proposals(his, s2, [s1]))
assert [n.text() for n in order[:3]] == ["Mary", "a look", "Bob"]
assert resolve(his, s2, [s1]) is bob
def test_object_pronoun_skips_subject():
bill = name("Bill", "m")
s1 = Node("S", [bill, Node("VP", [Node("V", word="arrived")])])
john = name("John", "m")
him = pron("him", "m")
s2 = s(john, "likes", him)
# Step 3 needs an NP or S between the candidate and X, so John is not proposed.
assert john not in list(proposals(him, s2, [s1]))
assert resolve(him, s2, [s1]) is bill
def test_possessive_inside_subject():
john = name("John", "m")
mother = Node("NP", [Node("Det", [john, Node("POS", word="'s")]),
Node("Nominal", [Node("N", word="mother")])], gender="f", number="sg", person=3)
him = pron("him", "m")
s1 = s(mother, "likes", him)
order = list(proposals(him, s1, []))
assert order == [john]
assert resolve(him, s1) is john
def test_step_8_right_of_path():
him = pron("him", "m")
picture = common("the", "picture", pp("of", him))
john = name("John", "m")
s1 = s(picture, "pleased", john)
assert list(proposals(him, s1, [])) == [john]
assert resolve(him, s1) is john
def test_no_antecedent():
she = pron("she", "f")
s1 = Node("S", [she, Node("VP", [Node("V", word="left")])])
assert resolve(she, s1, [s(name("Tom", "m"), "slept")]) is None
def test_agreement():
assert agrees(pron("it", "n"), common("a", "car"))
assert not agrees(pron("they", None, "pl"), common("a", "car"))
assert agrees(Node("NP"), pron("she", "f"))
def level_order(root):
"""An independent breadth-first order: sort by depth, then by preorder position."""
out = []
stack = [(root, 0)]
while stack:
n, d = stack.pop()
out.append((d, len(out), n))
for c in reversed(n.children):
stack.append((c, d + 1))
return [n for d, k, n in sorted(out, key=lambda t: (t[0], t[1])) if n is not root]
def random_tree(rng, depth=0):
labels = ["S", "NP", "VP", "PP", "Nominal", "Det"]
if depth >= 4 or rng.random() < 0.3:
return Node("NP", [Node("N", word="w")], gender=rng.choice("mfn"))
k = rng.randint(1, 3)
return Node(rng.choice(labels), [random_tree(rng, depth + 1) for _ in range(k)],
gender=rng.choice("mfn"))
def test_breadth_first_order_and_uniqueness():
rng = random.Random(7)
for _ in range(300):
t = random_tree(rng)
t = Node("S", [t, random_tree(rng)])
assert [id(n) for n in bfs(t)] == [id(n) for n in level_order(t)]
prev = Node("S", [random_tree(rng), random_tree(rng)])
nps = [n for n in level_order(t) if n.label == "NP" and n.children and n.children[0].label == "N"]
p = rng.choice(nps)
got = list(proposals(p, t, [prev]))
ids = [id(n) for n in got]
assert len(ids) == len(set(ids))
assert all(n.label == "NP" for n in got)
assert p not in got
# Step 4 lists the earlier sentence in breadth-first order.
tail = [n for n in level_order(prev) if n.label == "NP"]
assert [id(n) for n in got[-len(tail):]] == [id(n) for n in tail]
# Every proposal from the current sentence is a node of it.
inside = {id(n) for n in level_order(t)}
assert all(id(n) in inside for n in got[:len(got) - len(tail)])
par = parents(t)
assert id(p) in par
History
Hobbs (1978) proposed the naive algorithm as a baseline, to show how much a purely syntactic method could do, next to a semantic method of his own. Its high accuracy on his three texts made it the standard baseline that later pronoun resolution methods were measured against, including the centering method of Brennan, Friedman and Pollard (1987) and the salience method of Lappin and Leass (1994). It is still taught as the first pronoun resolution algorithm in textbooks such as Jurafsky and Martin.
References
- Hobbs 1978, the naive algorithm on surface parse trees, and its evaluation by hand on pronouns from three texts
- Daniel Jurafsky and James H. Martin, Speech and Language Processing, 2nd edition, Prentice Hall, 2009, Chapter 21, Computational Discourse (the section on the Hobbs algorithm with its grammar fragment, the nine steps and a worked example)
- Lappin and Leass 1994, the comparison of their salience-based method with the Hobbs algorithm on the same pronouns
- Tetreault 2001, the summary of the evaluation of Hobbs 1978, and a new evaluation of the Hobbs algorithm and centering methods on news and fiction text
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 3QNB55 Edit this page History Report an error Markdown