Course contents 12 / 15

12 / 15 · Nonparametric and Topic Models

Latent Dirichlet allocation

Topic models: each document a mixture of topics shared by the corpus, fitted by collapsed Gibbs sampling or mean-field variational inference, with the role of the Dirichlet priors and how topics are evaluated.

On this page 8

An article about the transfer market of a football club uses the vocabulary of sports and of money in the same paragraph. A thousand other articles use the same two vocabularies in other proportions, and a few more besides: politics, medicine, weather. Given only the words, can we recover the vocabularies, and say for each article how much of each it uses?

The Dirichlet process mixture gave every data point exactly one cluster, and so cannot answer. Latent Dirichlet allocation (LDA) of Blei, Ng and Jordan (2003) can. It has a set of topics, each a distribution over words, shared by the whole collection, and for every document its own mixture of them. The number of topics is fixed in advance, so LDA is a parametric model; it sits beside the Dirichlet process because it is built from the same Dirichlet–categorical blocks, is fitted by the same kind of collapsed sampler, and becomes nonparametric when its topics are drawn from a hierarchical Dirichlet process (Teh et al., 2006).

One topic per document is not enough#

Treat each document as a bag of words, its word order ignored. The simplest probabilistic model of such bags is a mixture of unigrams (Nigam et al., 2000): pick one topic kk for the whole document with probability πk\pi_k, then draw all its words from that topic’s distribution ϕk\phi_k over the vocabulary,

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}} ,

where wdnw_{dn} is the nn-th of the NdN_d words of document dd. It is the finite mixture of the Dirichlet process note with documents as the points, and the 4F13 course fits it by EM before moving to LDA.

It fails on documents that mix subjects. Take the two topics of the figure below, sports and economics, and the three-word document “team goal market”. Sports gives these words the probabilities 0.340.34, 0.300.30 and 0.020.02; economics gives them 0.020.02, 0.020.02 and 0.340.34. The best single topic, sports, must produce “market”, to which it gives 2%. A document-specific mixture with proportions 0.70.7 and 0.30.3 gives each word the probability 0.7 ϕ1w+0.3 ϕ2w0.7\,\phi_{1w} + 0.3\,\phi_{2w}, for “team” 0.7⋅0.34+0.3⋅0.02=0.2440.7 \cdot 0.34 + 0.3 \cdot 0.02 = 0.244:

sports alone:0.34⋅0.30⋅0.02=0.00204,mixture:0.244⋅0.216⋅0.116=0.0061.\begin{aligned} \text{sports alone:}\quad & 0.34 \cdot 0.30 \cdot 0.02 = 0.00204, \\ \text{mixture:}\quad & 0.244 \cdot 0.216 \cdot 0.116 = 0.0061 . \end{aligned}

The mixture explains the document three times better. (This toy comparison fixes the proportions; LDA puts a prior on them.)

The probabilistic latent semantic analysis of Hofmann (1999) gives each training document its own proportions, but as parameters. Their number grows with the corpus and they overfit, and a new document has no proportions at all. LDA makes the proportions random, with a Dirichlet prior, which fixes both problems (Blei, Ng and Jordan, 2003, Section 4.3).

The generative story#

LDA describes how a corpus could have been produced. With KK topics over a vocabulary of VV words, and symmetric Dirichlet priors with parameters α\alpha and β\beta:

  1. For each topic k=1,…,Kk = 1, \dots, K, draw its word distribution ϕk∼Dir(β,…,β)\phi_k \sim \mathrm{Dir}(\beta, \dots, \beta).
  2. For each document d=1,…,Dd = 1, \dots, D, draw its topic proportions θd∼Dir(α,…,α)\theta_d \sim \mathrm{Dir}(\alpha, \dots, \alpha).
  3. For each position nn of document dd, draw a topic zdn∼Categorical(θd)z_{dn} \sim \mathrm{Categorical}(\theta_d),
  4. and then the word wdn∼Categorical(ϕzdn)w_{dn} \sim \mathrm{Categorical}(\phi_{z_{dn}}).
Figure

How LDA generates a document

The generative process of LDALeft, two topics as bars of probability over six words; middle, a bar of the document topic proportions; right, the eight words of the document, coloured by topic.1topic 1: sportstopic 2: economicsmatch0.300.02goal0.300.02team0.340.02price0.020.30market0.020.34bank0.020.302proportions0.70.3θddocument dteamgoalmarketmatchgoalbankteammatch34p(goal | d) = 0.7 · 0.30 + 0.3 · 0.02 = 0.216The generative process of LDAAt the top, two topics as bars of probability over six words; below, a bar of the document topic proportions and the eight words of the document, coloured by topic.1topic 1: sportstopic 2: economicsmatch0.30goal0.30team0.34price0.30market0.34bank0.302proportions θ0.70.33document dteamgoalmarketmatchgoalbankteammatch4a word from the chosen topicp(goal | d) = 0.7 · 0.30 + 0.3 · 0.02 = 0.216
Two topics over a vocabulary of six words (1) and one document with topic proportions 0.7 and 0.3 (2). For each of its eight positions a topic is drawn (3), then a word from that topic (4). A word’s probability mixes the topics with the document’s proportions: p(goal | d) = 0.7 · 0.30 + 0.3 · 0.02 = 0.216.
SymbolMeaning
ϕkw\phi_{kw}probability of word ww in topic kk
θdk\theta_{dk}share of topic kk in document dd
zdnz_{dn}topic of the nn-th word of document dd
ndkn_{dk}words of document dd assigned to topic kk
nkwn_{kw}occurrences of word ww assigned to topic kk, over the corpus
nkn_kall words assigned to topic kk, ∑wnkw\sum_w n_{kw}

The joint distribution of everything is the product of the four steps:

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

Summing out the topic of one word gives the probability of the word in its document,

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

so the D×VD \times V matrix of word probabilities per document is the product of a D×KD \times K matrix of proportions and a K×VK \times V matrix of topics. LDA is a probabilistic, non-negative low-rank factorization of the document–word matrix, an admixture or mixed-membership model in which a document belongs partly to several clusters (Murphy, 2023, Section 28.5.1). In the figure, p(goal∣d)=0.7⋅0.30+0.3⋅0.02=0.216p(\text{goal} \mid d) = 0.7 \cdot 0.30 + 0.3 \cdot 0.02 = 0.216.

Geometrically, every distribution over the vocabulary is a point of the word simplex, and the KK topics span a smaller topic simplex inside it. The mixture of unigrams puts each document at a corner of the topic simplex; pLSA puts each training document at a fixed point inside it; LDA places a smooth Dirichlet-shaped density over it, so a new document can land anywhere (Blei, Ng and Jordan, 2003, Section 4.4).

The form is not arbitrary. Suppose the order of words carries no information, in the strong sense of infinite exchangeability: for every length, the joint probability of a sequence is unchanged by any permutation of it. Then de Finetti’s theorem says that the joint distribution is a mixture of independent draws given some latent parameter: draw hidden word frequencies once, then sample the words independently from them (Teh, 2010, section “Predictive Distribution and the Blackwell-MacQueen Urn Scheme”, states it as an integral over a random distribution). For a finite document the representation holds only approximately; the theorem itself needs measure theory beyond the course.

LDA takes that parameter to be θd\theta_d and gives it a Dirichlet distribution (Blei, Ng and Jordan, 2003, Section 3.1). The Dirichlet process mixture had one level of sharing: points share clusters. LDA has two: words share topics within a document through θd\theta_d, and documents share topics through the common ϕ\phi.

Inference: the posterior over topic assignments#

The quantity of interest is the posterior p(z,θ,ϕ∣w)p(z, \theta, \phi \mid w): which topic each word belongs to, what the topics are, and what each document is about. Its normalizer sums over K∑dNdK^{\sum_d N_d} assignments and has no closed form. The two standard approximations are the collapsed Gibbs sampler of Griffiths and Steyvers (2004) and the variational method of the original paper.

Collapsed Gibbs sampling#

Both θ\theta and ϕ\phi can be integrated out, because each appears only in a Dirichlet prior and in categorical terms: the Dirichlet–categorical conjugacy of the conjugate priors note. Write B(a)=∏jΓ(aj)/Γ(∑jaj)B(a) = \prod_j \Gamma(a_j) / \Gamma(\sum_j a_j) for the normalizer of a Dirichlet, so that ∫∏jπjaj−1 dπ=B(a)\int \prod_j \pi_j^{a_j - 1}\, d\pi = B(a). Collecting the factors that contain each θd\theta_d and each ϕk\phi_k, we integrate them one at a time. For one document, by the definition of BB,

∫Dir(θd∣α)∏n=1Ndθdzdn dθd=1B(α)∫∏k=1Kθdkα+ndk−1 dθd=B(nd⋅+α)B(α),\begin{aligned} \int \mathrm{Dir}(\theta_d \mid \alpha) \prod_{n=1}^{N_d} \theta_{d z_{dn}}\, d\theta_d &= \frac{1}{B(\alpha)} \int \prod_{k=1}^K \theta_{dk}^{\alpha + n_{dk} - 1}\, d\theta_d \\ &= \frac{B(n_{d\cdot} + \alpha)}{B(\alpha)} , \end{aligned}

and each topic gives the same with β\beta and the word counts nk⋅n_{k\cdot}. The product over documents and topics is

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)} ,

a function of the counts alone, with nd⋅=(nd1,…,ndK)n_{d\cdot} = (n_{d1}, \dots, n_{dK}) and nk⋅=(nk1,…,nkV)n_{k\cdot} = (n_{k1}, \dots, n_{kV}). The sampler monitors this quantity.

The sampler resamples one token’s topic at a time. Let token ii be word vv in document dd, and let a superscript −i-i mean “counted without token ii”. Bayes’ rule splits the conditional into a prior for ziz_i given the other topics and a likelihood for its word. The topic of token ii depends on the other topics only through θd\theta_d, and its word depends on the other tokens only through ϕk\phi_k, so each factor averages one parameter over its posterior:

p(zi=k∣z−i,w)∝p(zi=k∣z−i)⋅p(wi=v∣zi=k,z−i,w−i)=∫θdk p(θd∣z−i) dθd⋅∫ϕkv p(ϕk∣z−i,w−i) dϕk=E[θdk∣z−i]  E[ϕkv∣z−i,w−i].\begin{aligned} p(z_i = k \mid z_{-i}, w) &\propto p(z_i = k \mid z_{-i}) \\ &\quad \cdot p(w_i = v \mid z_i = k, z_{-i}, w_{-i}) \\ &= \int \theta_{dk}\, p(\theta_d \mid z_{-i})\, d\theta_d \\ &\quad \cdot \int \phi_{kv}\, p(\phi_k \mid z_{-i}, w_{-i})\, d\phi_k \\ &= \mathbb E\big[\theta_{dk} \mid z_{-i}\big]\; \mathbb E\big[\phi_{kv} \mid z_{-i}, w_{-i}\big] . \end{aligned}

Each factor is the posterior mean of a Dirichlet: θd\theta_d given the other topics of document dd is Dir(α+nd⋅−i)\mathrm{Dir}(\alpha + n_{d\cdot}^{-i}), and ϕk\phi_k given the other words assigned to topic kk is Dir(β+nk⋅−i)\mathrm{Dir}(\beta + n_{k\cdot}^{-i}). By the predictive formula of the conjugate priors note, the posterior mean of a Dir(a)\mathrm{Dir}(a) component is ak/∑jaja_k / \sum_j a_j. The denominator of the first, Nd−1+KαN_d - 1 + K\alpha, does not depend on kk, so

 p(zi=k∣z−i,w)  ∝  (ndk−i+α) nkv−i+βnk−i+Vβ \boxed{\ 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} \ }

(Griffiths and Steyvers, 2004, Eq. 5; the 4F13 course derives it this way). The same result follows from the ratio of p(w,z)p(w, z) at zi=kz_i = k and at its removal, since only three counts change by one.

The two factors read naturally: how much document dd already uses topic kk, and how often topic kk already produces word vv, each smoothed by its prior. A sweep visits every token, removes it from the counts, draws a new topic and adds it back: O(K)O(K) work per token, with nothing but integer counts in memory. After the chain has mixed, a sample of zz estimates the integrated-out quantities by the same posterior means:

ϕ^kw=nkw+βnk+Vβ,θ^dk=ndk+αNd+Kα.\begin{aligned} \hat\phi_{kw} &= \frac{n_{kw} + \beta}{n_k + V\beta}, \\ \hat\theta_{dk} &= \frac{n_{dk} + \alpha}{N_d + K\alpha} . \end{aligned}

This is the twin of the restaurant sampler of the previous note. There a point was reseated in proportion to the cluster’s size times its predictive density; here a token is reassigned in proportion to the document’s use of a topic times the topic’s predictive probability of the word.

Take a token of the word “goal” in a document whose other words are 4 in topic 1 and 2 in topic 2. Over the corpus, topic 1 has 500 tokens, 30 of them “goal”; topic 2 has 400 tokens, 2 of them “goal”. With V=1000V = 1000, α=0.1\alpha = 0.1 and β=0.01\beta = 0.01, the unnormalized weights are

topic 1:4.1⋅30.01510=0.2413,topic 2:2.1⋅2.01410=0.0103,\begin{aligned} \text{topic 1:}\quad & 4.1 \cdot \tfrac{30.01}{510} = 0.2413, \\ \text{topic 2:}\quad & 2.1 \cdot \tfrac{2.01}{410} = 0.0103 , \end{aligned}

and the token goes to topic 1 with probability 0.9590.959.

Topics are interchangeable, so the posterior has K!K! relabelled copies of every mode. A single chain stays in one of them and gives consistent labels, but averaging ϕ^\hat\phi over several chains is meaningless without matching the topics first.

The variational alternative#

The original paper took the other route of this course, mean-field variational inference. With a Dirichlet prior on the topics, as in its Section 5.4, the factorized family is

q(θ,z,ϕ)=∏kDir(ϕk∣λk)⋅∏d(Dir(θd∣γd)∏nCategorical(zdn∣rdn)).\begin{aligned} q(\theta, z, \phi) ={}& \prod_{k} \mathrm{Dir}(\phi_k \mid \lambda_k) \\ &\cdot \prod_d \Big( \mathrm{Dir}(\theta_d \mid \gamma_d) \prod_n \mathrm{Categorical}(z_{dn} \mid r_{dn}) \Big) . \end{aligned}

Each factor’s update is the exponentiated expected log joint under the others. The expectations needed are those of logarithms of Dirichlet variables, a property of the exponential family:

Eq[log⁡θdk]=ψ(γdk)−ψ(∑jγdj),\mathbb E_q[\log \theta_{dk}] = \psi(\gamma_{dk}) - \psi\Big(\sum_j \gamma_{dj}\Big) ,

with ψ\psi the digamma function, and the same for ϕ\phi. The reason: Dir(θ∣γ)\mathrm{Dir}(\theta \mid \gamma) is an exponential family with sufficient statistics log⁡θk\log \theta_k, natural parameters γk−1\gamma_k - 1 and log-partition function A(γ)=∑klog⁡Γ(γk)−log⁡Γ(∑jγj)A(\gamma) = \sum_k \log\Gamma(\gamma_k) - \log\Gamma(\sum_j \gamma_j). The expected sufficient statistic is the gradient of AA (conjugate priors note), and ∂A/∂γk=ψ(γk)−ψ(∑jγj)\partial A/\partial \gamma_k = \psi(\gamma_k) - \psi(\sum_j \gamma_j). The updates are

rdnk∝exp⁡(Eq[log⁡θdk]+Eq[log⁡ϕkwdn]),γdk=α+∑nrdnk,λkw=β+∑d,nrdnk [wdn=w].\begin{aligned} r_{dnk} &\propto \exp\big(\mathbb E_q[\log \theta_{dk}] + \mathbb E_q[\log \phi_{k w_{dn}}]\big), \\ \gamma_{dk} &= \alpha + \textstyle\sum_{n} r_{dnk}, \\ \lambda_{kw} &= \beta + \textstyle\sum_{d, n} r_{dnk}\, [w_{dn} = w] . \end{aligned}
Derivation of the three updates

In the log joint, zdnz_{dn} appears only in log⁡θdzdn+log⁡ϕzdnwdn\log \theta_{d z_{dn}} + \log \phi_{z_{dn} w_{dn}}, so averaging over the other factors gives log⁡q∗(zdn=k)=Eq[log⁡θdk]+Eq[log⁡ϕkwdn]+const\log q^*(z_{dn} = k) = \mathbb E_q[\log \theta_{dk}] + \mathbb E_q[\log \phi_{k w_{dn}}] + \text{const}. The factor θd\theta_d appears in its prior and in one term per word, which contributes log⁡θdk\log \theta_{dk} with probability rdnkr_{dnk}:

log⁡q∗(θd)=∑k(α−1)log⁡θdk+∑n∑krdnklog⁡θdk+const=∑k(α+∑nrdnk−1)log⁡θdk+const,\begin{aligned} \log q^*(\theta_d) &= \sum_k (\alpha - 1) \log \theta_{dk} + \sum_n \sum_k r_{dnk} \log \theta_{dk} + \text{const} \\ &= \sum_k \Big(\alpha + \sum_n r_{dnk} - 1\Big) \log \theta_{dk} + \text{const} , \end{aligned}

the log density of Dir(γd)\mathrm{Dir}(\gamma_d) with γdk=α+∑nrdnk\gamma_{dk} = \alpha + \sum_n r_{dnk}. The same steps for ϕk\phi_k, where word wdnw_{dn} contributes log⁡ϕkwdn\log \phi_{k w_{dn}} with probability rdnkr_{dnk}, give λkw\lambda_{kw}.

They are the Gibbs update with counts replaced by expected counts and probabilities by exponentials of expected logarithms. Coordinate ascent alternates a local step, which iterates rdr_d and γd\gamma_d for every document with the topics fixed, and a global step, which recomputes λ\lambda from all the expected counts. Without the prior on the topics, the global step becomes the M-step of a variational EM that estimates ϕ\phi as a parameter, the form in Vetrov and Kropotov’s lecture notes. Blei et al. write the topics as βk\beta_k, their prior parameter as η\eta and the assignment probabilities as ϕdn\phi_{dn}, and the next note follows them; γ\gamma and λ\lambda are the same in both.

The updates are deterministic, vectorize over the document–word count matrix, and come with an objective, the ELBO, to monitor convergence. In exchange they are biased: mean field underestimates the posterior variance and, like the sampler, can stop in a local optimum. With hyperparameters tuned for each method, the two give similar topics and similar held-out perplexity (Asuncion et al., 2009).

The hyperparameters α\alpha and β\beta#

The two Dirichlet parameters set what kind of documents and topics the model expects. The density of Dir(α,…,α)\mathrm{Dir}(\alpha, \dots, \alpha) is proportional to ∏kθdkα−1\prod_k \theta_{dk}^{\alpha - 1}. With α<1\alpha \lt 1 the exponent is negative, and the density grows without bound as any θdk\theta_{dk} approaches 0: the mass sits near the corners and edges of the simplex, and each document uses few topics. With α=1\alpha = 1 the density is constant, uniform. With α>1\alpha \gt 1 it vanishes on the boundary and peaks at the centre, θdk=1/K\theta_{dk} = 1/K, so every document mixes all topics evenly. β\beta plays the same role for topics: a small β\beta gives topics concentrated on few words.

Figure

What the parameter α does

Draws from the Dirichlet distribution for three values of αThree triangles of points: with α = 0.1 the points hug the corners and edges, with α = 1 they are spread evenly, with α = 10 they gather in the centre.123α = 0.1one topic above 0.9: 70.3%123α = 1one topic above 0.9: 2.7%123α = 10one topic above 0.9: 0%Draws from the Dirichlet distribution for three values of αThree triangles of points: with α = 0.1 the points hug the corners and edges, with α = 1 they are spread evenly, with α = 10 they gather in the centre.123α = 0.1one topic above 0.9: 70.3%123α = 1one topic above 0.9: 2.7%123α = 10one topic above 0.9: 0%
300 random vectors of proportions over three topics from Dir(α, α, α); the corners are single-topic documents, the centre an even mix. With α = 0.1 one topic takes more than 0.9 in 70.3% of the draws (65.9% in the distribution); with α = 1 the distribution is uniform (3%, 2.7% in the sample); with α = 10 the proportions crowd the centre.

In the posterior, α\alpha is a pseudo-count added to every topic of every document. A document whose ten tokens are assigned 88, 22 and 00 to three topics has the estimate θ^=(8+α,2+α,α)/(10+3α)\hat\theta = (8 + \alpha, 2 + \alpha, \alpha)/(10 + 3\alpha):

α=0.1:θ^=(0.786,0.204,0.010),α=1:θ^=(0.692,0.231,0.077).\begin{aligned} \alpha = 0.1:\quad \hat\theta &= (0.786, 0.204, 0.010), \\ \alpha = 1:\quad \hat\theta &= (0.692, 0.231, 0.077) . \end{aligned}

The larger prior spreads the document over a topic it never used. For short documents, such as tweets or search queries, α\alpha dominates the counts.

Common defaults are α=50/K\alpha = 50/K and β=0.1\beta = 0.1 (Griffiths and Steyvers, 2004), or α=β=1/K\alpha = \beta = 1/K (scikit-learn). The hyperparameters can also be learned, by maximizing the evidence with a fixed-point iteration or by sampling them. Wallach, Mimno and McCallum (2009) found that an asymmetric, learned prior on θ\theta, which lets some topics be common in every document, improves held-out likelihood and topic quality markedly, while an asymmetric prior on the topics brings little.

Evaluation: perplexity and coherence#

A topic model is a model of text, so it can be scored like a language model, by the perplexity of held-out documents:

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

the exponentiated average negative log-likelihood per word. A perplexity of 17 means the model is as uncertain about each word as a uniform choice among 17 words: if every word has probability 1/171/17, the average negative log-likelihood is log⁡17\log 17 and its exponential is 17.

Two complications are specific to topic models. First, p(wd)p(w_d) integrates over the document’s proportions and is itself intractable. It is estimated by sampling or, as in the experiment below, by document completion: estimate θd\theta_d from the first half of a test document and score the second half (Wallach et al., 2009). Different estimators give different numbers, so perplexities are comparable only under one protocol. Second, likelihood is not what people want from topics. In a study with human judges, models with better held-out likelihood often had less interpretable topics (Chang et al., 2009).

Coherence measures interpretability directly from co-occurrence: the top words of a good topic appear in the same documents. The UMass coherence of a topic with top words v1,…,vMv_1, \dots, v_M (Mimno et al., 2011) is

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(v)D(v) counts the documents containing vv and D(v,u)D(v, u) those containing both; the +1+1 avoids the logarithm of zero. Each term is a smoothed log conditional probability that a document with vlv_l also contains vmv_m. For three top words in 40, 30 and 20 documents, co-occurring pairwise in 25 (words 1 and 2), 15 (1 and 3) and 12 (2 and 3) documents,

C=log⁡2640+log⁡1640+log⁡1330=−0.431−0.916−0.836=−2.18.\begin{aligned} C &= \log\tfrac{26}{40} + \log\tfrac{16}{40} + \log\tfrac{13}{30} \\ &= -0.431 - 0.916 - 0.836 = -2.18 . \end{aligned}

Values closer to zero mean a more coherent topic. Variants based on pointwise mutual information over a large reference corpus, such as Wikipedia, agree better with human judgements (Newman et al., 2010).

An experiment: recovering known topics#

The Code section uses the “bars” corpus of Griffiths and Steyvers (2004): a vocabulary of 25 words laid out on a 5×55 \times 5 grid, and 10 true topics, the five rows and the five columns, each uniform over its five words. 200 training documents of 50 words each are generated with α=0.3\alpha = 0.3, so that most documents use a few bars, and 50 more are held out. Because the true topics are known, recovery can be measured directly: each learned topic is paired with a true bar by the Hungarian algorithm, and the distance is the total variation between their distributions.

The collapsed sampler runs 200 sweeps with α=0.3\alpha = 0.3 and β=0.1\beta = 0.1 from random assignments. Its log joint log⁡p(w,z)\log p(w, z) climbs from −54,604-54{,}604 after the first sweep to −39,588-39{,}588 after 10, −33,406-33{,}406 after 50 and −33,376-33{,}376 after 200. Mean-field variational inference, by hand with 100 rounds of local and global steps and in scikit-learn’s batch LatentDirichletAllocation, does as well:

worst topic, total variationheld-out perplexity
collapsed Gibbs0.0700.07017.1117.11
mean field, by hand0.0540.05417.1617.16
mean field, scikit-learn0.0510.05117.1217.12
the true topics0017.0917.09
one unigram distribution—25.1025.10

Every method recovers all ten bars, and its perplexity is within 0.070.07 of the true topics’. The unigram model is essentially the uniform distribution over 25 words. The UMass coherence of the top five words averages −3.52-3.52 for the Gibbs topics, −3.59-3.59 for the true bars and −4.51-4.51 for random topics: coherence measures co-occurrence in this corpus, so a learned topic can score slightly above the true one.

The concentration matters when it is wrong by a factor of ten. Variational inference from five random starts for each value, counting a bar as recovered when some topic is within total variation 0.20.2 of it:

α\alphabars recovered, of 10held-out perplexity
0.030, 0, 0, 0, 018.5 – 19.5
0.3 (true)8, 8, 10, 10, 1017.1 – 17.7
36, 2, 10, 10, 919.6 – 20.5

With α\alpha too small, every document is forced toward a single topic, and the topics become typical combinations of bars. With α\alpha too large, documents spread over all topics, perplexity suffers, and recovery depends on the start.

The number of topics has a softer effect. With K=5K = 5, 1010 and 2020, the average held-out perplexity over five starts is 21.3321.33, 17.3417.34 and 17.5117.51, and the average coherence −3.51-3.51, −3.50-3.50 and −3.64-3.64. Too few topics cost perplexity; too many cost little perplexity and split bars into less coherent pieces.

Where it breaks#

Look at the two starts that found only eight bars with the true α\alpha. In the first, one topic puts most of its mass on row 0 and the rest on column 2: two bars share a topic. To keep the count at ten, two other topics both describe column 0. The second start fails the same way, with column 3 covered twice. Each run has stopped at a local optimum of the bound: moving the duplicate topic over to the missing bar would pass through states that explain the data worse. The held-out perplexity, 17.717.7 against 17.117.1, is the only sign of trouble without the true topics to compare with. Restarts help, and so does keeping the run with the best bound or held-out score; on real corpora, where the truth is unknown, topics that change between runs should be reported with caution.

The model’s other limits follow from its assumptions. It is a bag of words, so “not good” and “good” are the same evidence. KK must be chosen, usually by held-out likelihood or coherence, which often disagree; the hierarchical Dirichlet process makes the number of topics a posterior quantity at the price of a more complex sampler (Teh et al., 2006). Without a stop-word list or a learned asymmetric prior, frequent words such as “the” and “of” appear at the top of every topic. And both methods need many passes over every token: coordinate ascent changes the global topics only after a full pass, and collapsed Gibbs, which updates its counts after every token, still needs many sweeps to mix.

What you should remember#

  • LDA: topics ϕk∼Dir(β)\phi_k \sim \mathrm{Dir}(\beta), proportions θd∼Dir(α)\theta_d \sim \mathrm{Dir}(\alpha), then a topic and a word for each position; p(w∣d)=∑kθdkϕkwp(w \mid d) = \sum_k \theta_{dk} \phi_{kw}.
  • It is a non-negative low-rank factorization of the document–word matrix, with the number of topics fixed in advance.
  • Collapsed Gibbs: p(zi=k∣⋅)∝(ndk−i+α)(nkv−i+β)/(nk−i+Vβ)p(z_i = k \mid \cdot) \propto (n_{dk}^{-i} + \alpha)(n_{kv}^{-i} + \beta)/(n_k^{-i} + V\beta), a product of two Dirichlet predictive probabilities.
  • Mean field replaces counts by expected counts and probabilities by exp⁡E[log⁡⋅]\exp \mathbb E[\log \cdot], alternating local and global steps.
  • α<1\alpha \lt 1 means few topics per document; a tenfold wrong α\alpha can hide the true topics.
  • Check topics across restarts, and evaluate by held-out perplexity under a stated protocol and by coherence.

Code#

A collapsed Gibbs sampler and mean-field variational inference for LDA on the bars corpus, with topic recovery, held-out perplexity, UMass coherence, the effect of α\alpha and KK, and a look inside a local optimum. It runs in about 40 seconds; exact numbers can vary across platforms and library versions.

import numpy as np
from scipy.special import digamma, gammaln
from scipy.optimize import linear_sum_assignment
from sklearn.decomposition import LatentDirichletAllocation

rng = np.random.default_rng(0)

# the collapsed Gibbs update for one token: two topics, alpha = 0.1, beta = 0.01, V = 1000
p = np.array([(4 + 0.1) * (30 + 0.01) / (500 + 1000 * 0.01), (2 + 0.1) * (2 + 0.01) / (400 + 1000 * 0.01)])
print(p.round(4), (p / p.sum()).round(3))                             # [0.2413 0.0103] [0.959 0.041]

# the "bars" corpus: 25 words on a 5 x 5 grid, 10 topics (5 rows, 5 columns), each uniform over its 5 words
V, K = 25, 10
grid = np.arange(V).reshape(5, 5)
phi_true = np.zeros((K, V))
for r in range(5):
    phi_true[r, grid[r]] = 0.2                           # a horizontal bar
    phi_true[5 + r, grid[:, r]] = 0.2                    # a vertical bar
D, N, alpha, beta = 200, 50, 0.3, 0.1
theta_true = rng.dirichlet(np.full(K, alpha), size=D)
docs = [rng.choice(V, size=N, p=theta_true[d] @ phi_true) for d in range(D)]   # w ~ sum_k theta_dk phi_kw
test = [rng.choice(V, size=N, p=t @ phi_true) for t in rng.dirichlet(np.full(K, alpha), size=50)]
counts = np.stack([np.bincount(w, minlength=V) for w in docs])               # D x V document-word counts

def log_joint(ndk, nkw):                                 # log p(w, z) with theta and phi integrated out
    topics = (gammaln(nkw + beta).sum(axis=1) - gammaln(nkw.sum(axis=1) + V * beta)).sum() + K * (gammaln(V * beta) - V * gammaln(beta))
    docs_ = (gammaln(ndk + alpha).sum(axis=1) - gammaln(ndk.sum(axis=1) + K * alpha)).sum() + len(ndk) * (gammaln(K * alpha) - K * gammaln(alpha))
    return topics + docs_

# collapsed Gibbs sampling (Griffiths and Steyvers, 2004)
def lda_gibbs(docs, K, alpha, beta, sweeps, rng):
    z = [rng.integers(K, size=len(w)) for w in docs]     # random initial topics
    ndk, nkw, nk = np.zeros((len(docs), K)), np.zeros((K, V)), np.zeros(K)
    for d, w in enumerate(docs):
        np.add.at(ndk[d], z[d], 1); np.add.at(nkw, (z[d], w), 1); np.add.at(nk, z[d], 1)
    trace = []
    for sweep in range(sweeps):
        for d, w in enumerate(docs):
            u = rng.random(len(w))
            for i, (v, k) in enumerate(zip(w, z[d])):
                ndk[d, k] -= 1; nkw[k, v] -= 1; nk[k] -= 1                # take token i out
                p = (ndk[d] + alpha) * (nkw[:, v] + beta) / (nk + V * beta)
                c = np.cumsum(p)
                k = int(np.searchsorted(c, u[i] * c[-1]))                 # draw its new topic
                z[d][i] = k; ndk[d, k] += 1; nkw[k, v] += 1; nk[k] += 1
        trace.append(log_joint(ndk, nkw))
    return ndk, nkw, np.array(trace)

def match(phi):                                          # pair learned topics with true bars; total variation distances
    cost = 0.5 * np.abs(phi[:, None, :] - phi_true[None]).sum(axis=2)
    r, c = linear_sum_assignment(cost)
    return cost[r, c]

def heldout_perplexity(docs, phi, alpha, iters=100):     # document completion: theta from the first half, score the second
    ll, n = 0.0, 0
    for w in docs:
        a, b = w[: len(w) // 2], w[len(w) // 2:]
        th = np.full(len(phi), 1 / len(phi))
        for _ in range(iters):
            r = th[:, None] * phi[:, a]; r /= r.sum(axis=0)
            th = (r.sum(axis=1) + alpha) / (len(a) + len(phi) * alpha)
        ll += np.log(th @ phi[:, b]).sum(); n += len(b)
    return np.exp(-ll / n)

def umass(phi, top=5):                                   # UMass coherence of the top words, averaged over topics
    df = (counts > 0).astype(float)
    co = df.T @ df                                       # co[v, u]: documents containing both v and u
    score = []
    for k in range(len(phi)):
        t = np.argsort(-phi[k])[:top]
        score.append(sum(np.log((co[t[m], t[l]] + 1) / co[t[l], t[l]]) for m in range(1, top) for l in range(m)))
    return np.mean(score)

ndk, nkw, trace = lda_gibbs(docs, K, alpha, beta, 200, rng)
print(trace[[0, 9, 49, 199]].round(0))                  # [-54604. -39588. -33406. -33376.]: log p(w, z) climbs, then levels off
phi_gibbs = (nkw + beta) / (nkw.sum(axis=1, keepdims=True) + V * beta)
print(match(phi_gibbs).max().round(3))                   # 0.07: every bar recovered within 7% total variation
uni = (counts.sum(axis=0) + 1.0) / (counts.sum() + V)
print(round(heldout_perplexity(test, phi_gibbs, alpha), 2), round(heldout_perplexity(test, phi_true, alpha), 2),
      round(np.exp(-np.mean([np.log(uni[w]).mean() for w in test])), 2))      # Gibbs topics, true topics, unigram
# 17.11 17.09 25.1
rand = np.array([umass(rng.dirichlet(np.ones(V), size=K)) for _ in range(20)])
print(round(umass(phi_gibbs), 2), round(umass(phi_true), 2), round(rand.mean(), 2))   # -3.52 -3.59 -4.51: learned, true, random

# mean-field variational inference (Blei, Ng and Jordan, 2003, with a Dirichlet prior on the topics)
def lda_cavi(counts, K, alpha, beta, iters, rng, inner=20):
    lam = beta + rng.gamma(100.0, 0.01, size=(K, V))     # q(phi_k) = Dir(lam_k)
    gam = np.ones((len(counts), K))                      # q(theta_d) = Dir(gam_d)
    for _ in range(iters):
        Elog_phi = digamma(lam) - digamma(lam.sum(axis=1, keepdims=True))
        for _ in range(inner):                           # local step: every document, topics fixed
            Elog_theta = digamma(gam) - digamma(gam.sum(axis=1, keepdims=True))
            r = np.exp(Elog_theta[:, None, :] + Elog_phi.T[None])           # D x V x K, unnormalized q(z = k) per word type
            r /= r.sum(axis=2, keepdims=True)
            gam = alpha + (counts[:, :, None] * r).sum(axis=1)
        lam = beta + (counts[:, :, None] * r).sum(axis=0).T                 # global step: the topics
    return lam / lam.sum(axis=1, keepdims=True), gam

phi_vi, gam = lda_cavi(counts, K, alpha, beta, 100, rng)
print(match(phi_vi).max().round(3), round(heldout_perplexity(test, phi_vi, alpha), 2))     # 0.054 17.16
skl = LatentDirichletAllocation(n_components=K, doc_topic_prior=alpha, topic_word_prior=beta, learning_method='batch', max_iter=100, random_state=0).fit(counts)
phi_skl = skl.components_ / skl.components_.sum(axis=1, keepdims=True)
print(match(phi_skl).max().round(3), round(heldout_perplexity(test, phi_skl, alpha), 2))   # 0.051 17.12

# the hyperparameters and the number of topics: variational inference from five random starts each
for a in (0.03, 0.3, 3.0):
    fits = [lda_cavi(counts, K, a, beta, 100, np.random.default_rng(s))[0] for s in range(5)]
    print('alpha', a, [int((match(f) < 0.2).sum()) for f in fits], [float(round(heldout_perplexity(test, f, a), 1)) for f in fits])
# alpha 0.03 [0, 0, 0, 0, 0] [18.5, 19.0, 18.9, 19.5, 19.3]
# alpha 0.3 [8, 8, 10, 10, 10] [17.7, 17.7, 17.1, 17.1, 17.1]
# alpha 3.0 [6, 2, 10, 10, 9] [20.2, 20.5, 19.6, 19.6, 19.8]
for k in (5, 10, 20):
    fits = [lda_cavi(counts, k, alpha, beta, 100, np.random.default_rng(s))[0] for s in range(5)]
    print('K', k, round(np.mean([heldout_perplexity(test, f, alpha) for f in fits]), 2), round(np.mean([umass(f) for f in fits]), 2))
# K 5 21.33 -3.51 | K 10 17.34 -3.5 | K 20 17.51 -3.64

# inside a local optimum: the first start with the true alpha (bars 0-4 are the rows, 5-9 the columns)
phi0 = lda_cavi(counts, K, alpha, beta, 100, np.random.default_rng(0))[0]
cost = 0.5 * np.abs(phi0[:, None, :] - phi_true[None]).sum(axis=2)
print(cost.argmin(axis=1), cost.min(axis=0).round(2))   # the nearest bar of each topic; each bar's distance to its nearest topic
# [4 2 5 1 8 6 3 0 5 9] [0.31 0.11 0.04 0.06 0.05 0.05 0.04 0.53 0.06 0.05]: two topics on column 0, none close to column 2
print(phi0[cost[:, 0].argmin()].reshape(5, 5).round(2))  # the topic nearest to row 0 also covers column 2
# [[0.11 0.13 0.24 0.13 0.12]
#  [0.   0.   0.07 0.   0.  ]
#  [0.   0.   0.06 0.   0.  ]
#  [0.   0.   0.07 0.   0.  ]
#  [0.   0.   0.08 0.   0.  ]]

Next#

Both inference methods read the whole corpus many times: the sampler in every sweep, coordinate ascent before every change of the global topics. With a few hundred documents that takes seconds; with millions of news articles, days. The next note keeps the variational family and the updates above and changes only the order of work: it updates the topics after each small random batch of documents, as a step along a noisy natural gradient, and so fits topic models to corpora that do not fit in memory.

References#