Sub topic 5
How LDA imagines documents being written
This chapter assumes you know basic probability (distributions, sampling, conditional probability) and what a bag-of-words count matrix is. Dirichlet priors get a short recap here and a fuller treatment in their own chapter.
Latent Dirichlet Allocation (LDA) is a generative model. It does not read documents and extract themes directly. It tells a made-up story about how documents could have been produced, and then training asks which version of that story best explains the documents you actually have. Once you understand the story, the outputs of gensim's LdaModel (topic-word lists, per-document topic mixtures) have a clear meaning.
The two distributions that matter
LDA has two kinds of probability distribution. Everything else is machinery around them.
- Topic-word distribution (often written φ, or "beta" in gensim). Each topic is a probability distribution over the whole vocabulary. A "sports" topic gives high probability to team, season and goal, and near-zero probability to vote. There are K of these, one per topic.
- Document-topic distribution (θ, "theta"). Each document has its own distribution over the K topics. A document might be 70% topic 0 and 30% topic 1. There is one θ per document.
A topic in LDA is therefore not a label or a cluster of documents. It is a list of word probabilities. A document does not belong to one topic. It mixes several.
| Symbol | Shape | Meaning |
|---|---|---|
| K | scalar | Number of topics, chosen by you |
| V | scalar | Vocabulary size |
| φ (phi) | K × V | Row k is topic k's distribution over words |
| θ (theta) | D × K | Row d is document d's distribution over topics |
| α (alpha) | scalar or length K | Dirichlet prior on each θ |
| η (eta) | scalar or length V | Dirichlet prior on each row of φ |
| z | per word | The topic assigned to one word position |
| w | per word | The observed word at that position |
The generative process
The story has two parts: one done once for the corpus, and one repeated for every document.
- For each topic k = 1..K, draw a word distribution φ_k from Dirichlet(η).
- For each document d:
- Draw a topic mixture θ_d from Dirichlet(α).
- For each word position in the document:
- Draw a topic z from θ_d.
- Draw a word w from φ_z.
Step 2.2.1 picks a topic, and step 2.2.2 picks a word from that topic. Each word is explained by its own topic, so one document can contain words from several topics.
Only w is observed. The variables θ, φ and z are latent, which is the "Latent" in the name. Training works backwards from the observed words to estimate them.
Role of the Dirichlet priors
A Dirichlet distribution produces probability vectors that sum to 1. Its concentration parameter controls how spread out those vectors are.
- α below 1 gives sparse document mixtures. Each document concentrates on a few topics.
- α above 1 gives mixtures close to uniform. Every document uses most topics.
- η below 1 gives topics concentrated on a few words. Larger η gives flatter, blurrier topics.
These are priors, meaning beliefs about the shape of θ and φ before seeing data. Real documents usually cover few topics and real topics use few characteristic words, so values below 1 are a common starting point.
Running the story forwards
The code below samples a tiny corpus from the generative process. It uses only NumPy. Real training does the reverse, but seeing the forward direction makes the model concrete.
import numpy as np
rng = np.random.default_rng(42)
vocab = ["goal", "team", "season", "vote", "party", "policy", "law", "coach"]
K = 2 # number of topics
V = len(vocab)
alpha = 0.3 # sparse document-topic mixtures
eta = 0.2 # fairly peaked topic-word distributions
# Step 1: one word distribution per topic (K x V matrix)
phi = rng.dirichlet(np.full(V, eta), size=K)
for k in range(K):
top = np.argsort(phi[k])[::-1][:3]
print(f"topic {k} top words:", [vocab[i] for i in top])
# Step 2: generate three documents
for d in range(3):
theta = rng.dirichlet(np.full(K, alpha)) # topic mixture of this document
n_words = rng.poisson(8) + 1 # document length, at least 1
z = rng.choice(K, size=n_words, p=theta) # topic for each position
w = [vocab[rng.choice(V, p=phi[k])] for k in z]
print(f"doc {d}: theta={np.round(theta, 2)}")
print(" topics:", z.tolist())
print(" words: ", w)The topics here are random, so the word lists will not look like "sports" or "politics". The code shows the structure: each document has its own θ, each position gets a topic from that θ, and each word comes from that topic's φ row. Real training reverses this, choosing φ and θ so the observed words become likely.
Running the story backwards
Training receives only w, the word counts. It must infer φ for every topic, θ for every document, and implicitly z for every word. It looks for parameters under which the observed corpus has high probability. The exact posterior is intractable, so practical systems approximate it with variational Bayes (gensim's method) or Gibbs sampling. Those methods are covered in a later chapter.
What you receive from gensim after training maps directly onto the story:
lda.get_topics()returns φ, a K × V matrix.lda.get_document_topics(bow)returns θ for one document.lda.print_topics()shows the highest-probability words of each φ row.
The bag-of-words assumption
The story draws each word independently given its topic. Word order never enters. The model is exchangeable: shuffling the words in a document does not change its probability. This is why LDA takes a bag-of-words input and why it cannot tell "dog bites man" from "man bites dog". Context, negation and phrase structure are all invisible to it, unless you build phrases into tokens during preprocessing.
Common errors when reading LDA output
- Treating θ as a hard class. A document with θ = [0.55, 0.45] is not "topic 0". Taking the argmax discards information, and for flat mixtures it is nearly arbitrary.
- Assuming topics are ordered or stable. Topic numbering depends on random initialisation. Two runs with different seeds can produce the same themes under different indices. Set
random_statewhen you need repeatable runs. - Reading probabilities as importance across topics. A word's probability within a topic is not comparable to its probability in another topic's row without care. A word frequent in the whole corpus tends to rank highly in many topics.
- Expecting K to be discovered. LDA does not find the number of topics. You choose K, then judge the result, which is the subject of the evaluation chapter.
- Confusing α and η. α shapes document mixtures (θ). η shapes topic word lists (φ). Changing α alters how many topics each document uses. Changing η alters how focused each topic is.
What the story cannot say
The story has no concept of topic correlation. With a Dirichlet prior on θ, knowing a document uses "cooking" tells you almost nothing about whether it also uses "nutrition". It also fixes K in advance, and it assumes each word is explained by exactly one topic. These assumptions become the limitations discussed later in the tutorial.
Exercise
In the generative process, a document has θ = [0.9, 0.1] over two topics and contains 100 words. Roughly how many words come from topic 1, and does that mean the document "is about" topic 0? What changes if α is raised from 0.1 to 10 for a corpus of such documents?
Show answer
About 10 words come from topic 1 (100 × 0.1), though the exact number varies by sampling because each position draws its topic independently. The document is mostly topic 0, but LDA treats it as a mixture, so calling it "about" topic 0 only is a simplification. Raising α from 0.1 to 10 makes document mixtures much closer to uniform, so typical θ vectors would look like [0.5, 0.5] instead of lopsided values like [0.9, 0.1]. Each document would then draw on all topics in similar proportions.