Algorithm Search⌘K

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)
Properties
deterministicnot exactgreedyofflineiterative
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 C≥1C \ge 1. The bigrams are the adjacent token pairs inside each sentence, with no padding, and n(u,w)n(u, w) counts the pair (u,w)(u, w); let BB be the total number of bigrams. A partition π\pi of the VV word types into classes gives class counts n(l,m)n(l, m), the probabilities p(l,m)=n(l,m)/Bp(l, m) = n(l, m) / B, and the marginals pL(l)=∑mp(l,m)p_L(l) = \sum_m p(l, m) and pR(m)=∑lp(l,m)p_R(m) = \sum_l p(l, m). The average mutual information (AMI) of π\pi is

I(π)=∑l,mp(l,m)log⁡p(l,m)pL(l) pR(m)(log⁡=ln⁡, nats),I(\pi) = \sum_{l, m} p(l, m) \log \frac{p(l, m)}{p_L(l)\, p_R(m)} \quad (\log = \ln,\ \text{nats}),

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 pp from pL×pRp_L \times p_R. Brown et al. (equation 9) show that the log likelihood per bigram of the class bigram model P(w∣u)=P(c(w)∣c(u))P(w∣c(w))P(w \mid u) = P(c(w) \mid c(u)) P(w \mid c(w)), with relative frequency parameters, is I(π)I(\pi) minus an entropy that does not depend on π\pi. So the best partition into CC classes is the one with the largest II. Brown et al. give no exact method for it, and Brown clustering is a greedy heuristic for it.

The algorithm

Write q(l,m)=p(l,m)log⁡p(l,m)pL(l)pR(m)q(l, m) = p(l, m) \log \frac{p(l, m)}{p_L(l) p_R(m)}, with q=0q = 0 when p(l,m)=0p(l, m) = 0, and s(i)=∑lq(l,i)+∑mq(i,m)−q(i,i)s(i) = \sum_l q(l, i) + \sum_m q(i, m) - q(i, i), the part of II in row ii and column ii. For a merge of ii and jj, write i+ji{+}j for the merged class, and q(⋅,i+j)q(\cdot, i{+}j) for the value computed from the summed counts and the summed marginals.

  1. BROWN-CLUSTERING(corpus, C)
  2. 1V ← word types by decreasing count; class i ← {V[i]}
  3. 2n(l, m) ← count of the adjacent pairs of classes (l, m) in each sentence
  4. 3k ← |V|
  5. 4while k > C do
  6. 5compute p_L, p_R, q(l, m), s(l) and I ← sum of all q(l, m)
  7. 6for each pair i < j of current classes do
  8. 7I(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)]
  9. 8(i, j) ← the pair with the largest I(i, j), the first pair on ties
  10. 9add row j to row i and column j to column i; delete row and column j
  11. 10record the merge (i, j); k ← k - 1
  12. 11return the k classes and the merges

Line L7 is equation 15 of Brown et al. It gives the AMI after the merge in O(k)O(k) time, because the merge changes only the cells in rows and columns ii and jj. Line L9 keeps the merged class at position ii. The code breaks ties within 10−1210^{-12} in favor of the first pair, so that rounding does not decide them.

The tree and the bit strings. Run the loop with C=1C = 1. Each merge makes a tree node with the kept class ii as left child and the removed class jj 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 CC merges gives the partition into C+1C + 1 classes, and a prefix of length bb of the bit strings groups the words into at most 2b2^b 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 V=7V = 7 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 II. 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 C=3C = 3 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 min⁡(C,V)\min(C, V) classes. The key step is the merge formula of line L7: a merge leaves every cell outside rows and columns ii and jj unchanged, together with its marginals, and the cells inside are counted by s(i)+s(j)−q(i,j)−q(j,i)s(i) + s(j) - q(i, j) - q(j, i). The invariant of the loop is that the matrix nn 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 VV word types. The bigrams are the adjacent token pairs inside each sentence, n(u,w)n(u, w) is the number of times the pair (u,w)(u, w) occurs, and B=∑u,wn(u,w)B = \sum_{u, w} n(u, w). All logs are natural.

Notation. A partition π\pi of the vocabulary into classes gives the class counts nπ(l,m)=∑u∈l∑w∈mn(u,w)n_\pi(l, m) = \sum_{u \in l} \sum_{w \in m} n(u, w). Let p(l,m)=nπ(l,m)/Bp(l, m) = n_\pi(l, m) / B, pL(l)=∑mp(l,m)p_L(l) = \sum_m p(l, m) and pR(m)=∑lp(l,m)p_R(m) = \sum_l p(l, m). Let

q(l,m)=p(l,m)log⁡p(l,m)pL(l) pR(m)(log⁡=ln⁡),q(l, m) = p(l, m) \log \frac{p(l, m)}{p_L(l)\, p_R(m)} \quad (\log = \ln),

with q(l,m)=0q(l, m) = 0 when p(l,m)=0p(l, m) = 0. If p(l,m)>0p(l, m) > 0, then pL(l)≥p(l,m)>0p_L(l) \ge p(l, m) > 0 and pR(m)>0p_R(m) > 0, so qq is well defined. The average mutual information of π\pi is I(π)=∑l,mq(l,m)I(\pi) = \sum_{l, m} q(l, m), and for a class ii let s(i)=∑lq(l,i)+∑mq(i,m)−q(i,i)s(i) = \sum_l q(l, i) + \sum_m q(i, m) - q(i, i), the sum of qq over row ii and column ii, with the cell (i,i)(i, i) counted once.

Lemma 1 (the merge formula, equation 15 of Brown et al.). Let i≠ji \ne j be two classes of π\pi with kk classes, and let π′\pi' be π\pi with ii and jj replaced by their union i+ji + j. Then

I(π′)=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)],I(\pi') = I(\pi) - s(i) - s(j) + q(i, j) + q(j, i) + q'(i{+}j, i{+}j) + \sum_{l \ne i, j} \big[ q'(l, i{+}j) + q'(i{+}j, l) \big],

where q′q' is qq computed in π′\pi', that is, from the counts nπ′(l,i+j)=nπ(l,i)+nπ(l,j)n_{\pi'}(l, i{+}j) = n_\pi(l, i) + n_\pi(l, j), nπ′(i+j,m)=nπ(i,m)+nπ(j,m)n_{\pi'}(i{+}j, m) = n_\pi(i, m) + n_\pi(j, m), nπ′(i+j,i+j)n_{\pi'}(i{+}j, i{+}j) the sum of the four counts of {i,j}×{i,j}\{i, j\} \times \{i, j\}, and the marginals pL′(i+j)=pL(i)+pL(j)p_L'(i{+}j) = p_L(i) + p_L(j) and pR′(i+j)=pR(i)+pR(j)p_R'(i{+}j) = p_R(i) + p_R(j).

Proof. Take a cell (l,m)(l, m) with l,m∉{i,j}l, m \notin \{i, j\}. Its count does not change. The row of ll in π′\pi' has the same total as in π\pi, because the merge only adds two cells of that row together, so pL′(l)=pL(l)p_L'(l) = p_L(l). In the same way pR′(m)=pR(m)p_R'(m) = p_R(m). So q′(l,m)=q(l,m)q'(l, m) = q(l, m) for all these cells.

Let RR be the set of cells of π\pi in row ii, row jj, column ii or column jj. The sum s(i)s(i) covers row ii and column ii, each cell once. The sum s(j)s(j) covers row jj and column jj. A cell is in both sets only if it is in row ii or column ii and also in row jj or column jj. Rows ii and jj are disjoint, and so are columns ii and jj, so the common cells are (i,j)(i, j) and (j,i)(j, i). Hence ∑Rq=s(i)+s(j)−q(i,j)−q(j,i)\sum_{R} q = s(i) + s(j) - q(i, j) - q(j, i), and

I(π)=∑l,m∉{i,j}q(l,m)+s(i)+s(j)−q(i,j)−q(j,i).I(\pi) = \sum_{l, m \notin \{i, j\}} q(l, m) + s(i) + s(j) - q(i, j) - q(j, i).

The cells of π′\pi' that are not of the form (l,m)(l, m) with l,m∉{i,j}l, m \notin \{i, j\} are (i+j,i+j)(i{+}j, i{+}j) and, for each l≠i,jl \ne i, j, the cells (l,i+j)(l, i{+}j) and (i+j,l)(i{+}j, l). So

I(π′)=∑l,m∉{i,j}q(l,m)+q′(i+j,i+j)+∑l≠i,j[q′(l,i+j)+q′(i+j,l)].I(\pi') = \sum_{l, m \notin \{i, j\}} q(l, m) + q'(i{+}j, i{+}j) + \sum_{l \ne i, j} \big[ q'(l, i{+}j) + q'(i{+}j, l) \big].

Subtract the two equations to get the claim. □\square

Claim. If 1≤C1 \le C, BROWN-CLUSTERING stops, returns min⁡(C,V)\min(C, V) classes, and each merge it makes joins a pair (i,j)(i, j) of the current partition π\pi such that I(π′)I(\pi') is the largest over all pairs of classes of π\pi. 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 πk\pi_k of the vocabulary into kk classes, and the matrix nn is the k×kk \times k matrix nπkn_{\pi_k}, 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 k=Vk = V. So (I) holds.

Maintenance. Assume (I) and k>Ck > C. Line L5 computes pLp_L, pRp_R, qq, ss and I(πk)I(\pi_k) from n=nπkn = n_{\pi_k}. For each pair i<ji < j, line L7 evaluates the right side of Lemma 1: the terms q′q' are computed from the merged counts and the merged marginals, exactly as the lemma defines them. So the value of line L7 is I(π′)I(\pi') for the partition π′\pi' that merges ii and jj. Line L8 keeps the first pair with the largest value, so the chosen pair maximizes I(π′)I(\pi') over all pairs. Line L9 adds row jj to row ii and then column jj to column ii. After that, n(i,m)=nπk(i,m)+nπk(j,m)n(i, m) = n_{\pi_k}(i, m) + n_{\pi_k}(j, m) for m≠i,jm \ne i, j, n(l,i)=nπk(l,i)+nπk(l,j)n(l, i) = n_{\pi_k}(l, i) + n_{\pi_k}(l, j) for l≠i,jl \ne i, j, and n(i,i)n(i, i) is the sum of the four counts of {i,j}×{i,j}\{i, j\} \times \{i, j\}. Then line L9 deletes row and column jj. The result is nπ′n_{\pi'} with the merged class in place ii, and the class list is changed in the same way. Line L10 sets k←k−1k \leftarrow k - 1, so (I) holds for πk−1=π′\pi_{k-1} = \pi'.

Termination. Each iteration lowers kk by 1. If V≤CV \le C the loop does not run and the VV single classes are returned. Otherwise the loop stops when k=Ck = C, after V−CV - C merges, and line L11 returns CC classes. □\square

Corollary (likelihood). Give the class bigram model P(w∣u)=P(c(w)∣c(u)) P(w∣c(w))P(w \mid u) = P(c(w) \mid c(u))\, P(w \mid c(w)) the relative frequency parameters P(m∣l)=p(l,m)/pL(l)P(m \mid l) = p(l, m) / p_L(l) and P(w∣m)=pR(w)/pR(m)P(w \mid m) = p_R(w) / p_R(m), where pR(w)p_R(w) is the right marginal of the word ww in the word bigram matrix. Then the average log likelihood of the bigrams is

1B∑u,wn(u,w)log⁡P(w∣u)=I(π)−HR(log⁡=ln⁡),\frac{1}{B} \sum_{u, w} n(u, w) \log P(w \mid u) = I(\pi) - H_R \quad (\log = \ln),

where HR=−∑wpR(w)log⁡pR(w)H_R = -\sum_w p_R(w) \log p_R(w) does not depend on π\pi.

Proof. For a bigram (u,w)(u, w) with n(u,w)>0n(u, w) > 0, let l=c(u)l = c(u) and m=c(w)m = c(w). Then

log⁡P(w∣u)=log⁡p(l,m)pL(l)+log⁡pR(w)pR(m)=log⁡p(l,m)pL(l) pR(m)+log⁡pR(w).\log P(w \mid u) = \log \frac{p(l, m)}{p_L(l)} + \log \frac{p_R(w)}{p_R(m)} = \log \frac{p(l, m)}{p_L(l)\, p_R(m)} + \log p_R(w).

Multiply by n(u,w)/Bn(u, w) / B and sum over all pairs. The first term depends only on (l,m)(l, m), and the weights n(u,w)/Bn(u, w) / B with u∈lu \in l, w∈mw \in m add up to p(l,m)p(l, m), so the first term gives I(π)I(\pi). In the second term the weights n(u,w)/Bn(u, w) / B with a fixed ww add up to pR(w)p_R(w), so it gives ∑wpR(w)log⁡pR(w)=−HR\sum_w p_R(w) \log p_R(w) = -H_R. □\square

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 CC classes with the highest II; the page gives a corpus of one sentence where it does not. ■\blacksquare

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: O(N)O(N) time and Θ(V2)\Theta(V^2) space for the dense matrix.
  • One merge with kk classes. Line L5 costs O(k2)O(k^2). Lines L6 to L8 evaluate k(k−1)/2k(k-1)/2 pairs at O(k)O(k) each, so O(k3)O(k^3). Line L9 costs O(k2)O(k^2) with a dense matrix stored as lists.
  • All merges. From k=Vk = V down to C+1C + 1 the cost is ∑kO(k3)=O(V4)\sum_k O(k^3) = O(V^4), so the total is O(N+V4)O(N + V^4) for the version on this page.
  • Better bookkeeping. Brown et al. keep the table of the losses I−I(i,j)I - I(i, j) for all pairs and update it after each merge with their equation 17 in O(k2)O(k^2) time, which gives O(V3)O(V^3) in all (page 473). Recomputing II from scratch for each pair would cost O(k2)O(k^2) per pair and O(V5)O(V^5) in all, the cost they give for the straightforward method.
  • Windowed version. With only C+1C + 1 active classes at a time (see Variants), each step has O(C2)O(C^2) pairs, so the cost is about O(VC2)O(V C^2) 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 C=1C = 1 gives the partitions for every number of classes at once, nested in each other.
  • Monotone AMI. A merge never increases II, 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 II among the partitions into CC classes.

Variants and improvements

  • Word exchange. After the V−CV - C 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 CC 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 C+1C + 1 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 I(π′)I(\pi') from scratch in line L7 is correct but costs O(k2)O(k^2) per pair and O(V5)O(V^5) in all. Use the merge formula of line L7, and the loss table of Brown et al. for O(V3)O(V^3).
  • 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 I=0.1185I = 0.1185 for two classes. The partition {a, b}, {c, d, e} has I=0.6730I = 0.6730. 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 10−1610^{-16} 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 II 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.

brown_clustering.pyI0RawGitHub
# 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 V3V^3, 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

  1. 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
  2. Liang 2005, the description of Brown clustering with a window of C classes and its use as features
  3. Koo, Carreras and Collins 2008, prefixes of the Brown bit strings as word features of a dependency parser
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example