Skip to content
BIASED

Latent Dirichlet allocation

A topic model in which every document is its own mixture of shared topics: the generative story, Dirichlet priors as pseudo-counts, Dirichlet–multinomial conjugacy, collapsed Gibbs sampling on counts, and mean-field variational inference.

One topic per document is not enough

The topic Dirichlet processes ended with mixture models whose every object belongs to exactly one cluster. Apply that to text, with a whole document as the object, and each document gets exactly one theme. Real documents are not like that: a report on a football club's finances is about sport and about money at once. This topic builds a mixture of mixtures, in which every document mixes several shared themes in its own proportions.

A word of warning first. In this lesson a topic almost always means an LDA topic, a distribution over words; earlier lessons of the course are named in italics.

Text is treated as a bag of words: a document is the multiset of its tokens, and word order is thrown away. Take a vocabulary of V=4V = 4 words (team, goal, market, price) and two topics, each a probability vector over the vocabulary:

ϕ1=(0.45, 0.45, 0.05, 0.05) (sport),ϕ2=(0.05, 0.05, 0.45, 0.45) (economics).\phi_1 = (0.45,\ 0.45,\ 0.05,\ 0.05) \ \text{(sport)}, \qquad \phi_2 = (0.05,\ 0.05,\ 0.45,\ 0.45) \ \text{(economics)}.

A mixture of unigrams picks one topic per document with probabilities πk\pi_k and draws all the words from it:

p(wd)=∑k=1Kπk∏n=1Ndϕkwdn.p(w_d) = \sum_{k=1}^{K} \pi_k \prod_{n=1}^{N_d} \phi_{k w_{dn}}.

For the document "goal team price" with π=(0.5,0.5)\pi = (0.5, 0.5) this gives 0.5⋅0.010125+0.5⋅0.001125=0.0056250.5 \cdot 0.010125 + 0.5 \cdot 0.001125 = 0.005625. The sport topic alone explains "goal team" well but has to pay 0.050.05 for "price", and no single topic does better.

LDA instead gives each document its own topic proportions θd\theta_d and lets every word choose its topic separately. The probability of one word becomes a mixture:

p(wdn=w∣θd,ϕ)=∑k=1Kθdk ϕkw.p(w_{dn} = w \mid \theta_d, \phi) = \sum_{k=1}^{K} \theta_{dk}\, \phi_{kw}.

With θd=(2/3,1/3)\theta_d = (2/3, 1/3) the words "goal" and "team" get 23⋅0.45+13⋅0.05≈0.317\tfrac23 \cdot 0.45 + \tfrac13 \cdot 0.05 \approx 0.317 each, "price" gets ≈0.183\approx 0.183, and the document gets ≈0.0184\approx 0.0184: about 1.81.8 times what the sport topic alone gives and more than three times the mixture of unigrams.

The generative story

LDA is a generative model with KK topics, a vocabulary of size VV and DD documents, document dd having NdN_d tokens. Two hyperparameters set symmetric Dirichlet priors: α\alpha for the proportions, β\beta for the topics. The story:

  1. For each topic k=1,…,Kk = 1, \dots, K: draw the word distribution ϕk∼Dir⁡(β)\phi_k \sim \operatorname{Dir}(\beta).
  2. For each document d=1,…,Dd = 1, \dots, D: draw the topic proportions θd∼Dir⁡(α)\theta_d \sim \operatorname{Dir}(\alpha).
  3. For each position n=1,…,Ndn = 1, \dots, N_d in document dd: draw the topic assignment zdn∼Cat⁡(θd)z_{dn} \sim \operatorname{Cat}(\theta_d),
  4. and then the word wdn∼Cat⁡(ϕzdn)w_{dn} \sim \operatorname{Cat}(\phi_{z_{dn}}).

Only the words ww are observed. The joint distribution of everything is

p(w,z,θ,ϕ)=∏k=1KDir⁡(ϕk∣β)∏d=1D(Dir⁡(θd∣α)∏n=1Ndθdzdn ϕzdnwdn).p(w, z, \theta, \phi) = \prod_{k=1}^{K} \operatorname{Dir}(\phi_k \mid \beta) \prod_{d=1}^{D} \Big( \operatorname{Dir}(\theta_d \mid \alpha) \prod_{n=1}^{N_d} \theta_{d z_{dn}}\, \phi_{z_{dn} w_{dn}} \Big).

Two kinds of latent variables sit in this formula. The topics ϕk\phi_k are global: every document draws its words from the same KK topics. The proportions θd\theta_d and the assignments zdnz_{dn} are local: each belongs to one document or one token. This split will matter again in the topic Stochastic variational inference.

Summing zdnz_{dn} out gives back the mixture of the previous block, and in matrix form the model says something familiar. Stack the θd\theta_d into a D×KD \times K matrix Θ\Theta and the ϕk\phi_k into a K×VK \times V matrix Φ\Phi. Then the D×VD \times V matrix of word probabilities is ΘΦ\Theta \Phi: a non-negative low-rank factorization, with rows of both factors on the probability simplex. Its non-Bayesian ancestor, pLSA, fits θd\theta_d as free parameters; LDA puts a prior on them, which controls overfitting and gives a principled way to handle a new document.

Note what the model ignores. Given θd\theta_d and ϕ\phi, the tokens of a document are independent and identically distributed, so reordering them changes nothing.

Dirichlet priors as pseudo-counts

The Dirichlet distribution came up in the topic Dirichlet processes. On the simplex {θ:θk≥0,∑kθk=1}\{\theta : \theta_k \ge 0, \sum_k \theta_k = 1\} its density is

Dir⁡(θ∣α)=1B(α)∏k=1Kθkαk−1,B(α)=∏kΓ(αk)Γ(∑kαk).\operatorname{Dir}(\theta \mid \alpha) = \frac{1}{B(\alpha)} \prod_{k=1}^{K} \theta_k^{\alpha_k - 1}, \qquad B(\alpha) = \frac{\prod_k \Gamma(\alpha_k)}{\Gamma\big(\sum_k \alpha_k\big)}.

Dir⁡(α)\operatorname{Dir}(\alpha) with a scalar α\alpha means αk=α\alpha_k = \alpha for all kk. Note the reuse of letters: in the previous topic α\alpha was the DP concentration, and in Bayesian linear regression β\beta was a noise precision; here both are Dirichlet parameters. A symmetric Dirichlet has mean αk/∑jαj=1/K\alpha_k / \sum_j \alpha_j = 1/K whatever α\alpha is, so α\alpha controls the shape around the mean:

  • α<1\alpha < 1: the density grows towards the corners and edges of the simplex; documents use few topics.
  • α=1\alpha = 1: the density is uniform on the simplex.
  • α>1\alpha > 1: the density peaks at the centre; documents mix all topics evenly.

β\beta plays the same role for topics: a small β\beta makes each topic concentrate on few words.

The Dirichlet is conjugate to the categorical distribution (see Conjugate priors and the exponential family). If ndkn_{dk} of the NdN_d tokens of document dd are assigned to topic kk, the likelihood is ∏kθdkndk\prod_k \theta_{dk}^{n_{dk}}, and

p(θd∣zd)=Dir⁡(α+nd1,…,α+ndK),E[θdk∣zd]=ndk+αNd+Kα.p(\theta_d \mid z_d) = \operatorname{Dir}(\alpha + n_{d1}, \dots, \alpha + n_{dK}), \qquad \mathbb E[\theta_{dk} \mid z_d] = \frac{n_{dk} + \alpha}{N_d + K\alpha}.

So α\alpha is a pseudo-count: as if every topic had already been seen α\alpha times in every document. A document with counts (4,1)(4, 1) gets the posterior mean (0.788,0.212)(0.788, 0.212) with α=0.1\alpha = 0.1, (0.75,0.25)(0.75, 0.25) with α=0.5\alpha = 0.5, and (0.6,0.4)(0.6, 0.4) with α=5\alpha = 5: the larger α\alpha, the harder the estimate is pulled towards uniform.

The hyperparameters matter in practice: on synthetic data with known topics, an α\alpha off by a factor of ten can hide the true topics altogether. Popular defaults are α=50/K\alpha = 50/K with β=0.1\beta = 0.1, or α=β=1/K\alpha = \beta = 1/K; they can also be learned by evidence maximization, as in Bayesian model selection.

Integrating out proportions and topics

We want the posterior over all the latent variables, p(z,θ,ϕ∣w)p(z, \theta, \phi \mid w). Its normalizer sums over every assignment of topics to tokens: KNK^N terms for N=∑dNdN = \sum_d N_d tokens. The tiny corpus below has 212=40962^{12} = 4096; a real one has millions of tokens. As with the Gaussian mixtures of EM and Bayesian PCA, the exact computation is hopeless, and we approximate.

Conjugacy lets us integrate out the continuous variables exactly. For one document,

p(zd∣α)=∫∏kθdkndkDir⁡(θd∣α) dθd=B(nd⋅+α)B(α),p(z_d \mid \alpha) = \int \prod_k \theta_{dk}^{n_{dk}} \operatorname{Dir}(\theta_d \mid \alpha)\, d\theta_d = \frac{B(n_{d\cdot} + \alpha)}{B(\alpha)},

and the same calculation for each topic gives the collapsed joint

p(w,z)=∏k=1KB(nk⋅+β)B(β)∏d=1DB(nd⋅+α)B(α),p(w, z) = \prod_{k=1}^{K} \frac{B(n_{k\cdot} + \beta)}{B(\beta)} \prod_{d=1}^{D} \frac{B(n_{d\cdot} + \alpha)}{B(\alpha)},

where nk⋅=(nk1,…,nkV)n_{k\cdot} = (n_{k1}, \dots, n_{kV}) counts the tokens of each word assigned to topic kk, and nk=∑vnkvn_k = \sum_v n_{kv}. Only counts remain.

The ratio of BB functions has a sequential reading. Integrating θd\theta_d out, the predictive probability that the next token of document dd gets topic kk is the posterior mean from the previous block, (ndk+α)/(Nd+Kα)(n_{dk} + \alpha)/(N_d + K\alpha), and the probability of a whole sequence of assignments is a product of such predictive steps, each with the counts updated by the steps before. Take a document with assignments (1,1,2)(1, 1, 2) and α=0.5\alpha = 0.5:

0.51⋅1.52⋅0.53=0.0625=B(2.5, 1.5)B(0.5, 0.5).\frac{0.5}{1} \cdot \frac{1.5}{2} \cdot \frac{0.5}{3} = 0.0625 = \frac{B(2.5,\ 1.5)}{B(0.5,\ 0.5)}.

Each token of a topic makes the next one more likely, like drawing balls from a Pólya urn and returning two of the same colour.

Now the conditional for one token. Let token ii be word vv in document dd, and let a superscript −i-i mean "counts of all tokens except ii". The conditional is the product of two predictive probabilities, one for the topic within the document and one for the word within the topic:

p(zi=k∣z−i,w)∝ndk−i+αNd−1+Kα⋅nkv−i+βnk−i+Vβ.p(z_i = k \mid z_{-i}, w) \propto \frac{n_{dk}^{-i} + \alpha}{N_d - 1 + K\alpha} \cdot \frac{n_{kv}^{-i} + \beta}{n_k^{-i} + V\beta}.

Collapsed Gibbs sampling

The first denominator is the same for every topic, so the sampler uses

p(zi=k∣z−i,w)∝(ndk−i+α) nkv−i+βnk−i+Vβ.p(z_i = k \mid z_{-i}, w) \propto \big(n_{dk}^{-i} + \alpha\big)\, \frac{n_{kv}^{-i} + \beta}{n_k^{-i} + V\beta}.

This is collapsed Gibbs sampling (Griffiths and Steyvers, 2004): Gibbs sampling, as in the topic Gibbs sampling and Metropolis–Hastings, on the collapsed model where only zz is left. The first factor says "topics popular in this document", the second "topics in which this word is common". A sweep visits every token in turn: remove it from the counts, compute KK weights, draw a topic, put the token back under the new topic.

A tiny corpus with K=2K = 2, V=4V = 4, α=0.5\alpha = 0.5, β=0.1\beta = 0.1; each word is followed by its current topic:

Document Tokens (topic)
1 team (1), goal (1), team (1), goal (1), market (2)
2 market (2), price (2), price (2), goal (1)
3 goal (1), team (1), price (2)

The count tables are nd⋅=(4,1),(1,3),(2,1)n_{d\cdot} = (4, 1), (1, 3), (2, 1) for the documents; topic 1 holds team 3, goal 4 (n1=7n_1 = 7), topic 2 holds market 2, price 3 (n2=5n_2 = 5).

Update the token goal in document 2. Without it, document 2 has n2⋅−i=(0,3)n_{2\cdot}^{-i} = (0, 3); topic 1 has 33 goals out of 66 tokens, topic 2 has 00 out of 55. The weights:

topic 1: 0.5⋅3.16.4≈0.2422,topic 2: 3.5⋅0.15.4≈0.0648.\text{topic 1:}\ 0.5 \cdot \frac{3.1}{6.4} \approx 0.2422, \qquad \text{topic 2:}\ 3.5 \cdot \frac{0.1}{5.4} \approx 0.0648.

Topic 1 wins with probability 0.2422/0.3070≈0.7890.2422 / 0.3070 \approx 0.789: the document leans to economics, but "goal" has never been seen there, and the word factor is stronger.

After burn-in the counts give point estimates, again the Dirichlet posterior means:

ϕ^kv=nkv+βnk+Vβ,θ^dk=ndk+αNd+Kα.\hat\phi_{kv} = \frac{n_{kv} + \beta}{n_k + V\beta}, \qquad \hat\theta_{dk} = \frac{n_{dk} + \alpha}{N_d + K\alpha}.

They are usually averaged over several well-separated samples of one chain.

Mean-field variational inference

The deterministic alternative is mean-field variational inference (Blei, Ng and Jordan, 2003), with the family

q(θ,z,ϕ)=∏kDir⁡(ϕk∣λk)∏d(Dir⁡(θd∣γd)∏nCat⁡(zdn∣rdn)).q(\theta, z, \phi) = \prod_{k} \operatorname{Dir}(\phi_k \mid \lambda_k) \prod_{d} \Big( \operatorname{Dir}(\theta_d \mid \gamma_d) \prod_{n} \operatorname{Cat}(z_{dn} \mid r_{dn}) \Big).

Here θ\theta and ϕ\phi are not integrated out but approximated. Each factor follows from the coordinate update of the topic Variational inference, log⁡qj∗=E−j[log⁡p]+const\log q_j^* = \mathbb E_{-j}[\log p] + \text{const}. The term of log⁡p\log p with zdnz_{dn} is ∑k[zdn=k](log⁡θdk+log⁡ϕkwdn)\sum_k [z_{dn} = k] \big(\log \theta_{dk} + \log \phi_{k w_{dn}}\big), and averaging it gives

rdnk∝exp⁡(Eq[log⁡θdk]+Eq[log⁡ϕkwdn]),Eq[log⁡θdk]=ψ(γdk)−ψ(∑jγdj),r_{dnk} \propto \exp\big(\mathbb E_q[\log \theta_{dk}] + \mathbb E_q[\log \phi_{k w_{dn}}]\big), \qquad \mathbb E_q[\log \theta_{dk}] = \psi(\gamma_{dk}) - \psi\Big(\sum_j \gamma_{dj}\Big),

where ψ\psi is the digamma function, the derivative of log⁡Γ\log \Gamma; Eq[log⁡ϕkv]\mathbb E_q[\log \phi_{kv}] has the same form with λ\lambda. The Dirichlet factors are conjugate updates with expected counts in place of counts:

γdk=α+∑nrdnk,λkv=β+∑d,nrdnk [wdn=v].\gamma_{dk} = \alpha + \sum_{n} r_{dnk}, \qquad \lambda_{kv} = \beta + \sum_{d, n} r_{dnk}\, [w_{dn} = v].

The algorithm alternates a local step (for each document, iterate rdr_d and γd\gamma_d with the topics fixed) and a global step (recompute λ\lambda from all documents).

Note that exp⁡Eq[log⁡θdk]\exp \mathbb E_q[\log \theta_{dk}] is not Eq[θdk]\mathbb E_q[\theta_{dk}]. For γd=(1,1)\gamma_d = (1, 1) the mean is 0.50.5, while ψ(1)−ψ(2)=−1\psi(1) - \psi(2) = -1 gives e−1≈0.368e^{-1} \approx 0.368.

Compared with collapsed Gibbs, mean field is deterministic, usually needs fewer passes and reports an ELBO to monitor. It is also biased by its family: the factorized qq ignores dependencies and underestimates posterior variance. The Gibbs sampler is asymptotically exact but noisy, and its convergence is harder to judge.

Where LDA breaks and what comes next

A model is usually judged by held-out perplexity,

PPL=exp⁡(−∑dlog⁡p(wd)∑dNd),\mathrm{PPL} = \exp\Big(-\frac{\sum_d \log p(w_d)}{\sum_d N_d}\Big),

the effective number of equally likely words the model hesitates between: a uniform model over VV words has perplexity VV. Since p(wd)p(w_d) is itself intractable, it is estimated, for example by document completion: infer θd\theta_d from half of a held-out document and score the other half. Lower is better, but likelihood does not always agree with human judgement, so topics are also scored by coherence: how often their top words occur together in documents.

Where LDA breaks:

  • Label switching. The posterior is symmetric in the topic labels, so topic 3 in one run may be topic 7 in another. Compare runs only after matching topics, e.g. with the Hungarian algorithm.
  • Local optima. Some restarts merge two themes into one topic and split another; run several restarts and keep the best ELBO or likelihood.
  • Choosing KK. Training fit almost always improves with KK; held-out perplexity and coherence often disagree. The hierarchical Dirichlet process infers the number of topics, at the price of a harder sampler.
  • Bag of words. Order and negation are invisible, and frequent stop words such as "the" and "of" dominate topics unless they are removed.

The last problem is cost. One Gibbs sweep and one mean-field iteration both touch every token of the corpus, and in mean field the topics λ\lambda are recomputed only after the local steps of all documents. With millions of documents, each improvement of the topics waits for a full pass over the data. The topic Stochastic variational inference fixes exactly this: it treats the global step as a natural-gradient step on the ELBO, estimated from a small minibatch of documents.

Check your understanding

The same questions as in Pulse. Answers are shared between modes.

Full notes

Answers are saved on the server and tied to this browser until you sign in.