Algorithmcore
Brown clustering
Also called Brown clusters, class-based bigram clustering.
Greedy agglomerative clustering of words that merges the two classes whose merge least lowers the mutual information of a class bigram model.
- Time
- O(N + V^4) worst
- Space
- Θ(V^2) extra
- Where
- C = the number of classes asked for; N = the number of tokens; V = the number of word types (the vocabulary size)
- Model
- Word RAM
- Properties
- deterministicnot exactgreedyofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter F. Brown, Peter V. deSouza, Robert L. Mercer, Vincent J. Della Pietra, Jenifer C. Lai, 1992
Brown clustering puts the words of a vocabulary into classes by greedy agglomerative clustering. It starts with one class per word. At each step it merges the two classes whose merge loses the least average mutual information between the classes of adjacent words, which is the same as keeping the likelihood of a class bigram language model as high as possible. If the merging goes on to one class, the merges form a binary tree, and the path from the root to a word is a bit string that serves as a word feature. Unlike k-means or a generic agglomerative clustering, the objective is not a distance between points: it is the information that one class carries about the class of the next word.
In plain words
Words that can appear in the same places in a sentence should go in the same group. "Cat" and "dog" both come after "the" and before "runs", so a model that predicts the group of the next word loses almost nothing if it cannot tell them apart.
The method begins with every word alone. Then it tries every pair of groups, asks how much prediction power the merge would cost, and does the cheapest merge. It repeats this until the number of groups you asked for is left. If you keep going to one group, the order of the merges makes a family tree of the words. Each word gets a code of zeros and ones that says how to walk down the tree to it. Words with a long common prefix are close in the tree.
The problem
The input is a corpus, a list of sentences of word tokens, and a number of classes . The bigrams are the adjacent token pairs inside each sentence, with no padding, and counts the pair ; let be the total number of bigrams. A partition of the word types into classes gives class counts , the probabilities , and the marginals and . The average mutual information (AMI) of is
which is the expected pointwise mutual information of the class of a word and the class of the next word, or the Kullback-Leibler divergence of from . Brown et al. (equation 9) show that the log likelihood per bigram of the class bigram model , with relative frequency parameters, is minus an entropy that does not depend on . So the best partition into classes is the one with the largest . Brown et al. give no exact method for it, and Brown clustering is a greedy heuristic for it.
The algorithm
Write , with when , and , the part of in row and column . For a merge of and , write for the merged class, and for the value computed from the summed counts and the summed marginals.
BROWN-CLUSTERING(corpus, C)- 1
V ← word types by decreasing count; class i ← {V[i]} - 2
n(l, m) ← count of the adjacent pairs of classes (l, m) in each sentence - 3
k ← |V| - 4
while k > C do - 5
compute p_L, p_R, q(l, m), s(l) and I ← sum of all q(l, m) - 6
for each pair i < j of current classes do - 7
I(i, j) ← I - s(i) - s(j) + q(i, j) + q(j, i) + q(i+j, i+j) + Σ_{l ≠ i, j} [q(l, i+j) + q(i+j, l)] - 8
(i, j) ← the pair with the largest I(i, j), the first pair on ties - 9
add row j to row i and column j to column i; delete row and column j - 10
record the merge (i, j); k ← k - 1 - 11
return the k classes and the merges
Line L7 is equation 15 of Brown et al. It gives the AMI after the merge in time, because the merge changes only the cells in rows and columns and . Line L9 keeps the merged class at position . The code breaks ties within in favor of the first pair, so that rounding does not decide them.
The tree and the bit strings. Run the loop with . Each merge makes a tree node with the kept class as left child and the removed class as right child. The bit string of a word is the path from the root, 0 for left and 1 for right. Undoing the last merges gives the partition into classes, and a prefix of length of the bit strings groups the words into at most clusters.
Example
The corpus is one sentence of 15 tokens: "the cat runs and the dog sleeps and a dog runs and the cat sleeps". It has 14 bigrams and types, ordered by count as and, the, cat, dog, runs, sleeps, a. The bigram counts are (row = first word):
| and | the | cat | dog | runs | sleeps | a | |
|---|---|---|---|---|---|---|---|
| and | 0 | 2 | 0 | 0 | 0 | 0 | 1 |
| the | 0 | 0 | 2 | 1 | 0 | 0 | 0 |
| cat | 0 | 0 | 0 | 0 | 1 | 1 | 0 |
| dog | 0 | 0 | 0 | 0 | 1 | 1 | 0 |
| runs | 2 | 0 | 0 | 0 | 0 | 0 | 0 |
| sleeps | 1 | 0 | 0 | 0 | 0 | 0 | 0 |
| a | 0 | 0 | 0 | 1 | 0 | 0 | 0 |
The AMI of the partition into single words is 1.4377 nats. The merges, with the AMI after each one:
| step | classes before | merge | AMI after | loss |
|---|---|---|---|---|
| 1 | 7 | runs + sleeps | 1.4377 | 0.0000 |
| 2 | 6 | the + a | 1.3761 | 0.0616 |
| 3 | 5 | cat + dog | 1.3761 | 0.0000 |
| 4 | 4 | and + {the, a} | 0.7375 | 0.6385 |
| 5 | 3 | {and, the, a} + {runs, sleeps} | 0.1175 | 0.6200 |
| 6 | 2 | all + {cat, dog} | 0.0000 | 0.1175 |
Step 1 loses nothing because "runs" and "sleeps" have proportional rows (both are followed only by "and") and equal columns (both follow "cat" once and "dog" once). Merging two classes with proportional rows and proportional columns never changes . At step 2 the pairs (the, a) and (cat, dog) tie at 1.3761, and the tie rule takes (the, a) because it comes first in the order of line L6. After it, "cat" and "dog" have equal rows and proportional columns, so step 3 is free. Step 4 is again a tie, between "and" with {the, a} and "and" with {runs, sleeps}. With the algorithm stops after step 4 with {and, the, a}, {cat, dog} and {runs, sleeps}. The full tree gives the bit strings and 000, the 0010, a 0011, runs 010, sleeps 011, cat 10 and dog 11.
Correctness
The claim is that each merge joins the pair of classes whose merge gives the largest AMI among all pairs, and that the loop stops with classes. The key step is the merge formula of line L7: a merge leaves every cell outside rows and columns and unchanged, together with its marginals, and the cells inside are counted by . The invariant of the loop is that the matrix holds the class bigram counts of the current partition, which line L9 keeps. By the likelihood identity of Brown et al., each step also gives the class bigram model of the highest likelihood among the partitions one merge away. The full proof, with the likelihood identity, is below.
The claim is about one step. The sequence of greedy merges does not find the best partition in general (see Pitfalls).
Proof: Each Brown merge is the merge that keeps the most average mutual informationfull
We use the pseudocode of the page. The corpus has word types. The bigrams are the adjacent token pairs inside each sentence, is the number of times the pair occurs, and . All logs are natural.
Notation. A partition of the vocabulary into classes gives the class counts . Let , and . Let
with when . If , then and , so is well defined. The average mutual information of is , and for a class let , the sum of over row and column , with the cell counted once.
Lemma 1 (the merge formula, equation 15 of Brown et al.). Let be two classes of with classes, and let be with and replaced by their union . Then
where is computed in , that is, from the counts , , the sum of the four counts of , and the marginals and .
Proof. Take a cell with . Its count does not change. The row of in has the same total as in , because the merge only adds two cells of that row together, so . In the same way . So for all these cells.
Let be the set of cells of in row , row , column or column . The sum covers row and column , each cell once. The sum covers row and column . A cell is in both sets only if it is in row or column and also in row or column . Rows and are disjoint, and so are columns and , so the common cells are and . Hence , and
The cells of that are not of the form with are and, for each , the cells and . So
Subtract the two equations to get the claim.
Claim. If , BROWN-CLUSTERING stops, returns classes, and each merge it makes joins a pair of the current partition such that is the largest over all pairs of classes of . Ties go to the first pair in the order of line L6.
Proof. We use this invariant at the test of line L4.
(I) The class list holds a partition of the vocabulary into classes, and the matrix is the matrix , with rows and columns in the order of the class list.
Initialization. Line L1 makes each word its own class, line L2 counts the word bigrams, which are the class bigrams of the partition into single words, and line L3 sets . So (I) holds.
Maintenance. Assume (I) and . Line L5 computes , , , and from . For each pair , line L7 evaluates the right side of Lemma 1: the terms are computed from the merged counts and the merged marginals, exactly as the lemma defines them. So the value of line L7 is for the partition that merges and . Line L8 keeps the first pair with the largest value, so the chosen pair maximizes over all pairs. Line L9 adds row to row and then column to column . After that, for , for , and is the sum of the four counts of . Then line L9 deletes row and column . The result is with the merged class in place , and the class list is changed in the same way. Line L10 sets , so (I) holds for .
Termination. Each iteration lowers by 1. If the loop does not run and the single classes are returned. Otherwise the loop stops when , after merges, and line L11 returns classes.
Corollary (likelihood). Give the class bigram model the relative frequency parameters and , where is the right marginal of the word in the word bigram matrix. Then the average log likelihood of the bigrams is
where does not depend on .
Proof. For a bigram with , let and . Then
Multiply by and sum over all pairs. The first term depends only on , and the weights with , add up to , so the first term gives . In the second term the weights with a fixed add up to , so it gives .
So among the partitions that one merge can reach, the merge of line L8 gives the class bigram model with the highest likelihood. This is a statement about one step. The greedy sequence of merges need not reach the partition into classes with the highest ; the page gives a corpus of one sentence where it does not.
Complexity
The model is the word-RAM, with the arithmetic on floating point numbers counted as unit cost.
- Counting. Line L2 reads each token once: time and space for the dense matrix.
- One merge with classes. Line L5 costs . Lines L6 to L8 evaluate pairs at each, so . Line L9 costs with a dense matrix stored as lists.
- All merges. From down to the cost is , so the total is for the version on this page.
- Better bookkeeping. Brown et al. keep the table of the losses for all pairs and update it after each merge with their equation 17 in time, which gives in all (page 473). Recomputing from scratch for each pair would cost per pair and in all, the cost they give for the straightforward method.
- Windowed version. With only active classes at a time (see Variants), each step has pairs, so the cost is about with the bookkeeping, plus the counting. This bound is our count, not a figure of the paper.
Properties
- Greedy and deterministic. The result depends on the order of the words through the tie rule, and on nothing random.
- Hard clustering. Each word type gets exactly one class and one bit string. The different senses of an ambiguous word share them.
- Hierarchical. One run to gives the partitions for every number of classes at once, nested in each other.
- Monotone AMI. A merge never increases , because merging classes is a function of the class variables and mutual information cannot grow under such a function (data processing). So the losses are never negative, up to rounding.
- Not optimal. The final partition need not have the largest among the partitions into classes.
Variants and improvements
- Word exchange. After the merges, Brown et al. move single words to the class that gives the largest AMI, one at a time, until no move helps. This is a local search step after the greedy start.
- Windowed clustering. Put the most frequent words in their own classes. At each step, add the next most frequent word as a new class and merge the best pair among the classes. Brown et al. used this to put a vocabulary of 260,741 words into 1000 classes. The implementation of Liang 2005 works this way and is the one most later work uses.
- Bit string features. Koo, Carreras and Collins 2008 and others use prefixes of several lengths of the bit strings, together with the full strings, as features of a parser or a tagger. A short prefix gives a coarse class and a long prefix a fine one.
When to use it
Use Brown clusters when you need cheap word features learned from unlabeled text for a tagger, a named entity recognizer or a parser trained on little labeled data; Turian, Ratinov and Bengio 2010 compared them with word embeddings as features for chunking and named entity recognition and found them competitive, a measurement on their data sets. Use dense embeddings when you need graded similarity or one vector per word for a network. The method models only the next word, so it captures syntactic classes well and topical similarity less well than a word-context matrix with a wide window.
Pitfalls
- Recomputing the AMI for each pair. Computing from scratch in line L7 is correct but costs per pair and in all. Use the merge formula of line L7, and the loss table of Brown et al. for .
- Greedy is not optimal. On the one-sentence corpus "e a d b c a" the first two merges are unique (c with e, then b with d), and the third is a tie whose two choices both give for two classes. The partition {a, b}, {c, d, e} has . Line L8 chooses only the best next merge, and no later step undoes a merge.
- Sentence edges. Line L2 counts pairs inside sentences. A word seen only at the end of sentences has an empty row, and a word seen only at the start has an empty column, so merging such a pair costs nothing, even if the words have nothing in common. On "the cat runs", "the dog runs", "a cat sleeps", "a dog sleeps", "the dog sleeps" the first merge is "sleeps" with "the". Pad the sentences with boundary symbols or join them into one stream when this matters.
- Ties decided by rounding. Two merges with the same exact AMI can differ by after rounding. Compare with a tolerance in line L8, or the order of the floating point sums decides the tie.
- The log base. Nats and bits change all values of by the same factor and do not change any choice. Say which one you print.
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/brown-clustering/. The authors are listed in prov/HG0BRB.jsonl.
"""Brown clustering: greedy merging of word classes.
Each merge joins the two classes whose merge keeps the average mutual
information (AMI) of adjacent classes highest. The bigrams are the adjacent
token pairs inside each sentence, with no padding. Logs are natural, so the
AMI is in nats.
"""
from collections import Counter
from dataclasses import dataclass
from math import log
@dataclass(frozen=True)
class Merge:
"""One merge. left and right are tree nodes, node is the new tree node.
Leaves 0 .. V-1 are the words in the order of vocabulary(). Internal
nodes are numbered V, V+1, ... in the order of the merges. ami is the
AMI of the partition just after the merge, in nats.
"""
left: int
right: int
node: int
ami: float
def vocabulary(corpus: list[list[str]]) -> list[str]:
"""The word types, by decreasing count, ties in string order."""
count = Counter(w for sentence in corpus for w in sentence)
return sorted(count, key=lambda w: (-count[w], w))
def bigram_counts(corpus: list[list[str]], words: list[str]) -> tuple[list[list[int]], int]:
"""The matrix n[l][m] of adjacent pairs (words[l], words[m]) and its total."""
index = {w: i for i, w in enumerate(words)}
n = [[0] * len(words) for _ in words]
total = 0
for sentence in corpus:
for a, b in zip(sentence, sentence[1:]):
n[index[a]][index[b]] += 1
total += 1
return n, total
def _q(c: int, left: int, right: int, total: int) -> float:
"""p log(p / (pl pr)) with p = c / total, pl = left / total, pr = right / total."""
if c == 0:
return 0.0
return c / total * log(c * total / (left * right))
def average_mutual_information(n: list[list[int]], total: int) -> float:
"""AMI of the class bigram matrix n, computed from scratch, in nats."""
k = len(n)
left = [sum(row) for row in n]
right = [sum(n[l][m] for l in range(k)) for m in range(k)]
return sum(_q(n[l][m], left[l], right[m], total) for l in range(k) for m in range(k))
def brown_clustering(
corpus: list[list[str]], num_classes: int = 1
) -> tuple[list[list[str]], list[Merge]]:
"""Merge classes greedily until num_classes classes remain.
Precondition: num_classes >= 1. Returns the classes (each a list of
words, the kept class first) and the merges in order. Ties within 1e-12
go to the first pair (i, j) in the order of the current class indices.
Cost: O(N + V^4) time for V types and N tokens, O(V^2) space.
"""
if num_classes < 1:
raise ValueError("num_classes must be at least 1")
words = vocabulary(corpus)
classes = [[w] for w in words] # @line L1
nodes = list(range(len(words)))
n, total = bigram_counts(corpus, words) # @line L2
merges: list[Merge] = []
k = len(words) # @line L3
while k > num_classes: # @line L4
left = [sum(row) for row in n] # @line L5
right = [sum(n[l][m] for l in range(k)) for m in range(k)]
q = [[_q(n[l][m], left[l], right[m], total) for m in range(k)] for l in range(k)]
s = [sum(q[l][i] for l in range(k)) + sum(q[i]) - q[i][i] for i in range(k)]
ami = sum(map(sum, q))
best = (0.0, -1, -1)
for i in range(k): # @line L6
for j in range(i + 1, k):
li, ri = left[i] + left[j], right[i] + right[j]
v = ami - s[i] - s[j] + q[i][j] + q[j][i] # @line L7
v += _q(n[i][i] + n[i][j] + n[j][i] + n[j][j], li, ri, total)
for l in range(k):
if l != i and l != j:
v += _q(n[l][i] + n[l][j], left[l], ri, total)
v += _q(n[i][l] + n[j][l], li, right[l], total)
if best[1] < 0 or v > best[0] + 1e-12: # @line L8
best = (v, i, j)
v, i, j = best
for m in range(k): # @line L9
n[i][m] += n[j][m]
for l in range(k):
n[l][i] += n[l][j]
del n[j]
for row in n:
del row[j]
classes[i] = classes[i] + classes[j]
del classes[j]
merges.append(Merge(nodes[i], nodes[j], len(words) + len(merges), v)) # @line L10
nodes[i] = merges[-1].node
del nodes[j]
k -= 1
return classes, merges # @line L11
def bit_strings(corpus: list[list[str]]) -> dict[str, str]:
"""The path of each word in the full merge tree: 0 for left, 1 for right.
The left child of a merge is the kept class. A corpus with one type
gives that type the empty string.
"""
words = vocabulary(corpus)
if not words:
return {}
_, merges = brown_clustering(corpus, 1)
children = {m.node: (m.left, m.right) for m in merges}
root = merges[-1].node if merges else 0
codes: dict[str, str] = {}
stack = [(root, "")]
while stack:
node, code = stack.pop()
if node < len(words):
codes[words[node]] = code
else:
a, b = children[node]
stack.append((a, code + "0"))
stack.append((b, code + "1"))
return codes
test_brown_clustering.py 127 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/brown-clustering/. The authors are listed in prov/HG0BRB.jsonl.
import math
import random
from brown_clustering import (
average_mutual_information,
bigram_counts,
bit_strings,
brown_clustering,
vocabulary,
)
EXAMPLE = ["the cat runs and the dog sleeps and a dog runs and the cat sleeps".split()]
def ami_of_partition(corpus: list[list[str]], partition: list[list[str]]) -> float:
"""AMI of a partition, from the word bigrams, with no shared code path."""
cls = {w: c for c, ws in enumerate(partition) for w in ws}
pairs = [(a, b) for s in corpus for a, b in zip(s, s[1:])]
total = len(pairs)
joint: dict[tuple[int, int], int] = {}
left: dict[int, int] = {}
right: dict[int, int] = {}
for a, b in pairs:
key = (cls[a], cls[b])
joint[key] = joint.get(key, 0) + 1
left[key[0]] = left.get(key[0], 0) + 1
right[key[1]] = right.get(key[1], 0) + 1
return sum(c / total * math.log(c * total / (left[l] * right[m])) for (l, m), c in joint.items())
def all_partitions(items: list[str], k: int):
if not items:
if k == 0:
yield []
return
first, rest = items[0], items[1:]
if k > 0:
for p in all_partitions(rest, k - 1):
yield [[first]] + p
for p in all_partitions(rest, k):
for i in range(len(p)):
yield p[:i] + [[first] + p[i]] + p[i + 1:]
def check_greedy(corpus: list[list[str]]) -> None:
"""At every step the chosen merge must reach the best AMI over all pairs."""
words = vocabulary(corpus)
final, merges = brown_clustering(corpus, 1)
assert len(merges) == max(len(words) - 1, 0)
for step, merge in enumerate(merges):
before, _ = brown_clustering(corpus, len(words) - step)
after, _ = brown_clustering(corpus, len(words) - step - 1)
best = max(
ami_of_partition(corpus, [c for t, c in enumerate(before) if t not in (i, j)] + [before[i] + before[j]])
for i in range(len(before))
for j in range(i + 1, len(before))
)
got = ami_of_partition(corpus, after)
assert abs(got - merge.ami) < 1e-9
assert got > best - 1e-9
def test_example_trace() -> None:
words = vocabulary(EXAMPLE)
assert words == ["and", "the", "cat", "dog", "runs", "sleeps", "a"]
n, total = bigram_counts(EXAMPLE, words)
assert total == 14
assert abs(average_mutual_information(n, total) - 1.4377014436) < 1e-9
classes, merges = brown_clustering(EXAMPLE, 3)
assert classes == [["and", "the", "a"], ["cat", "dog"], ["runs", "sleeps"]]
assert [round(m.ami, 4) for m in merges] == [1.4377, 1.3761, 1.3761, 0.7375]
assert [(m.left, m.right, m.node) for m in merges] == [(4, 5, 7), (1, 6, 8), (2, 3, 9), (0, 8, 10)]
_, full = brown_clustering(EXAMPLE, 1)
assert [round(m.ami, 4) for m in full[4:]] == [0.1175, 0.0]
assert bit_strings(EXAMPLE) == {
"and": "000", "the": "0010", "a": "0011", "runs": "010", "sleeps": "011", "cat": "10", "dog": "11",
}
def test_greedy_choice_against_all_pairs() -> None:
check_greedy(EXAMPLE)
rng = random.Random(7)
for _ in range(500):
vocab = "abcdefg"[: rng.randrange(1, 8)]
corpus = [[rng.choice(vocab) for _ in range(rng.randrange(1, 9))] for _ in range(rng.randrange(1, 3))]
check_greedy(corpus)
def test_greedy_is_not_optimal() -> None:
corpus = ["e a d b c a".split()]
greedy, _ = brown_clustering(corpus, 2)
best = max(all_partitions(vocabulary(corpus), 2), key=lambda p: ami_of_partition(corpus, p))
assert abs(ami_of_partition(corpus, greedy) - 0.1185) < 1e-4
assert abs(ami_of_partition(corpus, best) - 0.6730) < 1e-4
assert sorted(sorted(c) for c in best) == [["a", "b"], ["c", "d", "e"]]
def test_edges() -> None:
assert brown_clustering([], 1) == ([], [])
assert bit_strings([]) == {}
assert bit_strings([["x", "x"]]) == {"x": ""}
classes, merges = brown_clustering([["a", "b"]], 5)
assert classes == [["a"], ["b"]] and merges == []
classes, merges = brown_clustering([["a"], ["b"], ["c"]], 1)
assert sorted(classes[0]) == ["a", "b", "c"]
assert all(m.ami == 0.0 for m in merges)
try:
brown_clustering(EXAMPLE, 0)
except ValueError:
pass
else:
raise AssertionError("num_classes = 0 must fail")
def test_bit_strings_form_a_prefix_code() -> None:
rng = random.Random(3)
for _ in range(100):
vocab = "abcdefgh"[: rng.randrange(2, 9)]
corpus = [[rng.choice(vocab) for _ in range(rng.randrange(2, 10))] for _ in range(2)]
codes = list(bit_strings(corpus).values())
assert len(codes) == len(vocabulary(corpus))
for x in codes:
for y in codes:
assert x == y or not y.startswith(x)
History
Brown, deSouza, Mercer, Della Pietra and Lai built class-based n-gram models at IBM, published in Computational Linguistics in 1992. They derived the link between the likelihood of the class bigram model and the AMI, gave the greedy merge with the bookkeeping that costs order , the word exchange step, the binary tree with a figure for 1000 words, and the windowed version. Liang 2005 wrote the implementation with a window that most later work used. Miller, Guinness and Zamanian 2004 and Koo, Carreras and Collins 2008 used bit string prefixes as features for name tagging and dependency parsing, and Turian, Ratinov and Bengio 2010 compared these features with neural word embeddings.
References
- Brown, deSouza, Mercer, Della Pietra and Lai 1992, Section 3 (Word Classes): equation 9 (the likelihood as minus the entropy plus the average mutual information of adjacent classes), equations 10 to 17 (the merge formula and the bookkeeping that gives order V^3), the word exchange step, the binary tree of Figure 2, and the windowed algorithm used for 1000 classes
- Liang 2005, the description of Brown clustering with a window of C classes and its use as features
- Koo, Carreras and Collins 2008, prefixes of the Brown bit strings as word features of a dependency parser
- Turian, Ratinov and Bengio 2010, Brown clusters compared with word embeddings as features for chunking and named entity recognition
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 HG0BRB Edit this page History Report an error Markdown