Simple Algorithm
Machine Learning · Convergence · 28 min

Topic Models & Latent Dirichlet Allocation

Documents as mixtures of topics.

Give a machine a hundred thousand articles and no labels, and it can still sort their words into themes such as genetics, evolution, disease and computing. Latent Dirichlet allocation does it by treating each document as a mixture of topics and each topic as a distribution over words. This lesson derives the model and its two classic inference algorithms, asks how a topic model should be judged, and shows the provable algorithms that sidestep its intractable likelihood.

What you’ll learn

  • State LDA's generative process and joint distribution, explain mixed membership and how Dirichlet hyperparameters control sparsity, and relate LDA to the mixture of unigrams, pLSI and nonnegative matrix factorization.
  • Derive the collapsed Gibbs sampler from Dirichlet–multinomial conjugacy, and the mean-field variational updates of variational EM.
  • Evaluate topic models by held-out likelihood and by human-centered measures, and explain why the two can disagree.
  • Explain how the separability (anchor-word) assumption and the method of moments give polynomial-time algorithms with guarantees, while maximum likelihood and MAP inference are NP-hard in the worst case.

Documents as mixtures of topics

Fix a vocabulary of VV words and a number of topics KK. A topic is a distribution βk\boldsymbol\beta_k over the vocabulary; a document dd has topic proportions θd\boldsymbol\theta_d, a distribution over the KK topics. Latent Dirichlet allocation (Blei, Ng & Jordan, 2003) generates a corpus as follows, with Dirichlet priors on both kinds of distribution:

  1. For each topic kk, draw βk∼Dir(η1V)\boldsymbol\beta_k\sim\mathrm{Dir}(\eta\mathbf 1_V).
  2. For each document dd, draw θd∼Dir(α1K)\boldsymbol\theta_d\sim\mathrm{Dir}(\alpha\mathbf 1_K).
  3. For each word position nn of document dd, draw a topic zdn∼Cat(θd)z_{dn}\sim\mathrm{Cat}(\boldsymbol\theta_d), then the word wdn∼Cat(βzdn)w_{dn}\sim\mathrm{Cat}(\boldsymbol\beta_{z_{dn}}).
p(β,θ,z,w)=∏k=1KDir(βk∣η) ∏d=1D[Dir(θd∣α)∏n=1Ndθd,zdn βzdn,wdn]p(\boldsymbol\beta,\boldsymbol\theta,\mathbf z,\mathbf w)=\prod_{k=1}^K\mathrm{Dir}(\boldsymbol\beta_k\mid\eta)\ \prod_{d=1}^D\Big[\mathrm{Dir}(\boldsymbol\theta_d\mid\alpha)\prod_{n=1}^{N_d}\theta_{d,z_{dn}}\,\beta_{z_{dn},w_{dn}}\Big]
Words are exchangeable within a document (a "bag of words"); Blei, Ng & Jordan motivate the per-document latent θd\boldsymbol\theta_d through de Finetti's representation theorem. Symmetric hyperparameters α\alpha and η\eta are the common choice.

The key word is mixed membership: unlike a mixture model, which gives each document a single topic, LDA lets every document draw each of its words from a different topic. Averaging over the word positions, document dd's expected word distribution is ∑kθdkβk\sum_k\theta_{dk}\boldsymbol\beta_k, so the D×VD\times V matrix of document word probabilities factorizes as ΘB\Theta B with nonnegative rows that sum to one: LDA is a Bayesian, simplex-constrained nonnegative matrix factorization. Latent semantic analysis (Deerwester et al., 1990) factorized the count matrix with a truncated SVD instead, which allows negative "topics" that are hard to read.

ModelTopics per documentDocument proportions θd\boldsymbol\theta_dConsequence
Mixture of unigramsonea single hidden label zdz_da document about genetics and disease must pick one
pLSI (Hofmann, 1999)manyfree parameters, one vector per training document, fitted by EMKDKD parameters grow with the corpus; no probability for a new document; overfits
LDAmanyrandom, θd∼Dir(α)\boldsymbol\theta_d\sim\mathrm{Dir}(\alpha), integrated outa fixed number of global parameters and a proper generative model for new documents
With a flat prior, Dir(1)\mathrm{Dir}(\mathbf 1), the density of θd\boldsymbol\theta_d is constant on the simplex, so MAP estimation of the proportions coincides with maximum likelihood: pLSI is LDA fitted by MAP with α=1\alpha=1 (Girolami & Kabán, 2003, make the equivalence precise).

Dirichlet priors and sparsity

The Dirichlet density on the simplex is Dir(θ∣α)=Γ(α0)∏kΓ(αk)∏kθkαk−1\mathrm{Dir}(\boldsymbol\theta\mid\boldsymbol\alpha)=\frac{\Gamma(\alpha_0)}{\prod_k\Gamma(\alpha_k)}\prod_k\theta_k^{\alpha_k-1} with α0=∑kαk\alpha_0=\sum_k\alpha_k; it has mean αk/α0\alpha_k/\alpha_0 and Var⁡θk=αk(α0−αk)/(α02(α0+1))\Var\theta_k=\alpha_k(\alpha_0-\alpha_k)/\big(\alpha_0^2(\alpha_0+1)\big). For a symmetric α\alpha the shape is set by α\alpha alone:

  • α<1\alpha<1: the density blows up at the faces of the simplex, so draws are sparse, with a few large proportions and many near zero. Documents are about a handful of topics; topics use a small part of the vocabulary (small η\eta).
  • α=1\alpha=1: uniform on the simplex.
  • α>1\alpha>1: mass concentrates near the center, with every topic present in every document.

Conjugacy makes the posterior easy: given the topic counts nd=(nd1,…,ndK)\mathbf n_d=(n_{d1},\dots,n_{dK}) of document dd, θd∣zd∼Dir(α+nd)\boldsymbol\theta_d\mid\mathbf z_d\sim\mathrm{Dir}(\alpha+\mathbf n_d), and the next word's topic has predictive probability (ndk+α)/(Nd+Kα)(n_{dk}+\alpha)/(N_d+K\alpha). The hyperparameter acts as a pseudo-count added to every topic.

Predict before you look

With K=10K=10 topics and a symmetric Dir(0.1)\mathrm{Dir}(0.1) prior, each proportion θk\theta_k has mean 0.10.1. What is its standard deviation?

Show the answer

0.21

With α0=Kα=1\alpha_0=K\alpha=1, Var⁡θk=0.1×0.91×2=0.045\Var\theta_k=\frac{0.1\times0.9}{1\times2}=0.045, so the standard deviation is about 0.210.21, twice the mean: a typical draw puts most of its mass on one or two topics. With α=10\alpha=10 the standard deviation falls to about 0.030.03 and every topic gets close to its 10% share.

Inference: collapsed Gibbs sampling and variational EM

The posterior p(θ,z∣w,α,β)p(\boldsymbol\theta,\mathbf z\mid\mathbf w,\alpha,\boldsymbol\beta) couples every topic proportion with every word assignment and has no closed form. It is not merely inconvenient: Sontag & Roy (2011) proved that finding the most probable assignment of topics to words is NP-hard when documents use many topics (it is polynomial when they use few), that finding a document's most probable topic proportions is NP-hard too, and that sampling from the posterior is NP-hard in one restricted setting. Practical inference is therefore approximate.

Collapsed Gibbs sampling (Griffiths & Steyvers, 2004) integrates out θ\boldsymbol\theta and β\boldsymbol\beta analytically and samples only the topic assignments z\mathbf z.

DerivationThe collapsed conditional
  1. p(z,w∣α,η)=∏d=1DB(nd+α1)B(α1) ∏k=1KB(mk+η1)B(η1)p(\mathbf z,\mathbf w\mid\alpha,\eta)=\prod_{d=1}^D\frac{B(\mathbf n_d+\alpha\mathbf 1)}{B(\alpha\mathbf 1)}\ \prod_{k=1}^K\frac{B(\mathbf m_k+\eta\mathbf 1)}{B(\eta\mathbf 1)}

    Integrating each Dirichlet against its multinomial counts gives a ratio of multivariate Beta functions, B(a)=∏jΓ(aj)/Γ(∑jaj)B(\mathbf a)=\prod_j\Gamma(a_j)/\Gamma(\sum_ja_j). Here nd\mathbf n_d counts the topics in document dd and mk\mathbf m_k counts the words assigned to topic kk:

  2. P(zi=k∣z−i,w) ∝ ndk−i+αNd−i+Kα⋅mkv−i+ηmk⋅−i+VηP(z_i=k\mid\mathbf z_{-i},\mathbf w)\ \propto\ \frac{n^{-i}_{dk}+\alpha}{N^{-i}_d+K\alpha}\cdot\frac{m^{-i}_{kv}+\eta}{m^{-i}_{k\cdot}+V\eta}

    Take token ii, the word vv in document dd, and let a superscript −i-i mean counts with this token removed. Setting zi=kz_i=k raises ndkn_{dk}, NdN_d, mkvm_{kv} and mk⋅m_{k\cdot} by one each, and Γ(x+1)/Γ(x)=x\Gamma(x+1)/\Gamma(x)=x turns every ratio of Gamma functions into a count:

  3. β^kv=mkv+ηmk⋅+Vη,θ^dk=ndk+αNd+Kα\hat\beta_{kv}=\frac{m_{kv}+\eta}{m_{k\cdot}+V\eta},\qquad\hat\theta_{dk}=\frac{n_{dk}+\alpha}{N_d+K\alpha}

    The first denominator does not depend on kk and drops out. Each token is pulled toward topics that are already common in its document and topics in which its word is already common. After sampling, read off the smoothed estimates:

python
import numpy as np

def gibbs_sweep(docs, z, ndk, nkw, nk, alpha, eta, rng):
    """One sweep of collapsed Gibbs sampling for LDA with symmetric priors.
    docs[d]: word ids of document d; z[d]: their topics; ndk, nkw, nk: count arrays."""
    K, V = nkw.shape
    for d, words in enumerate(docs):
        for i, w in enumerate(words):
            k = z[d][i]                                  # remove the token's assignment
            ndk[d, k] -= 1; nkw[k, w] -= 1; nk[k] -= 1
            p = (ndk[d] + alpha) * (nkw[:, w] + eta) / (nk + V * eta)
            k = rng.choice(K, p=p / p.sum())             # sample from the full conditional
            z[d][i] = k
            ndk[d, k] += 1; nkw[k, w] += 1; nk[k] += 1

Each sweep costs O(K)\order{K} per token. Fast samplers exploit sparsity in the counts, and distributed versions split documents across machines.

Check your understanding

A token of word ww sits in a 20-word document. Topic 3 has no other words in this document (nd3=0n_{d3}=0) but contains ww 200 times among its m3⋅=1000m_{3\cdot}=1000 words; topic 1 has nd1=15n_{d1}=15 words here but contains ww only twice among m1⋅=2000m_{1\cdot}=2000. With V=10,000V=10{,}000, η=0.01\eta=0.01 and α=0.1\alpha=0.1, which topic is the token more likely to be assigned to?

  1. Topic 1, by a factor of about 8, because the document is already mostly topic 1
  2. Topic 3, by a factor of about 1.26
  3. Topic 3, by a factor of about 100, because ww is 100 times more frequent in topic 3
  4. Neither: with nd3=0n_{d3}=0, topic 3 has probability zero
Show the answer

B. Topic 3, by a factor of about 1.26

Topic 3: (0+0.1)⋅200.011100≈0.0182(0+0.1)\cdot\frac{200.01}{1100}\approx0.0182. Topic 1: (15+0.1)⋅2.012100≈0.0145(15+0.1)\cdot\frac{2.01}{2100}\approx0.0145. The ratio is about 1.261.26: the strong word–topic association just outweighs the document's preference. With α=0.01\alpha=0.01 the document wins instead, and topic 1 becomes about 7.9 times more likely: smaller α\alpha makes documents stick to the topics they already use.

Variational EM (Blei, Ng & Jordan, 2003) instead fits, for each document, a factorized approximation q(θd,zd)=Dir(θd∣γd)∏nCat(zdn∣ϕdn)q(\boldsymbol\theta_d,\mathbf z_d)=\mathrm{Dir}(\boldsymbol\theta_d\mid\boldsymbol\gamma_d)\prod_n\mathrm{Cat}(z_{dn}\mid\boldsymbol\phi_{dn}) by coordinate ascent on the ELBO. The mean-field rule log⁡q∗(zdn=k)=Eq[log⁡θdk]+log⁡βk,wdn+const\log q^*(z_{dn}=k)=\E_q[\log\theta_{dk}]+\log\beta_{k,w_{dn}}+\text{const}, with Eq[log⁡θdk]=ψ(γdk)−ψ(∑jγdj)\E_q[\log\theta_{dk}]=\psi(\gamma_{dk})-\psi(\sum_j\gamma_{dj}) (ψ\psi is the digamma function), gives

ϕdnk∝βk,wdnexp⁡(ψ(γdk)−ψ(∑jγdj)),γdk=α+∑nϕdnk,\phi_{dnk}\propto\beta_{k,w_{dn}}\exp\Big(\psi(\gamma_{dk})-\psi\big(\textstyle\sum_j\gamma_{dj}\big)\Big),\qquad\gamma_{dk}=\alpha+\sum_n\phi_{dnk},

iterated to convergence per document (the E-step); the M-step sets βkv∝∑d,nϕdnk1{wdn=v}\beta_{kv}\propto\sum_{d,n}\phi_{dnk}\mathbf 1\{w_{dn}=v\}. Asuncion, Welling, Smyth & Teh (2009) found that the differences between these algorithms (and MAP estimation) are mostly due to how much smoothing each applies to the counts, and shrink considerably once hyperparameters are tuned. For millions of documents, stochastic variational inference updates the topics from minibatches (Variational Inference).

What makes a good topic model?

The classic yardstick is held-out perplexity, exp⁡(−∑dlog⁡p(wd)/∑dNd)\exp\big(-\sum_d\log p(\mathbf w_d)/\sum_dN_d\big) over test documents: lower means the model predicts unseen text better. Even this is hard to compute, since p(wd)p(\mathbf w_d) integrates over the unknown θd\boldsymbol\theta_d, and estimators differ in accuracy (Wallach, Murray, Salakhutdinov & Mimno, 2009, compare them).

But people use topic models to read corpora, and Chang, Gerrish, Wang, Boyd-Graber & Blei (2009) measured that directly. In word intrusion, a person sees a topic's top five words plus one word that is improbable in that topic but probable in another, and must spot the intruder; if the topic is coherent, the intruder stands out. In topic intrusion, a person sees a document with its top topics plus one intruder topic. Their finding: models that perform better on held-out likelihood may infer less semantically meaningful topics.

Think first How can a model predict held-out words better and yet produce topics that people find less coherent?

Perplexity rewards probability on every token, frequent and rare alike, so a model gains by spreading topics to cover many small co-occurrence patterns, mixing themes or hedging across them. People judge a topic by its handful of top words and want them to form one theme. The two objectives overlap but are not the same, so optimizing one need not improve the other.

Automated proxies try to capture the human judgment. The UMass coherence of Mimno, Wallach, Talley, Leenders & McCallum (2011) scores a topic's top words v1,…,vMv_1,\dots,v_M by how often they co-occur in documents of the training corpus,

C=∑m=2M∑l=1m−1log⁡D(vm,vl)+1D(vl),C=\sum_{m=2}^M\sum_{l=1}^{m-1}\log\frac{D(v_m,v_l)+1}{D(v_l)},

where D(⋅)D(\cdot) counts documents containing the word(s); Newman, Lau, Grieser & Baldwin (2010) proposed scores based on pointwise mutual information in an external corpus. Proxies have limits of their own: Hoyle and coauthors (2021) found that automated coherence declares winners among neural and classical topic models where human evaluations do not.

Provable learning: anchor words and moments

Gibbs sampling and variational EM come with no guarantee of finding good topics. A different line of work asks for algorithms that provably recover β\boldsymbol\beta in polynomial time, under assumptions about the topics, and uses only low-order statistics of word co-occurrence.

DerivationWhy anchors are the corners of the co-occurrence matrix
  1. P(w2=j∣w1=i)=∑k=1KP(z1=k∣w1=i) P(w2=j∣z1=k)P(w_2=j\mid w_1=i)=\sum_{k=1}^KP(z_1=k\mid w_1=i)\,P(w_2=j\mid z_1=k)

    Take two distinct word positions in the same document, with words w1,w2w_1,w_2 and topics z1,z2z_1,z_2. Given z1z_1, the first word carries no further information about θ\boldsymbol\theta, so w1w_1 and w2w_2 are conditionally independent given z1z_1. Hence each row of the normalized co-occurrence matrix is a mixture:

  2. Qˉi=∑k=1KCik Qˉak,Cik≥0,  ∑kCik=1\bar Q_i=\sum_{k=1}^KC_{ik}\,\bar Q_{a_k},\qquad C_{ik}\ge0,\ \ \sum_kC_{ik}=1

    For an anchor word, P(z1=k∣w1=ak)=1P(z_1=k\mid w_1=a_k)=1, so its row is the topic's co-occurrence profile. Every other row is therefore a convex combination of the KK anchor rows, with weights Cik=P(z1=k∣w1=i)C_{ik}=P(z_1=k\mid w_1=i):

  3. βki=P(w=i∣z=k) ∝ Cik P(w=i)\beta_{ki}=P(w=i\mid z=k)\ \propto\ C_{ik}\,P(w=i)

    The anchors are the vertices of the convex hull of the rows, which a greedy farthest-point search finds. Solving a small simplex-constrained regression per word gives CikC_{ik}, and Bayes' rule turns it into the topics:

This was the first polynomial-time algorithm of its kind, and Arora and coauthors (2013) made it practical, reporting results comparable to the best MCMC implementations while running orders of magnitude faster. A second route is the method of moments: Anandkumar, Foster, Hsu, Kakade & Liu (2012) recover the topics and the Dirichlet prior from low-order moments, estimable from documents of just three words, by a spectral decomposition. In the tensor formulation (Anandkumar, Ge, Hsu, Kakade & Telgarsky, 2014), suitably corrected second- and third-order moments of LDA take the form ∑kwkβk⊗βk\sum_kw_k\boldsymbol\beta_k\otimes\boldsymbol\beta_k and ∑kwk′βk⊗βk⊗βk\sum_kw'_k\boldsymbol\beta_k\otimes\boldsymbol\beta_k\otimes\boldsymbol\beta_k, and an orthogonal tensor decomposition (after whitening, by a robust tensor power method) recovers each βk\boldsymbol\beta_k.

The contrast is instructive. Maximum likelihood is NP-hard in the worst case, already for two topics (Arora, Ge & Moitra, 2012), and so is MAP inference; the anchor and moment algorithms avoid the likelihood altogether, pay with statistical efficiency, and need assumptions (anchors, linearly independent topics) that real corpora satisfy only approximately. In practice their output is often used to initialize likelihood-based refinement.

Key takeaways

  • LDA draws topics βk∼Dir(η)\boldsymbol\beta_k\sim\mathrm{Dir}(\eta) and document proportions θd∼Dir(α)\boldsymbol\theta_d\sim\mathrm{Dir}(\alpha), then a topic and a word for every position: mixed membership, a fixed number of global parameters, and a Bayesian nonnegative factorization of the document–word matrix.
  • Dirichlet hyperparameters below 1 make proportions sparse; conjugacy turns them into pseudo-counts, (ndk+α)/(Nd+Kα)(n_{dk}+\alpha)/(N_d+K\alpha).
  • MAP inference is NP-hard in the worst case (Sontag & Roy), and so is maximum likelihood (Arora, Ge & Moitra). Collapsed Gibbs samples ziz_i with probability ∝(ndk+α)(mkv+η)/(mk⋅+Vη)\propto(n_{dk}+\alpha)(m_{kv}+\eta)/(m_{k\cdot}+V\eta); variational EM alternates digamma-based updates of ϕ\boldsymbol\phi and γ\boldsymbol\gamma with a weighted re-estimate of β\boldsymbol\beta. Tuned hyperparameters shrink the differences between them.
  • Held-out likelihood and human interpretability can disagree (Chang et al., 2009); coherence scores are useful proxies but are not validated universally.
  • Under separability, anchor words are the corners of the word co-occurrence matrix, giving provable polynomial-time recovery; moment and tensor methods recover topics from three-word statistics.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

What does LDA add to pLSI?

  1. Multiple topics per document
  2. Topics as distributions over words
  3. A Dirichlet prior on each document's topic proportions, which are integrated out, giving a fixed number of parameters and a probability for new documents
  4. Word order within documents
Show the answer

C. A Dirichlet prior on each document's topic proportions, which are integrated out, giving a fixed number of parameters and a probability for new documents

pLSI already mixes topics within a document, but its proportions are free parameters per training document, so the parameter count grows with the corpus and an unseen document has no probability under the model. LDA makes θd\boldsymbol\theta_d a random variable with a Dirichlet prior.

Question 2

In collapsed Gibbs sampling for LDA, what is the main effect of lowering the document–topic hyperparameter α\alpha from 1 to 0.01?

  1. Topics become sparser distributions over the vocabulary
  2. Each document concentrates on fewer topics, because a topic absent from a document gets only the tiny pseudo-count α\alpha
  3. The sampler converges in fewer sweeps
  4. The number of topics KK is chosen automatically
Show the answer

B. Each document concentrates on fewer topics, because a topic absent from a document gets only the tiny pseudo-count α\alpha

The document factor in the conditional is ndk+αn_{dk}+\alpha. With small α\alpha, topics already used in the document dominate, so documents end up with sparse topic proportions. Sparsity of topics over words is controlled by η\eta instead.

Question 3

What did "Reading tea leaves" (Chang et al., 2009) find about held-out likelihood?

  1. It perfectly predicts how interpretable people find the topics
  2. It cannot be computed for LDA, so it should not be used
  3. It is the same thing as the word-intrusion score
  4. Models that do better on it may infer less semantically meaningful topics, as measured by word and topic intrusion
Show the answer

D. Models that do better on it may infer less semantically meaningful topics, as measured by word and topic intrusion

Their large user studies showed that human-centered measures capture aspects of model quality that held-out likelihood misses, and that better predictive models sometimes produced less interpretable topics.

Question 4

Why does an anchor word help identify its topic?

  1. It is the most frequent word in the corpus
  2. It occurs only in topic kk, so the distribution of words co-occurring with it equals topic kk's co-occurrence profile, a vertex of the convex hull of all rows
  3. It appears in every document, so it pins down the Dirichlet prior
  4. It is the word with the largest probability in topic kk
Show the answer

B. It occurs only in topic kk, so the distribution of words co-occurring with it equals topic kk's co-occurrence profile, a vertex of the convex hull of all rows

Since P(z=k∣w=ak)=1P(z=k\mid w=a_k)=1, the anchor's normalized co-occurrence row equals P(w2∣z1=k)P(w_2\mid z_1=k). Every other word's row is a convex combination of the anchor rows, so the anchors are the corners, which can be found geometrically; Bayes' rule then gives the topics.

Further reading

  • D. M. Blei, A. Y. Ng & M. I. Jordan, "Latent Dirichlet allocation," Journal of Machine Learning Research 3, 993–1022 (2003).
  • T. L. Griffiths & M. Steyvers, "Finding scientific topics," Proceedings of the National Academy of Sciences 101(suppl. 1), 5228–5235 (2004).
  • J. Chang, S. Gerrish, C. Wang, J. Boyd-Graber & D. M. Blei, "Reading tea leaves: How humans interpret topic models," Advances in Neural Information Processing Systems 22, 288–296 (2009).
  • S. Arora, R. Ge & A. Moitra, "Learning topic models — going beyond SVD," IEEE Symposium on Foundations of Computer Science (2012).
  • D. M. Blei, "Probabilistic topic models," Communications of the ACM 55(4), 77–84 (2012).