Latent Dirichlet allocation (Blei, Ng, and Jordan, 2003) models each document as a mixture of $K$ topics whose proportions are drawn from a shared $\mathrm{Dirichlet}(\alpha)$, so every document, seen or unseen, has a probability. Conjugacy integrates out the topics and proportions, and collapsed Gibbs sampling resamples each word's topic with probability proportional to $(n_{d,k}^{-i} + \alpha)(n_{k,w_i}^{-i} + \beta)/(n_k^{-i} + V\beta)$. Since every weight is positive, the chain converges to the posterior from any start. On six toy documents ($K = 2$, $\alpha = 0.1$, $\beta = 0.05$), 30 runs spent a median 0.250 of their sweeps at the sea/travel split, against the exact posterior's 0.247. On 7,769 Reuters training stories, twenty topics fitted by variational inference were mostly recognizable, and one was incoherent.
The best fit of pLSA to the six documents gave $d_2$ (boat ocean) no chance of ever containing trip, and it had no probability at all for a new document. Both faults come from one gap: pLSA never says where a document's mixture of topics comes from. What changes when the model does say?
Both faults go away. Latent Dirichlet allocation (LDA), introduced by Blei, Ng, and Jordan (2003), is that model and the most widely used topic model. It keeps pLSA's picture, topics as distributions over words and documents as mixtures of topics, and adds the missing piece: each document's mixture is drawn from one distribution shared by the whole collection. That makes LDA a complete generative model of documents, with a fixed number of parameters however large the collection, and a probability for any document, including ones it has never seen.
First we state the model as a recipe and a diagram, and meet the Dirichlet distribution it is named for. Next we derive the collapsed Gibbs sampler, prove that it reaches the posterior, trace it on the six documents, and check it against the exact posterior. The other standard method, variational inference, is named here and derived in variational inference for LDA. Finally we fit twenty topics to Reuters and solve one problem by hand. The article assumes pLSA and its expectation-maximization algorithm.
The generative story
LDA imagines that a collection was produced by a random process. With $K$ topics and a vocabulary of $V$ words (the pLSA article calls the vocabulary size $M$):
- For each topic $k$, draw a distribution over words $\phi_k \sim \mathrm{Dirichlet}(\beta)$.
- For each document $d$:
- Draw its topic proportions $\theta_d \sim \mathrm{Dirichlet}(\alpha)$.
- For each word position $i$ in the document:
- Draw a topic $z_{d,i}$ from the proportions $\theta_d$.
- Draw the word $w_{d,i}$ from that topic's distribution $\phi_{z_{d,i}}$.
No one believes documents are written this way. Word order is ignored, and topics do not choose words independently. The story is a device: if documents had been produced like this, the topics and proportions that best explain the observed words are the ones worth finding. Only the words $w$ are observed. The topics $\phi$, the proportions $\theta$, and the assignments $z$ are all latent, and fitting LDA means inferring them.
The difference from pLSA is step 2.1. In pLSA, each document's proportions are free parameters. In LDA they are random variables, drawn from one shared distribution controlled by a single parameter $\alpha$. The model's parameters are just $\alpha$ and $\beta$. Every document, seen or unseen, gets a probability by averaging over the proportions it might have had.
A note on notation. The symbols follow the smoothed version of the model (Blei, Ng, and Jordan, 2003, §5.4) and Griffiths and Steyvers (2004). In Blei, Ng, and Jordan's paper, $\beta$ names the topic-word matrix itself, and in the smoothed version the prior on it is $\eta$, as in scikit-learn.
Example (counting LDA's parameters). LDA has two parameters for the six documents, $\alpha$ and $\beta$, and it would have the same two for six thousand documents, since the topics and mixtures are now latent variables rather than parameters. pLSA with two topics had 14 parameters for the six documents, six of them the documents' own mixture weights. Blei, Ng, and Jordan's original form treats the topics as parameters and counts $K + KV$ (2003, §4.3), still independent of the number of documents.
Plate notation
The same story is usually drawn as a graphical model:
- circles are random variables;
- arrows point from a variable to the ones drawn from it;
- a rectangle, a plate, means "repeat what is inside" the number of times written in its corner.
Multiplying one factor per circle, each conditioned on its parents, gives the joint probability of everything in the picture:
$$p(\phi, \theta, z, w \mid \alpha, \beta) = \prod_{k=1}^{K} p(\phi_k \mid \beta) \prod_{d=1}^{D} \left( p(\theta_d \mid \alpha) \prod_{i=1}^{N_d} \theta_{d, z_{d,i}}\, \phi_{z_{d,i}, w_{d,i}} \right).$$
Everything in inference starts from this product. pLSA's diagram would have no $\alpha$ node, and $\theta_d$ would be a fixed parameter rather than a circle. Two of the factors, $p(\theta_d \mid \alpha)$ and $p(\phi_k \mid \beta)$, are Dirichlet densities. The next section says what a Dirichlet looks like.
The Dirichlet distribution
Topic proportions and topics are both probability vectors, lists of nonnegative numbers summing to 1. The Dirichlet distribution is a distribution over such vectors. In the symmetric form used here, with $K$ components and concentration parameter $\alpha$, its density is
$$p(\theta \mid \alpha) = \frac{\Gamma(K\alpha)}{\Gamma(\alpha)^K} \prod_{k=1}^{K} \theta_k^{\alpha - 1}.$$
The fraction in front only makes the density integrate to 1. The shape comes from the product. Each $\theta_k^{\alpha - 1}$ is large near $\theta_k = 0$ when $\alpha < 1$ (a negative power), flat when $\alpha = 1$, and small near 0 when $\alpha > 1$. In the general, asymmetric form each component has its own $\alpha_k$. The fraction becomes $\Gamma(\sum_k \alpha_k) / \prod_k \Gamma(\alpha_k)$, and component $k$ has mean $\alpha_k / \sum_j \alpha_j$.
With three components the vectors are points in a triangle, and the effect of $\alpha$ can be seen:
Example (the mean is not a typical draw). Every component of a symmetric Dirichlet has the same expected value, $1/K$. With $K = 20$ topics and $\alpha = 0.05$, that is $0.05$. Yet in a typical draw the largest share is much larger, about 0.65. The mean says nothing about how far a typical draw strays from it, and that is what $\alpha$ controls. Averaged over draws, the largest component is:
| $\alpha$, with $K = 20$ | Average size of the largest component |
|---|---|
| 0.05 | 0.65 |
| 0.5 | 0.25 |
| 1 | 0.18 |
| 10 | 0.08 |
With $\alpha$ below 1, draws are sparse, concentrated on a few components. With $\alpha = 0.05$, a typical document puts about two-thirds of its weight on one topic. With $\alpha$ well above 1, draws are close to uniform, and every document is a little of everything. Small values suit text, since most documents are about a few things.
Settings in practice vary. Griffiths and Steyvers (2004) used $\alpha = 50/K$ with $\beta = 0.1$. That $\alpha$ is above 1 for fewer than 50 topics, and so favors broader mixtures. scikit-learn's defaults are $1/K$ for both. A small $\beta$ makes each topic concentrate on a modest set of words. (The table's values come from 10,000 draws for each setting; dirichlet_demo.py in tools/experiments/topics/. The figure's 600 draws per panel are drawn by tools/figures/latent-dirichlet-allocation.py.)
The prior says what mixtures to expect before any words are seen. The next subsection combines it with the words once they are.
Conjugacy and pseudo-counts
The Dirichlet is also the conjugate prior of the multinomial. After observing counts, the posterior is again Dirichlet, with the counts added to the parameters. The reason is visible in the formulas. If a document's topic assignments include $n_k$ words from topic $k$, their probability given $\theta$ is $\prod_k \theta_k^{n_k}$. Multiplying by the prior $\prod_k \theta_k^{\alpha - 1}$ gives $\prod_k \theta_k^{n_k + \alpha - 1}$, which is the shape of a Dirichlet with parameters $n_k + \alpha$. For example, take a two-topic document with prior $\alpha = 0.1$, two words assigned to topic 1 and one to topic 2. Its posterior is $\mathrm{Dirichlet}(2.1, 1.1)$, whose mean is $(2.1/3.2,\ 1.1/3.2) = (0.656, 0.344)$. The raw proportions are $(0.667, 0.333)$, so the prior pulls them slightly toward even. Priors, Posteriors and Conjugate Families (Theorem 8) derives the variances and covariances of a Dirichlet and the probability it gives to further words.
That property is what makes the inference below tractable. It also gives $\alpha$ and $\beta$ an interpretation as pseudo-counts: imaginary observations added to every topic in every document and to every word in every topic. It is the same idea as the add-one smoothing of Naive Bayes. The normalizing constant of the Dirichlet will be needed below. Write
$$B(a_1, \dots, a_K) = \frac{\prod_k \Gamma(a_k)}{\Gamma\!\left(\sum_k a_k\right)},$$
so that the density is $\prod_k \theta_k^{a_k - 1} / B(a)$, and therefore $\int \prod_k \theta_k^{a_k - 1}\, d\theta = B(a)$ over the simplex. Collapsed Gibbs sampling, below, rests on that integral, so it is proved here. Variational inference rests on a consequence of it, the expected logarithm of $\theta_k$, which is derived in variational inference for LDA.
Why the integral is $B(a)$. Here is the idea: a product of $K$ gamma integrals can be read as one integral over a total $s$ and proportions $\theta$, and the part over the proportions is the integral we want. By definition, $\Gamma(a) = \int_0^\infty x^{a-1} e^{-x}\, dx$ for $a > 0$. Multiplying $K$ of these,
$$\prod_{k=1}^{K} \Gamma(a_k) = \int_{x_1 > 0} \!\!\cdots\! \int_{x_K > 0} \ \prod_{k} x_k^{a_k - 1}\ e^{-(x_1 + \dots + x_K)}\ dx_1 \cdots dx_K.$$
Change variables to the total $s = x_1 + \dots + x_K$ and the proportions $\theta_k = x_k / s$. The free variables are $s > 0$ and $\theta_1, \dots, \theta_{K-1}$, with $\theta_K = 1 - \theta_1 - \dots - \theta_{K-1}$, and $x_k = s\theta_k$. The matrix of partial derivatives of $(x_1, \dots, x_K)$ with respect to $(\theta_1, \dots, \theta_{K-1}, s)$ has, in row $k < K$, the entry $s$ in column $k$ and $\theta_k$ in the last column. Row $K$ has $-s$ in each of the first $K - 1$ columns and $\theta_K$ in the last. Adding rows 1 to $K - 1$ to row $K$ leaves the determinant unchanged and turns row $K$ into $(0, \dots, 0, 1)$, since the $\theta_k$ sum to 1. The matrix is then upper triangular with diagonal $(s, \dots, s, 1)$, so the determinant is $s^{K-1}$. The integral becomes
$$\prod_{k} \Gamma(a_k) = \int_0^\infty \!\! \int_{\text{simplex}} \prod_k (s\theta_k)^{a_k - 1}\ e^{-s}\ s^{K-1}\ d\theta\, ds = \int_0^\infty s^{\,\sum_k a_k - 1} e^{-s}\, ds \ \cdot \int_{\text{simplex}} \prod_k \theta_k^{a_k - 1}\, d\theta.$$
The powers of $s$ are $\sum_k (a_k - 1) + (K - 1) = \sum_k a_k - 1$, so the first factor is $\Gamma(\sum_k a_k)$. Dividing by it gives the claim. The script confirms it by numerical integration for $K = 2$ and $K = 3$.
The integral also gives the mean quoted above. Write $e_k$ for the vector with 1 in place $k$ and 0 elsewhere. Then $\mathrm{E}[\theta_k] = \int \theta_k \prod_j \theta_j^{a_j - 1}\, d\theta / B(a) = B(a + e_k) / B(a)$. Since $\Gamma(x + 1) = x\,\Gamma(x)$, raising $a_k$ by 1 multiplies the numerator of $B$ by $a_k$ and its denominator by $\sum_j a_j$, so $\mathrm{E}[\theta_k] = a_k / \sum_j a_j$.
Inference
Given the documents, the goal is the posterior distribution of the latent variables, $p(\theta, \phi, z \mid w)$. Its normalizing constant sums over every possible assignment of topics to every word in the collection. With $n$ word occurrences there are $K^n$ assignments, too many to sum. For the 450,424 word occurrences of the Reuters training set below with $K = 20$, that is $20^{450{,}424}$ assignments. The sum does not split into one small sum per word, because the words are coupled. Once $\theta$ and $\phi$ are integrated out, the probability of an assignment depends on counts that the words share: every word of a document enters that document's topic counts, and every occurrence of a word enters its topic's word counts, as the collapsed joint probability below shows. Two families of approximation are standard: sampling (Markov chain Monte Carlo), and optimizing a simpler distribution (variational inference).
Collapsed Gibbs sampling
Here is the idea in plain words. If the topic of every other word were known, guessing the topic of one word would be easy: favor topics that are common in its document and that often produce this word. Gibbs sampling makes that guess for each word in turn, at random in proportion to those odds, and repeats.
Griffiths and Steyvers (2004) observed that $\theta$ and $\phi$ can be integrated out, thanks to conjugacy, leaving only the topic assignments $z$. Gibbs sampling then visits each word occurrence in turn and resamples its topic from its conditional distribution given all the other assignments:
$$P(z_i = k \mid z_{-i}, w) \propto \left(n_{d,k}^{-i} + \alpha\right) \frac{n_{k,w_i}^{-i} + \beta}{n_{k}^{-i} + V\beta}.$$
All three counts exclude the current word:
- $n_{d,k}^{-i}$ is the number of other words in document $d$ assigned to topic $k$;
- $n_{k,w_i}^{-i}$ is the number of times word $w_i$ is assigned to topic $k$ across the collection;
- $n_k^{-i}$ is the total number of words assigned to topic $k$.
The two factors are the two halves of the plain-words guess. Each sweep through the collection costs time proportional to the number of word occurrences times $K$. After many sweeps, the state of the sampler is distributed approximately as the posterior over assignments, which is proved below after the formula is derived. Estimates of the topics and proportions follow from the counts:
$$\hat{\phi}_{k,w} = \frac{n_{k,w} + \beta}{n_k + V\beta}, \qquad \hat{\theta}_{d,k} = \frac{n_{d,k} + \alpha}{n_d + K\alpha}.$$
These are the posterior means of the conjugacy section, with the counts of one sample plugged in. The sampler is short to implement and widely used, as in the MALLET toolkit (McCallum, 2002).
Deriving the update
Here is the plan of the derivation. Conjugacy lets us integrate $\theta$ and $\phi$ out exactly, leaving a joint probability of words and assignments that depends only on counts. The conditional for one word is then a ratio of two such joints, in which almost everything cancels.
The formal version. The sampling formula follows from the joint probability in five steps.
- Integrate out $\theta_d$. In the joint probability, document $d$ contributes $p(\theta_d \mid \alpha) \prod_i \theta_{d, z_{d,i}} = \frac{1}{B(\alpha)} \prod_k \theta_{d,k}^{\alpha - 1} \prod_k \theta_{d,k}^{n_{d,k}}$, where $n_{d,k}$ counts the words of $d$ assigned to topic $k$. Integrating over the simplex with the identity above gives $B(n_{d,\cdot} + \alpha) / B(\alpha)$, a function of the counts alone.
- Integrate out $\phi_k$. In the joint probability, topic $k$ contributes its prior density $\prod_w \phi_{k,w}^{\beta - 1} / B(\beta)$ and one factor $\phi_{k,w}$ for every occurrence of word $w$ assigned to it, $n_{k,w}$ of them. The product is $\prod_w \phi_{k,w}^{\beta - 1 + n_{k,w}} / B(\beta)$. Integrating over the simplex with the same identity gives $B(n_{k,\cdot} + \beta) / B(\beta)$.
- Write the collapsed joint. Multiplying the pieces, $$p(w, z \mid \alpha, \beta) = \prod_{d} \frac{B(n_{d,\cdot} + \alpha)}{B(\alpha)} \prod_{k} \frac{B(n_{k,\cdot} + \beta)}{B(\beta)}.$$ Griffiths and Steyvers (2004, eqs. 2 and 3) give the two factors separately. Everything now depends on $z$ only through the counts.
- Take the ratio. By the definition of conditional probability, $P(z_i = k \mid z_{-i}, w) = p(w, z_{-i}, z_i = k) / \sum_{k'} p(w, z_{-i}, z_i = k')$. The denominator is the same for every $k$, so the conditional is proportional to the joint with word $i$ assigned to $k$. Divide that joint by the collapsed joint of the collection with word $i$ removed, a quantity that does not depend on $k$ either. In the quotient every factor cancels except two: document $d$'s, where $n_{d,k}$ grows by 1, and topic $k$'s, where $n_{k,w_i}$ and $n_k$ grow by 1. Adding 1 to one argument $a_j$ of $B$ multiplies it by $a_j$ and divides it by the sum of all the arguments, because $\Gamma(x + 1) = x\, \Gamma(x)$: $$\frac{B(a + e_j)}{B(a)} = \frac{\Gamma(a_j + 1)}{\Gamma(a_j)} \cdot \frac{\Gamma\!\left(\sum_l a_l\right)}{\Gamma\!\left(\sum_l a_l + 1\right)} = \frac{a_j}{\sum_l a_l},$$ where $e_j$ adds 1 to component $j$ only. Applied to the two factors that change, $$\frac{B(n_{d,\cdot}^{-i} + \alpha + e_k)}{B(n_{d,\cdot}^{-i} + \alpha)} = \frac{n_{d,k}^{-i} + \alpha}{n_d^{-i} + K\alpha}, \qquad \frac{B(n_{k,\cdot}^{-i} + \beta + e_{w_i})}{B(n_{k,\cdot}^{-i} + \beta)} = \frac{n_{k,w_i}^{-i} + \beta}{n_k^{-i} + V\beta}.$$ The conditional is proportional to the product of these two ratios.
- Drop what does not depend on $k$. The denominator $n_d^{-i} + K\alpha$ is the same for every topic, so it disappears into the proportionality, leaving the update above. Griffiths and Steyvers (2004, eq. 5) write the same conditional with that denominator kept. Dividing the $K$ weights by their sum gives probabilities that add to 1.
The product of the two ratios in step 4 has a reading of its own. The first is the probability that the next word of document $d$ gets topic $k$, given the other assignments, and the second is the probability that a word drawn from topic $k$ is $w_i$. Both are posterior means of the conjugacy section. Summed over the $K$ topics and over all $V$ words that word $i$ could have been, the products add to exactly 1.
The script lda_gibbs_toy.py checks the result three ways. For every word of the example below, the formula's probabilities and those computed from ratios of the full collapsed joint agree to within $10^{-15}$. For 200 random pairs of a state and a word, the formula equals the conditional computed by brute force from the exact posterior over all 1,024 assignments, which is described below. And the sum over topics and words is 1 in each of those 200 cases.
Why the sampler reaches the posterior
Here is the idea. Resampling one word from its exact conditional cannot disturb the posterior: if the state was a draw from the posterior before the update, it is one after. And the pseudo-counts let every state reach every other. A chain with those two properties settles into the posterior from any start.
- One update leaves the posterior unchanged. Write $\pi(z) = P(z \mid w)$ for the posterior over assignments. Suppose the current state $z$ is distributed as $\pi$. The update of word $i$ keeps $z_{-i}$ and draws a new value $z_i'$ with probability $\pi(z_i' \mid z_{-i})$. The probability that the new state is $(z_{-i}, z_i')$ is therefore $$\sum_{z_i} \pi(z_{-i}, z_i)\, \pi(z_i' \mid z_{-i}) = \pi(z_{-i})\, \pi(z_i' \mid z_{-i}) = \pi(z_{-i}, z_i'),$$ so the new state is distributed as $\pi$ too. A sweep is one such update for each word in turn, and each leaves $\pi$ unchanged, so a whole sweep does. In the language of PageRank, $\pi$ is a stationary distribution of the Markov chain whose step is one sweep.
- Every state can reach every other in one sweep. Since $\alpha > 0$ and $\beta > 0$, every weight in the update formula is positive, so each word can receive any topic at its turn. The sweep in which every word receives the topic it has in a chosen target state therefore has positive probability, from any starting state. Every entry of the sweep's transition matrix is positive.
- Such a chain converges. Let $P$ be the sweep's transition matrix, with $S$ states, and let $\varepsilon > 0$ be its smallest entry, so that $S\varepsilon \le 1$. If $S\varepsilon = 1$, every entry of $P$ is $1/S$, one sweep reaches the uniform distribution from any start, and by step 1 that distribution is $\pi$. Otherwise put $Q = (P - \varepsilon \mathbf{1}\mathbf{1}^{\mathsf{T}}) / (1 - S\varepsilon)$, where $\mathbf{1}$ is the column of ones. Its entries are nonnegative and its rows sum to 1, so it is a stochastic matrix, and $P = S\varepsilon\, \mathbf{1}u^{\mathsf{T}} + (1 - S\varepsilon)\, Q$ with $u$ the uniform distribution. Take any starting distribution $p$, as a row vector. The entries of $p - \pi$ sum to 0, so $(p - \pi)\mathbf{1} = 0$ and the first term contributes nothing to $(p - \pi)P$. Multiplying a row vector $x$ by a stochastic matrix cannot increase the sum of the absolute values of its entries, $\|x\|_1$, since $\sum_j \lvert \sum_i x_i Q_{ij} \rvert \le \sum_i \lvert x_i \rvert \sum_j Q_{ij} = \|x\|_1$. Since $\pi P = \pi$, $$\|pP - \pi\|_1 = \|(p - \pi)P\|_1 = (1 - S\varepsilon)\, \|(p - \pi)Q\|_1 \le (1 - S\varepsilon)\, \|p - \pi\|_1,$$ and after $n$ sweeps $\|pP^n - \pi\|_1 \le (1 - S\varepsilon)^n \|p - \pi\|_1 \le 2(1 - S\varepsilon)^n$, which tends to 0. So from any start the distribution of the state approaches $\pi$, and $\pi$ is the only stationary distribution, since any other would have to approach $\pi$ while staying fixed. This is the argument PageRank uses for teleportation, applied to any stochastic matrix with positive entries. That the fraction of time spent in each state also approaches $\pi$ is Theorem 21.1 of Manning, Raghavan, and Schütze (2008, §21.2.1), which this article cites and does not prove (Markov Chains and Stationary Distributions proves it as the ergodic theorem, its Theorem 7); §21.2.2 there states the independence from the start.
So after many sweeps the state is approximately a draw from the posterior, and averages over sweeps approach posterior averages. The sampler was named, and both facts were proved for it, by Geman and Geman (1984, section XII). Their setting is any distribution that gives positive probability to every configuration of finitely many variables, each with finitely many values, which the posterior here is. Their Theorem A states that the distribution of the state converges to $\pi$ from every start, provided every variable is updated infinitely often. Their Theorem C states that averages over time converge to averages under $\pi$, provided every variable is updated within a bounded number of steps. The argument does not say how many sweeps are enough: on the six documents $S\varepsilon$ is about $10^{-14}$, so the bound of step 3 is useless as a rate.
On the six documents the whole chain can be written down, since there are only $2^{10} = 1{,}024$ states. The script builds the $1{,}024 \times 1{,}024$ transition matrix of one sweep. Each of the ten single-word updates, and the sweep, leaves the exact posterior unchanged to within $10^{-15}$. Every entry of the sweep matrix is positive, the smallest about $10^{-17}$. After $n$ sweeps from the worst starting state, the largest error in any state's probability is 0.096 for $n = 10$, 0.0029 for $n = 50$ and $4 \times 10^{-5}$ for $n = 100$. Now the formula can be run by hand.
A trace on the six-document example
Back to the six documents of the LSI example:
$d_1$ = ship ocean voyage, $d_2$ = boat ocean, $d_3$ = ship, $d_4$ = voyage trip, $d_5$ = voyage, $d_6$ = trip.
That is ten word occurrences and $V = 5$ words. We fit $K = 2$ topics with $\alpha = 0.1$ and $\beta = 0.05$. The sampler starts from random assignments (seed 18 of the script's generator):
| Word | ship | ocean | voyage | boat | ocean | ship | voyage | trip | voyage | trip |
|---|---|---|---|---|---|---|---|---|---|---|
| Document | $d_1$ | $d_1$ | $d_1$ | $d_2$ | $d_2$ | $d_3$ | $d_4$ | $d_4$ | $d_5$ | $d_6$ |
| Topic | 1 | 2 | 2 | 1 | 2 | 2 | 2 | 1 | 1 | 2 |
Topic 1 holds ship, boat, voyage, and trip once each ($n_1 = 4$); topic 2 holds ship once, ocean twice, voyage twice, and trip once ($n_2 = 6$).
The first update. Word 1 is ship in $d_1$, currently in topic 1. Removing it leaves $d_1$ with counts $(0, 2)$ over the two topics, ship with counts $(0, 1)$, and the topic totals $(3, 6)$. The two weights are
$$\text{topic 1: } (0 + 0.1) \times \frac{0 + 0.05}{3 + 5 \times 0.05} = 0.1 \times \frac{0.05}{3.25} = 0.0015,$$
$$\text{topic 2: } (2 + 0.1) \times \frac{1 + 0.05}{6 + 5 \times 0.05} = 2.1 \times \frac{1.05}{6.25} = 0.3528.$$
Normalized, $P(z_1 = 1) = 0.004$. The generator gives $u = 0.391$, which falls in topic 2's share, so ship moves to topic 2. The counts are updated before the next word is visited. Both factors pushed it there: the rest of $d_1$ was in topic 2, and topic 2 already held the other ship. Yet topic 1's weight, 0.0015, was not zero. Unlike a zero in pLSA's EM, which stays zero for good, the pseudo-counts keep every topic open to every word.
The rest of the first sweep (weights rounded to four decimals):
| # | Word | Was | Weight, topic 1 | Weight, topic 2 | $P(\text{topic } 1)$ | $u$ | Now |
|---|---|---|---|---|---|---|---|
| 1 | $d_1$ ship | 1 | 0.0015 | 0.3528 | 0.004 | 0.391 | 2 |
| 2 | $d_1$ ocean | 2 | 0.0015 | 0.3528 | 0.004 | 0.508 | 2 |
| 3 | $d_1$ voyage | 2 | 0.0323 | 0.3528 | 0.084 | 0.202 | 2 |
| 4 | $d_2$ boat | 1 | 0.0022 | 0.0076 | 0.227 | 0.471 | 2 |
| 5 | $d_2$ ocean | 2 | 0.0022 | 0.1593 | 0.014 | 0.628 | 2 |
| 6 | $d_3$ ship | 2 | 0.0022 | 0.0145 | 0.133 | 0.088 | 1 |
| 7 | $d_4$ voyage | 2 | 0.3554 | 0.0168 | 0.955 | 0.941 | 1 |
| 8 | $d_4$ trip | 1 | 0.0169 | 0.0168 | 0.502 | 0.693 | 2 |
| 9 | $d_5$ voyage | 1 | 0.0467 | 0.0145 | 0.763 | 0.876 | 2 |
| 10 | $d_6$ trip | 2 | 0.0022 | 0.0145 | 0.133 | 0.487 | 2 |
A word moves to topic 1 when $u$ is below $P(\text{topic } 1)$. The first sweep is mostly a collapse. By word 5, topic 2 holds almost everything, and its large count makes it attractive to every later word. Topic 1 ends the sweep with one ship and one voyage. Word 6 went against the odds: topic 1 had probability 0.133, and $u = 0.088$ fell inside it. That randomness is what lets the sampler leave a poor state.
Example (two factors that cancel). At word 8, trip in $d_4$, neither factor wins: $P(\text{topic } 1) = 0.502$. The document's other word (voyage) has just moved to topic 1, while the only other trip is in topic 2. The document factor favors topic 1, 1.1 to 0.1, and the word factor favors topic 2 by about as much. The choice is a coin flip.
Over the next sweeps the two topics reorganize:
After ten sweeps the state has all of $d_1$ in the sea topic. Over ship, boat, ocean, voyage, trip, the estimates are
- $\hat{\phi}_1 = (0.328, 0.168, 0.328, 0.168, 0.008)$,
- $\hat{\phi}_2 = (0.012, 0.012, 0.012, 0.482, 0.482)$,
and $\hat{\theta}_{d_1} = (3.1/3.2,\ 0.1/3.2) = (0.969, 0.031)$. But this is one state of a sampler that keeps moving, and one state is not the answer, as the exact posterior shows.
Checking the sampler against the exact posterior
Ten words with two topics have only $2^{10} = 1{,}024$ possible assignments. So here, unlike Reuters, the posterior can be computed exactly, by evaluating the collapsed joint for each assignment and normalizing. The most probable assignments are:
| Assignment | Posterior probability (each labeling) |
|---|---|
| Sea/travel split: $d_1$'s voyage with travel, its ship and ocean with sea | 0.124 |
| boat and ocean alone in one topic, everything else in the other | 0.052 |
| All of $d_1$ with the sea words | 0.051 |
Each appears twice, once with the sea in topic 1 and once in topic 2, because swapping the labels of the topics changes nothing in the model. The split has total probability 0.247. The probability that all three words of $d_1$ share a topic is 0.412. With $\alpha = 0.1$, the prior strongly prefers documents about one thing, and $d_1$ is ambiguous.
Example (where a stopped sampler is found). A sampler run for many sweeps and stopped has about one chance in four of being at the sea/travel split, the most probable division of the words: 0.247, the split's posterior probability with both labelings counted. Three times out of four the final state is something else, such as all of $d_1$ in one topic.
Over 30 runs (seeds 1 to 30) of 10,000 sweeps each, discarding the first 100, the share of sweeps spent at the split had median 0.250 (interquartile range 0.244 to 0.255), against the exact 0.247. The first visit to the split came after a median of 5 sweeps (IQR 4 to 15, longest 34). The sampled average of $\hat{\phi}$ was compared with the exact posterior mean, after matching each sample's topics to sea and travel. Its median over the 30 runs was within 0.003 of the exact value in every entry.
Two lessons carry over to real collections. The first is the example's point: a single sample is one plausible state. The second is that averaging samples requires care, because topic labels can swap between samples. In this tiny example they swap often. In a large collection a swap within one run is rare, which is why topics are commonly reported from a single late sample, as Griffiths and Steyvers (2004) did.
Sampling is one way to approximate the posterior. The other replaces it with a simpler distribution that can be optimized.
That is variational inference, the method of Blei, Ng, and Jordan (2003). It gives each document's proportions a Dirichlet distribution of its own and each word position its own distribution over topics, and adjusts them by two updates that never lower a bound on the probability of the documents. Variational inference for LDA derives the updates in full and runs them on the six documents, where the bound stays below the exact value. The Reuters model below is fitted this way.
Hyperparameters
The values of $\alpha$ and $\beta$ affect the topics found, and they can be learned from the data instead of fixed. Wallach, Mimno, and McCallum (2009) found that an asymmetric prior on the document proportions, letting some topics be generally more common than others, gave better models. It absorbed common words into a few general topics. The prior on the topics could safely stay symmetric.
The six documents showed the machinery. The next section runs it on real news.
Twenty topics in Reuters
LDA was fitted to the 7,769 training stories of Reuters-21578, after four preprocessing steps:
- lowercasing;
- keeping words of at least three letters;
- removing English stop words and a few Reuters-specific abbreviations (mln, dlrs, pct, shr, and others);
- keeping the 6,855 words that appear in at least 5 stories and at most half of them.
The model used $K = 20$, priors $\alpha = \beta = 1/K$, and 30 passes of batch variational inference. How to read the table:
- The labels are interpretations of the top words.
- The average weight is the topic's mean proportion across stories, each story counting equally.
- The category is the one most common among the stories where the topic has the largest weight, with the share of those stories that carry it. Stories can have several categories.
| Topic | Top words | Average weight | Most common category |
|---|---|---|---|
| Earnings tables | loss profit qtr revs oper note avg shrs sales includes | 15.6% | earn (98%) |
| Interest rates | bank rate banks market money rates central dealers fed week | 7.4% | interest (46%) |
| Asset sales | unit sale acquisition agreement sell assets terms subsidiary completed purchase | 7.0% | acq (89%) |
| Currencies and Japan | dollar japan economic government yen exchange japanese trade foreign currency | 6.4% | money-fx (40%) |
| Dividends | april record div gold pay qtly prior march sets dividend | 6.2% | earn (93%) |
| Economic statistics | january february rose rise stg december fell deficit compared surplus | 6.1% | trade (18%) |
| Grain and commodities | tonnes sugar wheat corn export usda production prices week grain | 5.3% | grain (51%) |
| Earnings reports | quarter earnings share sales profit expects reported results income profits | 5.1% | earn (94%) |
| Stakes | shares stock stake group common investment securities share exchange outstanding | 5.0% | acq (91%) |
| Takeover bids | offer share shares merger board tender shareholders bid stock acquisition | 4.9% | acq (93%) |
| Trade policy | trade japan states united house japanese usair officials reagan countries | 4.8% | trade (48%) |
| Metals and mixed | francs prices new plant steel marks copper price capacity group | 4.0% | crude (21%) |
| Stock splits | stock dividend split share april board record shareholders declared common | 3.6% | earn (91%) |
| Oil markets | oil opec bpd crude gulf prices saudi strike union ecuador | 3.2% | crude (56%) |
| British companies | stg plc group british standard shares bid pretax royal shell | 3.0% | earn (42%) |
| Soft commodities | coffee brazil cocoa prices stock producers new buffer export price | 2.9% | coffee (43%) |
| Energy production | oil gas energy reserves production petroleum exploration prices natural barrels | 2.8% | crude (58%) |
| Futures trading | analysts futures market analyst exchange american trading new contracts shearson | 2.6% | acq (35%) |
| (incoherent) | department dutch guilders credit hughes court baker bonus ccc turkey | 2.0% | acq (35%) |
| Agriculture abroad | china soviet grain wheat union crop weather state soybean agriculture | 2.0% | grain (56%) |
Most topics are immediately recognizable. Several patterns are typical of LDA:
- Large categories are split by their language. Earnings reports, the largest Reuters category, appear as four topics: results tables, dividend announcements, stock splits, and the prose of quarterly reports. Acquisitions appear as three: sales of units and assets, purchases of stakes, and takeover bids. As with k-means on Reuters, distinct vocabularies within one category are easier to separate than small categories with overlapping language.
- Topics follow co-occurrence, not meaning. "Trade policy" includes usair, which appears in 43 training stories, 42 of them about acquisitions. Its place in a trade topic is an artifact of the fit, not a theme. "Currencies and Japan" combines two subjects that often appeared in the same stories.
- Some topics are mixtures or junk. "Metals and mixed" combines steel, copper, and European currencies (francs and marks). One topic, of dutch, guilders, hughes, court, and turkey, has no coherent subject at all. Its coherence score, discussed in evaluating topic models, is the only negative one among the twenty.
The ten words in each row of the table are not the whole topic, as the next subsection shows.
What a topic is, in numbers
Example (how much of a topic its top ten words hold). Each topic is a distribution over all 6,855 words, and in a typical topic its ten listed words do not carry most of its probability. Across the twenty topics, the ten most probable words carry a median of 17 percent of a topic's probability. The range runs from 9 percent for "Currencies and Japan" to 55 percent for the formulaic "Earnings tables". The figure shows how the rest spreads out:
In a typical topic about 870 words have more than the uniform probability $1/V$. The top-word lists are a summary for reading, and the tail is where most of the probability lives. That tail is what lets a topic give some probability to a word a document never used, which pLSA's best fit on the six documents could not do.
One story's mixture
The story training/1000, about a raised bid for Viacom, is labeled acq. Its inferred mixture is
- 35 percent takeover bids,
- 33 percent British companies,
- 19 percent stock splits,
- 12 percent earnings tables.
The first is right. The second is a mistake: nothing in the story concerns a British company. A short story gives inference little evidence, and words shared by several topics, such as bid, can be credited to the wrong one.
Across the training set, 71 percent of stories had a single topic above one-half of their mixture. Stories had on average 2.3 topics with more than a tenth of their weight. That is close to what the prior with $\alpha = 1/K$ predicts for random draws. Each component of a Dirichlet with $K = 20$ and $\alpha = 0.05$ has a beta distribution with parameters 0.05 and 0.95, which exceeds a tenth with probability 0.112, so a draw has on average $20 \times 0.112 = 2.24$ topics above a tenth (dirichlet_demo.py).
The scripts are reuters_lda.py, reuters_coherence_hand.py, and lda_gibbs_toy.py in tools/experiments/topics/ in the site repository, and the figures are drawn by tools/figures/latent-dirichlet-allocation.py.
Worked problems
The course had no assignment for this topic, and the course text has no exercises on LDA. This problem is posed on the six documents with the article's settings, $K = 2$, $\alpha = 0.1$ and $\beta = 0.05$, and every number in it is checked by lda_gibbs_toy.py. Two more problems, on the expected logarithm and on the variational bound, are in variational inference for LDA.
Problem 1 (one Gibbs update, and what it says about two states). Every word except $d_1$'s voyage is at the sea/travel split: ship, boat and ocean in the sea topic, and the voyage and trip of $d_4$, $d_5$ and $d_6$ in the travel topic. Find the probability that the sampler assigns $d_1$'s voyage to travel, and use it to compare the posterior probabilities of the split and of the state with all of $d_1$ in the sea topic.
The probability is 0.707, and the split is 2.41 times as probable as the other state. With $d_1$'s voyage removed, the counts are:
- in $d_1$: two words in the sea topic and none in travel;
- voyage: none in the sea topic, two in travel ($d_4$ and $d_5$);
- topic totals: five in the sea topic (two ship, one boat, two ocean), four in travel (two voyage, two trip).
The update formula gives the weights
$$\text{sea: } (2 + 0.1) \times \frac{0 + 0.05}{5 + 0.25} = 0.0200, \qquad \text{travel: } (0 + 0.1) \times \frac{2 + 0.05}{4 + 0.25} = 0.0482.$$
So $P(\text{travel}) = 0.0482 / 0.0682 = 0.707$. The document factor favors the sea, 2.1 to 0.1, and the word factor favors travel by more, since the sea topic holds no voyage at all.
The two possible outcomes are the two states of the question, and they differ only in this word. By step 4 of the derivation, the conditional probabilities of the two values are proportional to the joint probabilities of the two states. So the posterior odds of the split against the state with all of $d_1$ in the sea topic are $0.0482 / 0.0200 = 2.41$. The exact posterior agrees: 0.1236 against 0.0513 for one labeling of each, a ratio of 2.41, and these are the 0.124 and 0.051 of the table of the exact posterior.
What we have learned
LDA completes pLSA by drawing each document's mixture from a shared Dirichlet prior, whose pseudo-counts keep every word possible in every topic. Its posterior must be approximated. Collapsed Gibbs sampling, derived from conjugacy and proved to converge to the posterior, matched the exact posterior on the six documents, where the sea/travel split holds only a quarter of the probability. Variational inference, the other standard method and the one used on Reuters, is derived in variational inference for LDA. On Reuters, twenty topics were mostly recognizable, and one was junk.
We judged those topics by reading them. Evaluating topic models sets out how a model's quality is measured, and what the measurements can and cannot say about how many topics to fit.
References
- Blei, D. M., Ng, A. Y., and Jordan, M. I. (2003). Latent Dirichlet allocation. Journal of Machine Learning Research, 3, 993–1022. record · 6 pages
- Geman, S., and Geman, D. (1984). Stochastic relaxation, Gibbs distributions, and the Bayesian restoration of images. IEEE Transactions on Pattern Analysis and Machine Intelligence, 6(6), 721–741. record · 3 pages
- Griffiths, T. L., and Steyvers, M. (2004). Finding scientific topics. Proceedings of the National Academy of Sciences, 101(suppl. 1), 5228–5235. record
- Manning, C. D., Raghavan, P., and Schütze, H. (2008). Introduction to Information Retrieval, chapter 21. Cambridge University Press. record · 102 pages
- McCallum, A. K. (2002). MALLET: A machine learning for language toolkit. Software, University of Massachusetts Amherst. record
- Wallach, H. M., Mimno, D., and McCallum, A. (2009). Rethinking LDA: Why priors matter. In Advances in Neural Information Processing Systems 22 (NIPS 2009), 1973–1981. record
Reviewed: verified, 16 Nov 2026 · citations checked, 16 Nov 2026 · editorial review, 23 Nov 2026 · 13 revisions