Foundations to Frontier
Tests
D. Classical Machine Learning › D14 Topic Models

Latent Dirichlet Allocation (Variational and Gibbs Sampling)

Latent Dirichlet allocation (Blei, Ng and Jordan, 2003) is the canonical topic model. It imagines each document generated by first drawing a mixture of topics from a Dirichlet distribution, then choosing a topic for every word from that mixture and the word from the chosen topic's distribution over the vocabulary. Inverting this process recovers interpretable themes (topics as word distributions) and each document's topic proportions from nothing but word counts. Exact inference is intractable, so two approximations dominate: collapsed Gibbs sampling, which integrates out the topic and document distributions and resamples each word's topic from a simple conditional; and mean-field variational inference, which fits factorised Dirichlet and categorical approximations by coordinate ascent on the ELBO. Practical use hinges on the number of topics K, the Dirichlet priors α and η, and evaluation by held-out perplexity and topic coherence. This page covers the generative model, collapsed Gibbs updates, variational EM, priors and their effect on sparsity, choosing K, evaluation, and extensions. In the exercises you implement both inference methods and recover known topics; then you choose K by document-completion perplexity and study the prior α.

Level 0: Foundation

★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.

Themes hidden in word counts

Read a pile of articles and you sense recurring themes: some talk about rockets and orbits, others about reefs and tides, some about both. Latent Dirichlet allocation (LDA) finds such themes automatically. It assumes each document is a blend of a few topics and each topic favours certain words, then works backwards from which words appear together to estimate the topics and each document’s blend. No one labels anything.

LDA by Gibbs sampling: topics emerge from word co-occurrence
sweep 0/80
■ topic 1:
■ topic 2:
■ topic 3:
At first the labels are random and every topic is a jumble. Within a few sweeps, words that keep appearing in the same documents pull into the same topic, and the three themes appear with no labels given. Small α makes each document concentrate on one or two topics; large α spreads documents across all topics. With K above 3 the extra topics split a theme or soak up the shared filler words.
Why engineers care

Maintenance logs, safety narratives, test reports and anomaly descriptions are large collections of free text. Topic models summarise them into themes, track how themes change over time or fleet, cluster reports for triage, and give compact document features for search and prediction, all without hand-labelled training data.

📝 Quick check (Level 0)
0/3 answered
  1. 1. In LDA, a document is…
  2. 2. A topic is…
  3. 3. LDA learns from…

Level 1: Beginner

★★☆☆☆ Basic⏱ 20 minSecondary-school mathematics: arithmetic and elementary algebra.

The generative story and the Gibbs step by hand

Generative model.

  1. For each topic k, draw a word distribution βₖ ~ Dir(η).
  2. For each document d, draw topic proportions θ_d ~ Dir(α).
  3. For each word position n, draw a topic z_dn ~ Cat(θ_d), then the word w_dn ~ Cat(β_z).

A document’s word distribution is θ_dᵀβ. With topics (½, ½, 0, 0) and (0, 0, ½, ½) and θ = (0.75, 0.25), the words have probabilities 0.375, 0.375, 0.125, 0.125.

Collapsed Gibbs sampling. Integrate out θ and β, and resample each token’s topic given all the others:

p(z = k | rest) ∝ (n_dk + α)(n_kw + η)/(n_k + Vη),

with the current token removed from the counts. Here n_dk counts tokens in d assigned to k, n_kw counts word w in topic k, and n_k is topic k’s total. If k already dominates the document and the word, it gets almost all the probability.

Estimates after sampling. β̂ₖw = (n_kw + η)/(n_k + Vη) and θ̂_dk = (n_dk + α)/(N_d + Kα).

Perplexity. exp(−log-likelihood per token). A uniform model over 60 words has perplexity 60; lower is better.

The steps in plain English:

  1. Tokenise, remove stop words and rare words, and build document–word counts.
  2. Choose K and the priors (α ≈ 0.1 or 50/K, η ≈ 0.01–0.1).
  3. Run Gibbs sweeps or variational EM until the log-likelihood stabilises.
  4. Inspect each topic’s top words and the documents’ proportions; evaluate held-out perplexity and topic coherence.
📝 Quick check (Level 1)
0/3 answered
  1. 1. In the Gibbs conditional, the current token's counts are…
  2. 2. Lower perplexity means…
  3. 3. θ_d is drawn from…

Level 2: Intermediate

★★★☆☆ Intermediate⏱ 30 minUndergraduate students and practising engineers.

Variational inference and the priors

Mean-field variational EM. Approximate the posterior with q(θ_d) = Dir(γ_d), q(z_dn) = Cat(φ_dn) and q(βₖ) = Dir(λₖ). Coordinate ascent on the ELBO gives:

  • φ_dnk ∝ exp(E[log β_k,w] + E[log θ_dk]), with E[log θ_k] = ψ(γ_k) − ψ(Σγ). For γ = (2, 5, 1): (−1.593, −0.510, −2.593).
  • γ_dk = α + Σₙ φ_dnk;
  • λ_kw = η + Σ_d n_dw φ_dwk.

Every update is a vectorised expectation, which makes it fast and deterministic. The stochastic version (online LDA, Hoffman et al., 2010) scales to millions of documents.

Gibbs or variational? Gibbs is simple and asymptotically exact, but stochastic and slower to scale. Variational inference is faster and deterministic, but biased, and tends to underestimate posterior spread. Both find similar topics on typical data.

Priors. Small α (below 1) makes each document concentrate on a few topics; large α spreads documents across topics. Small η makes topics concentrate on fewer words.

Exercise 1 (120 synthetic documents from 4 known topics over 60 words). Cosine similarity of the recovered topics to the true ones:

  • collapsed Gibbs: 0.999, 0.999, 0.999, 0.999;
  • variational EM: 0.998, 0.999, 0.999, 0.999.

Both recovered the generating topics almost exactly.

from sklearn.decomposition import LatentDirichletAllocation
lda = LatentDirichletAllocation(n_components=4, doc_topic_prior=0.1, topic_word_prior=0.05, learning_method="batch").fit(counts)
theta = lda.transform(counts); topics = lda.components_ / lda.components_.sum(1, keepdims=True)
🐍 Exercise 1: Gibbs and variational LDA
Generate a corpus from known topics, then recover them with collapsed Gibbs sampling and with mean-field variational EM; match recovered to true topics by cosine similarity.
📝 Quick check (Level 2)
0/3 answered
  1. 1. E[log θ_k] under Dir(γ) is…
  2. 2. Variational inference compared with Gibbs is…
  3. 3. Small α makes documents…

Level 3: Advanced

★★★★☆ Advanced⏱ 25 minGraduate level, with full derivations and proofs.

Theory

Why integrate out? Under the Dirichlet–multinomial conjugacy, integrating θ and β gives closed-form Pólya-urn conditionals: a word joins topic k in proportion to how often that topic is already used in the document and how often it has produced the word. Collapsed samplers mix much faster than samplers that also draw θ and β.

ELBO. log p(w | α, η) ≥ E_q[log p(w, z, θ, β)] − E_q[log q], and coordinate ascent increases it monotonically. Variational EM can also optimise α and η.

Evaluation pitfalls.

  • Perplexity can keep falling as K grows, while topics become less interpretable. Chang et al. (2009) showed that perplexity and human judgements of topic quality can disagree.
  • Topic coherence (NPMI or UMass scores) correlates better with human ratings.
  • Held-out likelihood must be estimated carefully, for example by document completion or importance sampling.

Extensions.

  • Correlated topic models, with a logistic-normal prior.
  • Dynamic topic models, with topics evolving over time.
  • Supervised LDA.
  • Hierarchical Dirichlet processes, which infer K.
  • Neural topic models and embedding-based approaches (BERTopic).

Interview questions.

  • How do you choose the number of topics? Combine held-out perplexity, which identifies underfitting, with coherence and human inspection, which identify usefulness; check stability across random seeds; or use an HDP.
  • Why do topic models produce junk topics? Uninformative frequent words, too large a K, or too few iterations. Remove stop words, and check coherence and stability.
📝 Quick check (Level 3)
0/3 answered
  1. 1. Collapsed Gibbs mixes faster because…
  2. 2. Chang et al. found perplexity and human topic quality…
  3. 3. A hierarchical Dirichlet process lets the model…

Level 4: Expert

★★★★★ Expert⏱ 25 minResearchers: original papers and open problems.

How many topics, and what does α do?

History.

  • D. Blei, A. Ng and M. Jordan (2003) introduced LDA.
  • T. Griffiths and M. Steyvers (2004) introduced collapsed Gibbs sampling for LDA.
  • M. Hoffman, D. Blei and F. Bach (2010) introduced online variational LDA.
  • J. Chang et al. (2009) studied the interpretability of topics.
  • Y. W. Teh et al. (2006) introduced hierarchical Dirichlet processes.

Exercise 2. 150 training and 60 test documents generated from 4 true topics over 60 words. Document-completion perplexity: θ is inferred from half of each test document’s words, and the other half is scored.

K 2 3 4 6 10 true topics
perplexity 14.25 12.27 9.13 9.14 9.33 9.10

With K = 4 fixed, varying the prior α:

α perplexity mean largest topic share per document
0.01 9.21 0.862
0.1 9.13 0.858
1.0 9.42 0.809
  • Perplexity fell steeply up to the true K = 4, then flattened, and rose slightly at K = 10. The model with K = 4 came within 0.03 of the true topics (9.13 against 9.10).
  • Extra topics barely hurt perplexity: the elbow, not the minimum, identifies K. In real data the curve often keeps creeping down, which is why coherence and inspection are needed.
  • α controlled document sparsity: α = 1 spread documents more evenly (largest topic share 0.81 against 0.86) and fitted worse than the generating value of 0.1.
🐍 Exercise 2 (research): choosing K and α
Fit variational LDA with K = 2–10 to documents from 4 true topics and compare document-completion perplexity; then vary α at K = 4 and record perplexity and document-topic sparsity.

Topic models in AI, robotics and aerospace

  • Maintenance and safety text: themes in pilot reports, work orders and incident narratives, tracked over time and fleets.
  • Anomaly triage: clustering free-text anomaly reports so that similar issues reach the same engineer.
  • Document features: topic proportions as compact inputs to classifiers and search.

References

  1. D. M. Blei, A. Y. Ng, M. I. Jordan (2003). “Latent Dirichlet allocation.” Journal of Machine Learning Research 3.
  2. T. L. Griffiths, M. Steyvers (2004). “Finding scientific topics.” PNAS 101(suppl. 1).
  3. M. Hoffman, D. M. Blei, F. Bach (2010). “Online learning for latent Dirichlet allocation.” Advances in NeurIPS 23.
  4. J. Chang, J. Boyd-Graber, S. Gerrish, C. Wang, D. M. Blei (2009). “Reading tea leaves: how humans interpret topic models.” Advances in NeurIPS 22.
  5. Y. W. Teh, M. I. Jordan, M. J. Beal, D. M. Blei (2006). “Hierarchical Dirichlet processes.” Journal of the American Statistical Association 101(476).