Algorithmcore
Hearst patterns
Also called lexico-syntactic hyponymy patterns.
Extract hyponym and hypernym pairs from text with six hand-chosen lexico-syntactic patterns, such as X such as Y and Y and other X.
- Time
- O(n) worst
- Space
- O(n) extra
- Where
- n = the number of items (noun phrases and words) of the sentence
- Model
- Word RAM
- Properties
- deterministicnot exactofflineiterativenot supervised
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Marti A. Hearst, 1992
Hearst patterns find pairs of noun phrases where one names a kind of the other, the hyponym relation, as in "France" and "European countries". Hearst 1992 listed six patterns that are made of a few fixed words and slots for noun phrases. "NP such as NP, NP and NP" is one of them: every noun phrase in the list after "such as" is a hyponym of the noun phrase before it. The patterns are found by hand. A matcher that runs them is a single left to right scan over a sentence whose noun phrases a chunker has already marked. The patterns are a heuristic: a match is evidence for the relation, not a proof of it. They find few pairs per million words, and Hearst judged the quality of the pairs she found high.
In plain words
People write sentences such as "most European countries, especially France, England and Spain". Without knowing anything about geography, a reader can tell from the words "especially" and the list that France, England and Spain are European countries.
Hearst picked six such fixed phrases: "such as", "such ... as", "or other", "and other", "including" and "especially". The method first groups the words of a sentence into noun phrases. Then it looks for one of the fixed phrases with a noun phrase on one side and a list of noun phrases on the other side. Each noun phrase in the list is reported as a kind of the single noun phrase. The method needs no training data and no dictionary, but it only finds pairs that a writer happened to state in one of these six ways.
The problem
The input is a sentence as a list of items, where each item is a noun phrase (NP) from a chunker or a single word, and the comma is a word. The output is every triple (hyponym, hypernym, pattern) that one of the six patterns matches. With CONJ for "and" or "or", the patterns of Hearst 1992 are:
| pattern | form | hypernym | hyponyms |
|---|---|---|---|
| 1 | NP [,] such as LIST | NP | the NPs of LIST |
| 2 | such NP as LIST | NP | the NPs of LIST |
| 3 | LEFT [,] or other NP | NP | the NPs of LEFT |
| 4 | LEFT [,] and other NP | NP | the NPs of LEFT |
| 5 | NP [,] including LIST | NP | the NPs of LIST |
| 6 | NP [,] especially LIST | NP | the NPs of LIST |
A LIST is NP ("," NP) [[","] CONJ NP], and a LEFT is NP ("," NP). Brackets mark an optional part. Each list is read as far as it goes: to the right after the trigger words, to the left before them. With these rules the output is well defined, and the matcher below computes it exactly.
The algorithm
RIGHT-LIST() returns the positions of the NPs of the longest LIST that starts at item . It reads ", NP" as long as it can, then one "CONJ NP" or ", CONJ NP" if it is there. LEFT-LIST() skips one comma before if there is one, then reads NP and ", NP" pairs to the left. NP-BEFORE() is the NP at , or at with a comma at , or nothing.
HEARST(a_0 .. a_{n-1})- 1
R ← empty list - 2
for p ← 0 to n - 1 do - 3
if a_p a_{p+1} = "such as" and h ← NP-BEFORE(p) exists then add (x, h, 1) to R for each x in RIGHT-LIST(p + 2) - 4
else if a_p = "such", a_{p+1} is an NP and a_{p+2} = "as" then add (x, p + 1, 2) to R for each x in RIGHT-LIST(p + 3) - 5
else if a_p ∈ {"including", "especially"} and h ← NP-BEFORE(p) exists then add (x, h, 5 or 6) to R for each x in RIGHT-LIST(p + 1) - 6
else if a_p ∈ {"or", "and"}, a_{p+1} = "other" and a_{p+2} is an NP then add (x, p + 2, 3 or 4) to R for each x in LEFT-LIST(p) - 7
return R
Words are compared in lowercase. Each position triggers at most one line, since lines L3 and L4 differ in the item after "such", and lines L5 and L6 test other words.
Example
The sentences below are the examples of Hearst 1992, with the noun phrases in brackets as a chunker could mark them.
| sentence | line | output pairs |
|---|---|---|
| [the bow lute] , such as [the Bambara ndang] , is plucked | L3 | (the Bambara ndang, the bow lute) |
| works by such [authors] as [Herrick] , [Goldsmith] , and [Shakespeare] | L4 | (Herrick, authors), (Goldsmith, authors), (Shakespeare, authors) |
| [bruises] , [wounds] , [broken bones] or other [injuries] | L6 | (bruises, injuries), (wounds, injuries), (broken bones, injuries) |
| [temples] , [treasuries] , and other [important civic buildings] | L6 | (temples, important civic buildings), (treasuries, important civic buildings) |
| [all common-law countries] , including [Canada] and [England] | L5 | (Canada, all common-law countries), (England, all common-law countries) |
| [most European countries] , especially [France] , [England] , and [Spain] | L5 | (France, most European countries), (England, most European countries), (Spain, most European countries) |
A trace of the last sentence, with the items numbered from 0: [most European countries] is 0, "," is 1, "especially" is 2, [France] is 3, "," is 4, [England] is 5, "," is 6, "and" is 7 and [Spain] is 8.
| p | item | what happens |
|---|---|---|
| 0, 1 | NP, "," | no trigger |
| 2 | especially | line L5: NP-BEFORE(2) skips the comma at 1 and gives 0; RIGHT-LIST(3) reads 3, then ", NP" at 4 and 5, then ", and NP" at 6 to 8, and stops |
| 3 to 6 | NPs and commas | no trigger |
| 7 | and | line L6 is false, since item 8 is an NP and not "other" |
| 8 | NP | no trigger |
The output is (3, 0, 6), (5, 0, 6) and (8, 0, 6).
Correctness
The claim is exact about the patterns and says nothing about the meaning of the sentence: HEARST returns exactly the triples of the six patterns, with the longest lists, in the order of the trigger position. The key step is that a list can grow in only one way at each point. After a list of NPs separated by commas, the next items are ", NP", "CONJ NP" or ", CONJ NP", and these cases exclude each other, so the lists that start at one position form a chain and the scan of RIGHT-LIST stops at the longest one. The same holds for LEFT-LIST to the left. Each position triggers at most one of lines L3 to L6, and each line tests exactly the condition of its pattern. The full proof is below.
Whether a match is a true hyponym pair is a different question. The patterns are a heuristic, and their quality is a measurement on a corpus.
Proof: The matcher returns exactly the matches of the six patterns, with the longest listsfull
We use the pseudocode of the page. A sentence is a sequence of items, each a noun phrase (NP) or a word, and words are compared in lowercase. CONJ is the set . The proof is about the patterns as they are written. Whether a match is a true hyponym pair is a heuristic question, answered by measurement.
The specification. A right list at is a sequence of items of the form NP ("," NP) [[","] CONJ NP]. The longest right list at is the right list at with the largest , and is the set of positions of its NPs, or if is not an NP. A left list ending at is a sequence of the form NP ("," NP) [","], and is the set of NP positions of the one with the smallest , or if there is none. The hypernym before is if is an NP, if is "," and is an NP, and undefined otherwise. A position triggers:
- pattern 1 if = "such as" and is defined, with the matches for ;
- pattern 2 if = "such", is an NP and = "as", with the matches for ;
- pattern 5 or 6 if is "including" or "especially" and is defined, with the matches for ;
- pattern 3 or 4 if is "or" or "and", = "other" and is an NP, with the matches for .
Lemma 1. The function RIGHT-LIST() stops and returns .
Proof. If is not an NP, there is no right list at and the function returns the empty list. Otherwise, call a right list at open if it has no CONJ, and closed if it ends with CONJ NP. Let be an open right list. The items that can follow it in a longer right list are ", NP" (a longer open list), "CONJ NP" (a closed list) or ", CONJ NP" (a closed list). These three cases are disjoint: the first and the third both start with ",", but the item after the comma is an NP in the first and a word in the third, and the second starts with a word in CONJ, which is not ",". A closed list cannot be extended. So the right lists at form one chain , each a prefix of the next, where and is the unique one-step extension of . The loop keeps the invariant that is the open list and that holds its NP positions. Each test of the loop checks one of the three cases. In the first case it moves to and adds its new NP. In the second and third cases it adds the last NP of the closed list and returns. If no case applies, has no extension and is the longest. Each round of the loop increases by 2 or returns, and at the start of every round, so the loop stops. In all cases it returns the NP positions of the last list of the chain, which is the longest.
Lemma 2. The function LEFT-LIST() stops and returns .
Proof. Read the items from toward 0. A left list ending at is an optional "," at , then an NP, then zero or more pairs "," NP read to the left. Whether the optional comma is present is decided by , since an NP is not ",". After that, the same argument as in Lemma 1 applies in the reverse direction with one extension case, ", NP": the left lists form one chain, and the loop follows it one pair at a time until is not "," or is not an NP. It returns the positions of the longest one, in left to right order. The index decreases by 2 each round and stays at least 0, so the loop stops.
Claim. HEARST returns, in the order of and then of the list, exactly the matches of the specification, and it stops.
Proof. Each position triggers at most one pattern. Patterns 1 and 2 both start with "such", but is the word "as" for pattern 1 and an NP for pattern 2. Patterns 5 and 6 start with "including" or "especially", and patterns 3 and 4 with "and" or "or", which are different words from "such" and from each other. Line L3 tests the condition of pattern 1 and, with the function NP-BEFORE, which returns by its definition, the existence of . Line L4 tests pattern 2, line L5 patterns 5 and 6 with , and line L6 patterns 3 and 4. When the test of a line holds, it adds one triple per position of RIGHT-LIST or LEFT-LIST, which are and by Lemmas 1 and 2. So the loop of line L2 adds, for each in increasing order, exactly the matches that triggers. The loop has rounds, each of which stops by the lemmas, and line L7 returns the list.
Complexity
The model is the word-RAM, with each item a word or an NP whose kind is known in constant time.
- Triggers. Lines L3 to L6 test a constant number of items at each position: for the loop of line L2.
- Lists. A list holds only NPs, commas and one conjunction followed by an NP. None of these is a trigger, since a trigger conjunction is followed by "other". So two right lists never share an item, two left lists never share an item, and each item is read by at most two lists. All the calls of RIGHT-LIST and LEFT-LIST together take time.
- Total. time per sentence, and space for the output, which has at most one triple per item for each kind of list. Over a corpus the cost is linear in its size, plus the cost of the chunker.
Properties
- No training data. The six patterns are fixed in advance, and the matcher needs no labeled pairs and no lexicon.
- Domain independent. Hearst chose patterns that occur often and in many kinds of text, that almost always indicate the relation, and that can be found with little knowledge in advance. These are the three properties she asked of a pattern, and the second one is a heuristic.
- Low recall. A pair is found only if one sentence states it in one of the six forms. Hearst 1992 reports, as a measurement, 7067 sentences with "such as" in the 8.6 million words of Grolier's encyclopedia and 152 relations that met her restrictions on the noun phrases, or 330 with looser restrictions, and 46 relations from 3178 sentences in about 20 million words of the New York Times.
- Checked against WordNet. Of 226 unique words in the encyclopedia pairs, 180 were in WordNet, and of the 106 relations whose words were both in WordNet, 61 were already there. Hearst judged the quality of the pairs high overall, without a precision figure.
- Order of the output. The hypernym of patterns 1, 2, 5 and 6 comes before the list, and that of patterns 3 and 4 after it.
Variants and improvements
- More patterns. Hearst 1992 gives a manual procedure: take a relation and pairs known to have it, find sentences where the two words occur close together, find what these sentences have in common, and use a new pattern to find new pairs. She did not automate it, because the step of finding what the sentences have in common was not well defined.
- Learned patterns. Later work learns patterns from dependency paths between known pairs, with known pairs from a lexicon as the training data, which is the idea of distant supervision. DIPRE grows patterns and pairs in a loop, starting from a few seed pairs.
- Counts over a corpus. Pairs from a large corpus can be scored by how often each pattern links them, for example with PPMI, and smoothed by a low-rank factorization, which finds pairs that no single sentence states.
- Regular expressions over tags. Without a chunker, the patterns can be written as regular expressions over part-of-speech tags, with an NP as a run of determiners, adjectives and nouns.
When to use it
Use the patterns to seed a taxonomy or to extend a lexicon such as WordNet from a large corpus, when high precision matters more than coverage and there is no labeled data. They are also a simple baseline for hypernym detection. When the relation is stated in many ways, or when the pairs must come from a small corpus, learned patterns or distributional methods find more pairs.
Pitfalls
- The wrong noun phrase before the trigger. Lines L3 and L5 take the NP just before the trigger as the hypernym. In "[countries] with [large populations] , such as [India]", line L3 reports India as a kind of large populations, while the hypernym is "countries". Attach prepositional phrases to the NP before matching, or check the head of the larger phrase.
- A left list that reads too far. Line L6 reads NPs and commas to the left as far as it can. In "after [the storm] , [roads] , [bridges] and other [structures] were closed", it reports the storm as a kind of structure, since the comma after "the storm" ends a clause and not a list item. A chunker that marks clauses, or a limit on the list, helps.
- Part of instead of kind of. "Including" also introduces parts and members. In "[the kit] , including [a hammer] and [nails]", line L5 reports a hammer as a kind of kit. Check the pairs against a lexicon, or keep pattern 5 only for high-count pairs.
- The list without its last comma. A RIGHT-LIST that does not accept ", CONJ NP" stops before "Spain" in the example above, and loses the last item of every list written with a serial comma. Accept both "CONJ NP" and ", CONJ NP".
- Full phrases as the pair. The output pairs are noun phrases such as "important civic buildings". A lexicon has "building". Reduce each NP to its lemmatized head noun before comparing it with a lexicon, as Hearst did for the WordNet check.
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/hearst-patterns/. The authors are listed in prov/B0F1S5.jsonl.
"""Hearst patterns: find hyponym and hypernym noun phrases with six fixed
lexico-syntactic patterns.
A sentence is a list of items. An item is a noun phrase, given as a tuple of
tokens (the output of a chunker), or a single word given as a str, including
the comma ",". The six patterns, with the numbers of Hearst 1992:
1 NP0 [,] such as LIST
2 such NP0 as LIST
3 LEFT [,] or other NP0
4 LEFT [,] and other NP0
5 NP0 [,] including LIST
6 NP0 [,] especially LIST
LIST is NP ("," NP)* [[","] (and | or) NP], read to the right as far as it
goes, and LEFT is NP ("," NP)*, read to the left as far as it goes. Each NP of
the list is a hyponym of NP0.
"""
Item = tuple[str, ...] | str
CONJ = ("and", "or")
def is_np(items: list[Item], i: int) -> bool:
return 0 <= i < len(items) and isinstance(items[i], tuple)
def word(items: list[Item], i: int) -> str | None:
"""The lowercased word at i, or None for a noun phrase or a position outside the list."""
if 0 <= i < len(items) and isinstance(items[i], str):
return items[i].lower()
return None
def right_list(items: list[Item], q: int) -> list[int]:
"""The positions of the noun phrases of the longest LIST that starts at q."""
if not is_np(items, q):
return []
out = [q]
j = q + 1
while True:
if word(items, j) == "," and is_np(items, j + 1):
out.append(j + 1)
j += 2
elif word(items, j) in CONJ and is_np(items, j + 1):
out.append(j + 1)
return out
elif word(items, j) == "," and word(items, j + 1) in CONJ and is_np(items, j + 2):
out.append(j + 2)
return out
else:
return out
def left_list(items: list[Item], p: int) -> list[int]:
"""The positions of the noun phrases of the longest LEFT [,] that ends just before p."""
j = p - 1
if word(items, j) == ",":
j -= 1
if not is_np(items, j):
return []
out = [j]
while word(items, j - 1) == "," and is_np(items, j - 2):
j -= 2
out.append(j)
return out[::-1]
def np_before(items: list[Item], p: int) -> int | None:
"""The noun phrase just before p, with an optional comma between, or None."""
if is_np(items, p - 1):
return p - 1
if word(items, p - 1) == "," and is_np(items, p - 2):
return p - 2
return None
def hearst_matches(items: list[Item]) -> list[tuple[int, int, int]]:
"""All (hyponym position, hypernym position, pattern) triples, in the order of the triggers.
Cost: O(len(items)). A list holds only noun phrases, commas and one
conjunction followed by a noun phrase, so it contains no trigger, the
right lists do not overlap, the left lists do not overlap, and each item
is read by at most two lists.
"""
found: list[tuple[int, int, int]] = [] # @line L1
for p in range(len(items)): # @line L2
w = word(items, p)
if w == "such" and word(items, p + 1) == "as": # @line L3
h = np_before(items, p)
if h is not None:
found += [(x, h, 1) for x in right_list(items, p + 2)]
elif w == "such" and is_np(items, p + 1) and word(items, p + 2) == "as": # @line L4
found += [(x, p + 1, 2) for x in right_list(items, p + 3)]
elif w in ("including", "especially"): # @line L5
h = np_before(items, p)
if h is not None:
found += [(x, h, 5 if w == "including" else 6) for x in right_list(items, p + 1)]
elif w in CONJ and word(items, p + 1) == "other" and is_np(items, p + 2): # @line L6
found += [(x, p + 2, 3 if w == "or" else 4) for x in left_list(items, p)]
return found # @line L7
def hearst_pairs(items: list[Item]) -> list[tuple[str, str, int]]:
"""The matches as (hyponym text, hypernym text, pattern)."""
return [(" ".join(items[x]), " ".join(items[h]), k) for x, h, k in hearst_matches(items)]
test_hearst_patterns.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hearst-patterns/. The authors are listed in prov/B0F1S5.jsonl.
import random
import re
from hearst_patterns import hearst_matches, hearst_pairs
def items(text: str) -> list:
"""Brackets mark the noun phrases: "[the bow lute] , such as [the Bambara ndang]"."""
out: list = []
for part in re.findall(r"\[[^\]]*\]|\S+", text):
out.append(tuple(part[1:-1].split()) if part.startswith("[") else part)
return out
def test_hearst_examples() -> None:
cases = [
("[the bow lute] , such as [the Bambara ndang] , is plucked", [("the Bambara ndang", "the bow lute", 1)]),
("works by such [authors] as [Herrick] , [Goldsmith] , and [Shakespeare] .",
[("Herrick", "authors", 2), ("Goldsmith", "authors", 2), ("Shakespeare", "authors", 2)]),
("[bruises] , [wounds] , [broken bones] or other [injuries]",
[("bruises", "injuries", 3), ("wounds", "injuries", 3), ("broken bones", "injuries", 3)]),
("[temples] , [treasuries] , and other [important civic buildings] .",
[("temples", "important civic buildings", 4), ("treasuries", "important civic buildings", 4)]),
("[all common-law countries] , including [Canada] and [England]",
[("Canada", "all common-law countries", 5), ("England", "all common-law countries", 5)]),
("[most European countries] , especially [France] , [England] , and [Spain] .",
[("France", "most European countries", 6), ("England", "most European countries", 6),
("Spain", "most European countries", 6)]),
]
for text, want in cases:
assert hearst_pairs(items(text)) == want
def test_edges() -> None:
assert hearst_matches([]) == []
assert hearst_matches(items("such as [dogs]")) == []
assert hearst_matches(items("[animals] such as")) == []
assert hearst_matches(items("and other [animals]")) == []
assert hearst_pairs(items("[animals] SUCH AS [cats] , [dogs] ,")) == [("cats", "animals", 1), ("dogs", "animals", 1)]
assert hearst_pairs(items("[pets] such as [cats] and [dogs] and [birds]")) == [("cats", "pets", 1), ("dogs", "pets", 1)]
assert hearst_pairs(items("[cats] , [dogs] and other [pets] , such as [birds]")) == [
("cats", "pets", 4), ("dogs", "pets", 4), ("birds", "pets", 1),
]
CODE = {",": ",", "such": "s", "as": "a", "and": "&", "or": "|", "other": "o", "including": "i", "especially": "e"}
RIGHT = re.compile(r"N(,N)*(,?[&|]N)?")
LEFT = re.compile(r",?N(,N)*")
def oracle(seq: list) -> list[tuple[int, int, int]]:
"""The same patterns as regular expressions over a one-letter code of the items."""
enc = "".join("N" if isinstance(x, tuple) else CODE.get(x.lower(), "w") for x in seq)
out = []
def nps(start: int, stop: int) -> list[int]:
return [i for i in range(start, stop) if enc[i] == "N"]
for p in range(len(enc)):
before = re.search(r"N,?$", enc[:p])
h = None if before is None else before.start()
if enc.startswith("sa", p) and h is not None:
m = RIGHT.match(enc, p + 2)
if m:
out += [(x, h, 1) for x in nps(m.start(), m.end())]
elif re.match(r"sNa", enc[p:]):
m = RIGHT.match(enc, p + 3)
if m:
out += [(x, p + 1, 2) for x in nps(m.start(), m.end())]
elif enc[p:p + 1] in ("i", "e") and h is not None:
m = RIGHT.match(enc, p + 1)
if m:
out += [(x, h, 5 if enc[p] == "i" else 6) for x in nps(m.start(), m.end())]
elif re.match(r"[&|]oN", enc[p:]):
m = LEFT.match(enc[:p][::-1])
if m:
out += [(x, p + 2, 3 if enc[p] == "|" else 4) for x in nps(p - m.end(), p)]
return out
def test_against_regex_oracle() -> None:
rng = random.Random(3)
words = [",", "such", "as", "and", "or", "other", "including", "especially", "the", "is", "Such"]
triggers = [["such", "as"], ["such", ("np",), "as"], ["and", "other"], ["or", "other"], ["including"], ["especially"]]
hits = 0
for _ in range(5000):
seq = [("np%d" % i,) if rng.random() < 0.45 else rng.choice(words) for i in range(rng.randrange(0, 14))]
if seq and rng.random() < 0.6:
p = rng.randrange(len(seq))
seq[p:p] = rng.choice(triggers)
got = hearst_matches(seq)
hits += bool(got)
assert got == oracle(seq)
assert len(got) == len(set(got))
for x, h, k in got:
assert isinstance(seq[x], tuple) and isinstance(seq[h], tuple) and x != h and 1 <= k <= 6
assert hits >= 500
History
Hearst 1992 presented the patterns at COLING as a way to acquire hyponyms from text with no pre-encoded knowledge, and to check and extend hand-built lexicons. She found the six patterns by hand, partly with the procedure above, and noted that she had not implemented an automatic version. The patterns became a standard baseline for hypernym detection and a common way to seed taxonomies, and later work learned more patterns from data.
References
- Hearst 1992, the six patterns numbered 1 to 6 with their examples, the three properties a pattern should have, the five step procedure for finding new patterns, and the results on Grolier's encyclopedia and the New York Times compared with WordNet
- Jurafsky and Martin, SLP3 draft of August 2025, the chapter on information extraction, the section on relation extraction with patterns
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 B0F1S5 Edit this page History Report an error Markdown