Sub topic 6
Fitting LDA: Variational Bayes and Gibbs Sampling
This chapter assumes you know the LDA generative process, the roles of the document-topic distribution (theta) and topic-word distribution (phi), and the Dirichlet priors alpha and eta. You should also be comfortable reading Python and NumPy. It explains how a library turns a corpus into fitted topics, and which settings control that process.
Why fitting LDA needs approximation
The generative story runs from topics to words. Fitting runs the other way. You observe the words and want the posterior over the hidden variables: the topic assignment z of every token, plus theta and phi. By Bayes' rule, the posterior is the joint probability divided by the probability of the corpus. That denominator sums over every possible assignment of topics to tokens, which is exponentially many. Exact inference is intractable.
Two families of approximation are in common use:
- Variational Bayes (VB) replaces the posterior with a simpler distribution and optimises it. The result is a deterministic, fast, and sometimes biased approximation.
- Gibbs sampling draws samples from the true posterior with a Markov chain. It is asymptotically exact but slower, and you must decide when the chain has run long enough.
gensim's LdaModel uses online variational Bayes. MALLET and tomotopy use Gibbs sampling.
Variational Bayes
Mean-field VB approximates the posterior with a factorised distribution q. Each document gets its own variational parameters (gamma, for its topic mixture), and each topic gets its own (lambda, for its word distribution). Fitting maximises the evidence lower bound (ELBO), a quantity that rises as q gets closer to the true posterior.
The algorithm alternates two steps, similar to EM:
- E-step. Hold the topics fixed. For each document, update gamma and the per-token topic responsibilities until gamma stops changing.
- M-step. Hold the document statistics fixed. Update lambda from the expected word-topic counts.
gensim uses the online variant of Hoffman et al. (2010). It processes the corpus in chunks. After each chunk it blends the new topic estimate into the old one with a step size that shrinks over time. This keeps memory use constant and lets you train on corpora that do not fit in RAM.
| Parameter | What it controls |
|---|---|
| `chunksize` | Documents per E-step batch |
| `update_every` | Chunks between M-steps. `1` is online, `0` is batch |
| `passes` | Full sweeps over the corpus |
| `iterations` | Maximum E-step loops per document |
| `gamma_threshold` | E-step stops early when gamma changes less than this |
| `decay`, `offset` | How fast the step size shrinks. `decay` is in (0.5, 1] |
| `random_state` | Seed for the random initialisation of lambda |
import logging
from gensim import corpora
from gensim.models import LdaModel
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.INFO)
docs = [
["goal", "match", "player", "team", "season"],
["election", "vote", "party", "government", "policy"],
["team", "coach", "league", "season", "win"],
["minister", "government", "vote", "law", "policy"],
]
dictionary = corpora.Dictionary(docs)
corpus = [dictionary.doc2bow(doc) for doc in docs]
lda = LdaModel(
corpus=corpus,
id2word=dictionary,
num_topics=2,
chunksize=2,
update_every=1,
passes=20,
iterations=100,
gamma_threshold=0.001,
eval_every=1,
random_state=42,
)
print(lda.log_perplexity(corpus))With logging on, gensim reports the per-word bound and how many documents converged in each E-step. If many documents hit iterations without converging, raise iterations.
Gibbs sampling
Gibbs sampling visits one hidden variable at a time and resamples it from its conditional distribution given everything else. For LDA, theta and phi can be integrated out analytically. This is called collapsed Gibbs sampling, and only the topic assignments z remain. The conditional for one token with word w in document d is:
p(z = k | everything else) ∝ (ndk + alpha) × (nkw + eta) / (n_k + V × eta)
All counts exclude the token being resampled:
- n_dk is the number of tokens in document d assigned to topic k.
- n_kw is the number of times word w is assigned to topic k.
- n_k is the total number of tokens assigned to topic k.
- V is the vocabulary size.
The first factor favours topics that the document already uses. The second favours topics that already explain this word. Alpha and eta act as smoothing counts.
Here is a complete sampler. It is meant for understanding, not speed.
import numpy as np
docs_text = [
["goal", "match", "player", "team", "season"],
["election", "vote", "party", "government", "policy"],
["team", "coach", "league", "season", "win"],
["minister", "government", "vote", "law", "policy"],
]
vocab = sorted({w for d in docs_text for w in d})
word_id = {w: i for i, w in enumerate(vocab)}
docs = [[word_id[w] for w in d] for d in docs_text]
def gibbs_lda(docs, vocab_size, num_topics, alpha=0.1, eta=0.01, iters=300, seed=0):
rng = np.random.default_rng(seed)
n_dk = np.zeros((len(docs), num_topics))
n_kw = np.zeros((num_topics, vocab_size))
n_k = np.zeros(num_topics)
z = []
for d, doc in enumerate(docs):
zs = rng.integers(num_topics, size=len(doc))
z.append(zs)
for w, k in zip(doc, zs):
n_dk[d, k] += 1
n_kw[k, w] += 1
n_k[k] += 1
for _ in range(iters):
for d, doc in enumerate(docs):
for i, w in enumerate(doc):
k = z[d][i]
n_dk[d, k] -= 1
n_kw[k, w] -= 1
n_k[k] -= 1
p = (n_dk[d] + alpha) * (n_kw[:, w] + eta) / (n_k + vocab_size * eta)
k = rng.choice(num_topics, p=p / p.sum())
z[d][i] = k
n_dk[d, k] += 1
n_kw[k, w] += 1
n_k[k] += 1
phi = (n_kw + eta) / (n_k[:, None] + vocab_size * eta)
theta = (n_dk + alpha) / (n_dk.sum(axis=1, keepdims=True) + num_topics * alpha)
return theta, phi
theta, phi = gibbs_lda(docs, len(vocab), num_topics=2)
for k in range(2):
top = np.argsort(phi[k])[::-1][:5]
print(k, [vocab[i] for i in top])
print(theta.round(2))Each token is removed from the counts, resampled, and added back. Forgetting the removal step is a common bug. The token then votes for its own current topic, and the chain gets stuck.
The chain starts from random assignments, so early samples are poor. Practitioners discard a burn-in period. They then either keep the final state or average over several well-spaced samples. Library implementations such as MALLET add optimisations like sparse updates, and they can also re-estimate alpha during sampling.
Choosing between them
| Row | Online variational Bayes | Collapsed Gibbs |
|---|---|---|
| Result | Deterministic given a seed | Random sample from the posterior |
| Speed on large corpora | Fast, streams data | Slower per sweep, needs all counts in memory |
| Topic quality | Often a bit lower | Often a bit higher, especially for small corpora |
| Convergence check | ELBO and gamma convergence | No definite test, inspect stability |
| Tool | gensim `LdaModel`, `LdaMulticore` | MALLET, tomotopy |
gensim 4 removed its MALLET wrapper, so using MALLET now means running its command-line tool yourself.
Common errors
- Too few passes on a small corpus. With one pass and few documents, the online updates never settle. Use many passes for small corpora.
- Large
chunksizeon a small corpus. Ifchunksizeis at least the corpus size, there is one update per pass, which behaves like batch VB. This is acceptable, but thenpassesmatters more. - Comparing perplexity across setups. The bound from
log_perplexitydepends on the vocabulary and the preprocessing. Compare it only between models trained on the same corpus. Use coherence to judge topic quality. - No fixed seed. Both methods start from random values. Without a seed, topics differ between runs, and topic numbers can swap (label switching). Compare runs by words, not by index.
- Expecting
alpha="auto"everywhere.LdaMulticoredoes not support learned or asymmetric alpha. UseLdaModelfor that.
Exercise
In the collapsed Gibbs sampler, why must the current token be removed from ndk, nkw and n_k before the new topic is sampled?
Show answer
The conditional probability is defined given all other assignments. If the token still counted, its own current topic would get extra weight in all three counts. The sampler would then favour keeping each token's current topic, so the chain would mix poorly and could stay near its random start.
Exercise
A gensim LDA run on a 500-document corpus gives different topics each time you run it. Name two causes and one fix for each.
Show answer
First, a random initialisation with no seed. Fix it by setting random_state. Second, too few passes or iterations, so the model has not converged and the starting point still shows in the result. Fix it by raising passes and iterations until the bound stops improving.