intermediate text-mining 35 min read

Topic Models: Latent Dirichlet Allocation

Documents as points in a polytope of topics: when the topics can be recovered, the two classical ways to infer them, and what a topic model finds in filings whose generator plants seven vocabularies but only six identifiable topics.

Overview & Motivation

The distributional semantics topic ended on a matrix. It took the finance corpus’s frequent content nouns, counted which ones share a document, and found that the ratio matrix drops to the level of noise after its fifth singular value, as a mixture of six sector vocabularies predicts. It closed by observing that a topic model would find this structure more easily than an embedding would. This page takes that up.

A topic model treats a document as a bag of words drawn from a few distributions over the vocabulary, its topics, mixed in proportions of its own. Picture the set of all distributions over VV words, a simplex with one corner per word. Each topic is a point in it, and so is each document’s word distribution, which is a weighted average of the topic points and so lies inside their convex hull. Fitting a topic model means finding a few corners that hold the documents’ points, and reading each document’s proportions off its position.

That picture organizes the page.

  1. The generative model. Latent Dirichlet allocation, the polytope its documents live in, and fitting a document’s proportions as a projection.
  2. Identifiability and anchor words. When the corners are determined by the documents, and how the corners can be found by convex geometry alone.
  3. Collapsed Gibbs sampling and mean-field variational inference, the two classical ways to fit the model.
  4. Evaluation. Why held-out likelihood is hard to estimate, and how to compare models anyway.

Then the finance case study. The corpus’s generator plants seven vocabularies, one per sector and one shared, and every filing draws about half its content nouns from its sector’s vocabulary and half from the shared one. We will see that only six of the seven can be recovered, and that the obstacles to recovering those six are optimizers rather than the model.


The generative model

Fix a vocabulary of VV words and write ΔV−1\Delta^{V-1} for the simplex of distributions over it. A topic is a point φk∈ΔV−1\varphi_k \in \Delta^{V-1}, and we stack KK of them as the rows of a K×VK \times V matrix Φ\Phi.

Definition 1 (Latent Dirichlet allocation).

Given α∈R>0K\alpha \in \mathbb R_{\gt 0}^K and β>0\beta \gt 0, draw each topic φk∼Dir(β1V)\varphi_k \sim \mathrm{Dir}(\beta \mathbf 1_V). For each document dd, draw its topic proportions θd∼Dir(α)\theta_d \sim \mathrm{Dir}(\alpha), and for each position n=1,…,ndn = 1, \dots, n_d draw a topic zdn∼Cat(θd)z_{dn} \sim \mathrm{Cat}(\theta_d) and then a word wdn∼Cat(φzdn)w_{dn} \sim \mathrm{Cat}(\varphi_{z_{dn}}). The probabilistic latent semantic indexing model (pLSI) is the same model with θd\theta_d and Φ\Phi treated as free parameters, with no priors.

The Dirichlet distribution and its moments are covered on formalStatistics (Multivariate Distributions, Theorems 5 and 6). A small α\alpha puts most of its mass near the corners of ΔK−1\Delta^{K-1}, so documents concentrate on few topics; a large one puts it near the center.

Definition 2 (Topic polytope).

The topic polytope of Φ\Phi is the convex hull T(Φ)=conv⁡{φ1,…,φK}⊆ΔV−1T(\Phi) = \operatorname{conv}\lbrace \varphi_1, \dots, \varphi_K \rbrace \subseteq \Delta^{V-1}.

Proposition 1 (Documents live in the polytope).

Given θd\theta_d and Φ\Phi, the words of document dd are independent and identically distributed with distribution

pd=Φ⊤θd∈T(Φ),p_d = \Phi^\top \theta_d \in T(\Phi),

so its count vector xdx_d satisfies E[xd∣θd]=nd pd\mathbb E[x_d \mid \theta_d] = n_d\, p_d. Stacking documents, the matrix of their word distributions is P=ΘΦP = \Theta \Phi, a product of nonnegative matrices with inner dimension KK.

Proof.

Summing out the topic of one position, P(wdn=w∣θd)=∑kθdk φk(w)=(Φ⊤θd)wP(w_{dn} = w \mid \theta_d) = \sum_k \theta_{dk}\, \varphi_k(w) = (\Phi^\top\theta_d)_w. Given θd\theta_d the pairs (zdn,wdn)(z_{dn}, w_{dn}) are independent across positions, so the words are too. Since θd\theta_d is a probability vector, pdp_d is a convex combination of the rows of Φ\Phi.

∎

Only the expected distribution pdp_d lies in the polytope. The observed frequencies p^d=xd/nd\hat p_d = x_d / n_d scatter around it, often outside. In the lab’s Topic simplex tab the vocabulary has three words, so the word simplex is a triangle, and three topics span a smaller triangle inside it. With α=1\alpha = 1 and documents of 1010 words, 0.6130.613 of the documents’ observed frequencies fall outside the topic triangle; at 160160 words, 0.1500.150 do. At α=0.1\alpha = 0.1 the documents crowd the corners, where a little noise carries them out: 0.6620.662 are still outside at 160160 words.

How do we place an observed document back in the polytope? By maximum likelihood, and the answer is a projection.

Proposition 2 (Fitting a document's proportions is a KL projection).

Fix Φ\Phi and a document with counts xx, length nn, and frequencies p^=x/n\hat p = x/n. For every θ∈ΔK−1\theta \in \Delta^{K-1},

∑wxwlog⁡ (Φ⊤θ)w=−n[H(p^)+KL(p^ ∥ Φ⊤θ)],\sum_w x_w \log\, (\Phi^\top\theta)_w = -n \left[ H(\hat p) + \mathrm{KL}\big(\hat p \,\Vert\, \Phi^\top\theta\big) \right],

where HH is the entropy. So the maximum-likelihood θ\theta places Φ⊤θ\Phi^\top\theta at a point of T(Φ)T(\Phi) nearest to p^\hat p in KL divergence. If some point of T(Φ)T(\Phi) gives every word of the document positive probability, a nearest point exists, and its probabilities on the document’s words are unique.

Proof.

With q=Φ⊤θq = \Phi^\top\theta, ∑wxwlog⁡qw=n∑wp^wlog⁡p^w−n∑wp^wlog⁡(p^w/qw)\sum_w x_w \log q_w = n \sum_w \hat p_w \log \hat p_w - n \sum_w \hat p_w \log(\hat p_w / q_w), which is the identity. Maximizing the left side over θ\theta therefore minimizes KL(p^ ∥ q)\mathrm{KL}(\hat p \,\Vert\, q) over q∈T(Φ)q \in T(\Phi), which is nonnegative by Gibbs’ inequality (formalML, KL Divergence, Proposition 2). The function q↦−∑w:p^w>0p^wlog⁡qwq \mapsto -\sum_{w : \hat p_w \gt 0} \hat p_w \log q_w is continuous where it is finite and tends to +∞+\infty as any qwq_w with p^w>0\hat p_w \gt 0 tends to 00; on the compact set T(Φ)T(\Phi), where it is finite somewhere, it attains its minimum. It is strictly convex in the coordinates (qw)p^w>0(q_w)_{\hat p_w \gt 0}, so two minimizers agree on them.

∎

The projection is computed by an EM iteration in which each step raises the likelihood. pLSI fits Φ\Phi too, minimizing the total ∑dnd KL(p^d ∥ T(Φ))\sum_d n_d\, \mathrm{KL}(\hat p_d \,\Vert\, T(\Phi)) jointly. Hofmann (1999) described the aspect model’s sub-simplex and its KL reading for the joint table of documents and words, and Gaussier and Goutte (2005) showed that pLSI solves non-negative matrix factorization under the generalized KL divergence.

Remark.

LSA’s projection is Euclidean and signed. The distributional semantics topic’s truncated SVD (its Definition 3) projects the rows of a document–word matrix onto a dd-dimensional subspace in Euclidean norm. A subspace of dimension d≥Kd \ge K has room for the polytope, but its coordinates take both signs. On the finance documents’ word frequencies, LSA’s rank-66 reconstruction has 0.2830.283 of its entries negative, which no mixture of distributions can produce. LDA keeps the simplex: a document’s coordinates are proportions.


Identifiability and anchor words

A factorization P=ΘΦP = \Theta\Phi is useful only if the documents determine it. They do not, in three ways.

Proposition 3 (The factorization is not unique).

(a) For every permutation matrix Π\Pi, the topics ΠΦ\Pi\Phi with proportions ΘΠ⊤\Theta\Pi^\top give the same documents, and under a symmetric prior the same posterior density. The posterior therefore has K!K! symmetric modes. (b) The polytope itself need not be determined. With V=3V = 3, K=2K = 2, φ1=(0.6,0.3,0.1)\varphi_1 = (0.6, 0.3, 0.1), φ2=(0.1,0.3,0.6)\varphi_2 = (0.1, 0.3, 0.6), and t=0.1t = 0.1, the stretched topics

φ1′=φ1+t(φ1−φ2),φ2′=φ2+t(φ2−φ1)\varphi_1' = \varphi_1 + t(\varphi_1 - \varphi_2), \qquad \varphi_2' = \varphi_2 + t(\varphi_2 - \varphi_1)

lie in the simplex, and every document of (Φ,Θ)(\Phi, \Theta) has proportions θ′=M⊤θ≥0\theta' = M^\top\theta \ge 0 under them, with the same pdp_d, where M=11+2t(1+ttt1+t)M = \frac{1}{1 + 2t}\begin{pmatrix} 1 + t & t \\ t & 1 + t \end{pmatrix}.

Proof.

(a) Relabeling topics is a bijection of the assignments zz that preserves the joint density of every quantity in Definition 1 when α\alpha is symmetric. (b) Solving the two definitions for φ1\varphi_1 and φ2\varphi_2 gives Φ=MΦ′\Phi = M\Phi', so ΘΦ=(ΘM)Φ′\Theta\Phi = (\Theta M)\Phi'. The rows of ΘM\Theta M are nonnegative and sum to one because MM is nonnegative with rows summing to one, and Φ′≥0\Phi' \ge 0 for t=0.1t = 0.1 by direct computation: φ1′=(0.65,0.3,0.05)\varphi_1' = (0.65, 0.3, 0.05).

∎

Part (a) means that topics are compared only after matching them, which the harness does by the assignment of least total L1L^1 distance. Part (b) means that some condition on Φ\Phi is needed. A third failure is the one the finance corpus has.

Proposition 4 (A topic every document shares at one weight is unidentifiable).

Suppose every document’s proportions put weight c∈(0,1)c \in (0, 1) on a shared topic φ0\varphi_0 and 1−c1 - c on one topic φs(d)\varphi_{s(d)} of its own, s(d)∈{1,…,S}s(d) \in \lbrace 1, \dots, S \rbrace. Then each document’s words are i.i.d. from

ψs=(1−c) φs+c φ0,\psi_s = (1 - c)\,\varphi_s + c\,\varphi_0 ,

the same distribution as a single-membership model, a mixture of unigrams with SS topics. For every c′∈[0,c]c' \in [0, c], the shared topic φ0\varphi_0 with weight c′c' and the own topics φs′=(ψs−c′φ0)/(1−c′)\varphi_s' = (\psi_s - c'\varphi_0)/(1 - c') give the same documents, and the topic–topic matrix R=E[θθ⊤]R = \mathbb E[\theta\theta^\top], of size S+1S + 1, has rank at most SS.

Proof.

By Proposition 1 a document’s words are i.i.d. from Φ⊤θd=ψs(d)\Phi^\top\theta_d = \psi_{s(d)}, which depends on the topics only through the ψs\psi_s. For c′≤cc' \le c, φs′=((1−c)φs+(c−c′)φ0)/(1−c′)\varphi_s' = \big((1 - c)\varphi_s + (c - c')\varphi_0\big)/(1 - c') is a probability vector and (1−c′)φs′+c′φ0=ψs(1 - c')\varphi_s' + c'\varphi_0 = \psi_s. Every θd\theta_d is one of the SS vectors vs=(1−c)es+c e0v_s = (1 - c)e_s + c\, e_0, so R=∑sP(s(d)=s) vsvs⊤R = \sum_s P(s(d) = s)\, v_s v_s^\top is a sum of SS rank-one matrices.

∎

The cure for (b) is a condition borrowed from non-negative matrix factorization (Donoho and Stodden 2003).

Definition 3 (Separability and anchor words).

Φ\Phi is separable if every topic kk has an anchor word aka_k with φk(ak)>0\varphi_k(a_k) \gt 0 and φj(ak)=0\varphi_j(a_k) = 0 for j≠kj \ne k.

An anchor word is evidence of its topic and of nothing else. Anchors are found in a matrix the distributional semantics topic already built, the document-level co-occurrence matrix, provided it is estimated without counting a word with itself.

Proposition 5 (The co-occurrence estimator is unbiased).

For a document with nd≥2n_d \ge 2, let

Q^d=xdxd⊤−diag⁡(xd)nd(nd−1).\hat Q_d = \frac{x_d x_d^\top - \operatorname{diag}(x_d)}{n_d(n_d - 1)} .

Then E[Q^d∣θd]=Φ⊤θdθd⊤Φ\mathbb E[\hat Q_d \mid \theta_d] = \Phi^\top\theta_d\theta_d^\top\Phi, and averaged over documents, E[Q^]=Φ⊤R Φ\mathbb E[\hat Q] = \Phi^\top R\, \Phi with R=E[θθ⊤]R = \mathbb E[\theta\theta^\top].

Proof.

xdxd⊤−diag⁡(xd)=∑i≠jewdiewdj⊤x_d x_d^\top - \operatorname{diag}(x_d) = \sum_{i \ne j} e_{w_{di}} e_{w_{dj}}^\top counts the nd(nd−1)n_d(n_d - 1) ordered pairs of distinct positions. Given θd\theta_d the words at two distinct positions are independent with distribution pdp_d (Proposition 1), so each pair has expectation pdpd⊤=Φ⊤θdθd⊤Φp_d p_d^\top = \Phi^\top\theta_d\theta_d^\top\Phi. Averaging over θd\theta_d gives Φ⊤R Φ\Phi^\top R\,\Phi.

∎

So Q=Φ⊤R ΦQ = \Phi^\top R\,\Phi is the joint distribution of the words at two distinct positions of a random document. Let p=Q1p = Q\mathbf 1 be its word marginal and Qˉ=diag⁡(p)−1Q\bar Q = \operatorname{diag}(p)^{-1} Q, whose row Qˉw\bar Q_w is the distribution of the second word given that the first is ww.

Theorem 1 (Anchor rows are the vertices).

Let Φ\Phi be separable with anchors a1,…,aKa_1, \dots, a_K, and let π=R1\pi = R\mathbf 1 be the topics’ marginal probabilities. For every word with p(w)>0p(w) \gt 0,

Qˉw=∑kCwk Qˉak,Cwk=P(z1=k∣w1=w)=φk(w) πkp(w),\bar Q_w = \sum_k C_{wk}\, \bar Q_{a_k}, \qquad C_{wk} = P(z_1 = k \mid w_1 = w) = \frac{\varphi_k(w)\, \pi_k}{p(w)} ,

so every row of Qˉ\bar Q lies in conv⁡{Qˉa1,…,QˉaK}\operatorname{conv}\lbrace \bar Q_{a_1}, \dots, \bar Q_{a_K} \rbrace. If RR is nonsingular, the anchor rows are affinely independent, they are the vertices of the convex hull of all rows, a word’s row is a vertex only if the word is an anchor, and Φ\Phi is recovered from CC and pp:

φk(w)=Cwk p(w)∑uCuk p(u).\varphi_k(w) = \frac{C_{wk}\, p(w)}{\sum_{u} C_{uk}\, p(u)} .
Proof.

Let z1z_1 be the topic of the first position. Given z1z_1, the first word is independent of θ\theta, so p(θ∣z1,w1)=p(θ∣z1)p(\theta \mid z_1, w_1) = p(\theta \mid z_1) and the second word is independent of the first given z1z_1. Hence

Qˉw=∑kP(z1=k∣w1=w)  gk,gk=P(w2=⋅∣z1=k),\bar Q_w = \sum_k P(z_1 = k \mid w_1 = w)\; g_k, \qquad g_k = P(w_2 = \cdot \mid z_1 = k),

and Bayes’ rule gives Cwk=φk(w)πk/p(w)C_{wk} = \varphi_k(w)\pi_k / p(w). For an anchor, Cakk=1C_{a_k k} = 1, so Qˉak=gk\bar Q_{a_k} = g_k. This proves the first claim, since each row CwC_w is a probability vector.

Now gk=∑jP(z2=j∣z1=k) φjg_k = \sum_j P(z_2 = j \mid z_1 = k)\, \varphi_j, that is, g=RˉΦg = \bar R \Phi with Rˉ=diag⁡(π)−1R\bar R = \operatorname{diag}(\pi)^{-1} R. If RR is nonsingular then π>0\pi \gt 0 and Rˉ\bar R is nonsingular. Separability makes the rows of Φ\Phi linearly independent, since its anchor columns form a diagonal matrix with positive diagonal. If ∑kλkgk=0\sum_k \lambda_k g_k = 0, then λ⊤RˉΦ=0\lambda^\top \bar R \Phi = 0, so λ⊤Rˉ=0\lambda^\top \bar R = 0 and λ=0\lambda = 0. The gkg_k are therefore linearly, hence affinely, independent, and their hull is a simplex with vertices gkg_k. Barycentric coordinates in a simplex are unique, so Qˉw=gk\bar Q_w = g_k forces Cw=ekC_w = e_k, which means φj(w)=0\varphi_j(w) = 0 for j≠kj \ne k: ww is an anchor of kk. Finally ∑uCuk p(u)=πk\sum_u C_{uk}\, p(u) = \pi_k, so the last display is Cwkp(w)/πk=φk(w)C_{wk}p(w)/\pi_k = \varphi_k(w).

∎

Arora, Ge, and Moitra (2012) introduced anchor words and proved polynomial-time recovery from finitely many documents (their Theorem 1.4) under a lower bound on the ℓ1\ell_1 condition number of RR, which implies nonsingularity. Arora et al. (2013, Section 3) gave the convex-combination form above. Theorem 1 is the exact, population-level core of those results, and nonsingularity is not a technicality. In Proposition 4’s world, the shared topic’s anchor row lies in the hull of the others: in the harness’s four-topic example its linear-programming distance to that hull is 00, and the anchor search below picks a non-anchor in its place.

Algorithm 1 (Anchor finding and recovery).

  1. Estimate Q^\hat Q by Proposition 5 and normalize its rows to Qˉ\bar Q.
  2. FastAnchorWords. Among candidate words that appear in at least 5%5\% of the documents, take the row of Qˉ\bar Q farthest from the origin; then, K−1K - 1 times, take the row farthest from the affine span of the rows chosen so far (Gram–Schmidt on differences).
  3. RecoverL2. For every word, find the probability vector CwC_w minimizing ∥Qˉw−Cw⊤QˉS∥2\lVert \bar Q_w - C_w^\top \bar Q_S \rVert^2, where QˉS\bar Q_S holds the anchor rows.
  4. Set φk(w)∝Cwk p^(w)\varphi_k(w) \propto C_{wk}\, \hat p(w), as in Theorem 1.

FastAnchorWords is Arora et al.’s Algorithm 4, and RecoverL2 is defined in their Section 3. The candidate threshold matters: with a fixed minimum count, rare words, whose sampled rows are mostly noise, win the farthest-point search. The lab’s Anchors tab draws the rows of a three-topic world in the anchors’ triangle, where Theorem 1 puts the population rows exactly, and the sampled rows scatter and tighten as the corpus grows. In a separable world of 400400 words and 55 topics, the mean L1L^1 error per topic falls from 0.5420.542 at 250250 documents to 0.0650.065 at 16,00016{,}000, and the planted anchors are found from 4,0004{,}000 documents on. Without anchors the error stops at 0.1900.190, above the population floor of 0.1690.169 that no amount of data removes. (The topics there are dense, Dir(1)\mathrm{Dir}(\mathbf 1) off the anchors. Sparse topics are already nearly separable: their frequent words carry almost all their mass in one topic, and the contrast disappears.)


Collapsed Gibbs sampling

The posterior p(z,θ,Φ∣w)p(z, \theta, \Phi \mid w) has no closed form, but conjugacy lets us integrate out everything except the assignments.

Lemma 1 (The Dirichlet–multinomial marginal).

For θ∼Dir(a)\theta \sim \mathrm{Dir}(a) and counts n∈NKn \in \mathbb N^K,

E[∏kθknk]=B(a+n)B(a),B(a)=∏kΓ(ak)Γ(∑kak).\mathbb E\Big[ \prod_k \theta_k^{n_k} \Big] = \frac{B(a + n)}{B(a)}, \qquad B(a) = \frac{\prod_k \Gamma(a_k)}{\Gamma\big(\sum_k a_k\big)} .
Proof.

The integrand ∏kθknk⋅∏kθkak−1/B(a)\prod_k \theta_k^{n_k} \cdot \prod_k \theta_k^{a_k - 1}/B(a) is B(a+n)/B(a)B(a + n)/B(a) times the Dir(a+n)\mathrm{Dir}(a + n) density, which integrates to one. This is the normalizing-constant step of the conjugacy in formalStatistics, Multivariate Distributions, Theorem 6.

∎

Write ndkn_{dk} for the number of tokens of document dd assigned to topic kk, nkwn_{kw} for the number of tokens of word ww assigned to kk, and nk=∑wnkwn_k = \sum_w n_{kw}. Applying Lemma 1 to every document and every topic,

p(w,z)=∏dB(α+nd⋅)B(α)∏kB(β1+nk⋅)B(β1).p(w, z) = \prod_d \frac{B(\alpha + n_{d\cdot})}{B(\alpha)} \prod_k \frac{B(\beta\mathbf 1 + n_{k\cdot})}{B(\beta\mathbf 1)} .

Theorem 2 (The collapsed full conditional).

For token ii of document dd, with word ww, and with every count computed without token ii (marked −i^{-i}),

P(zi=k∣z−i,w)  ∝  (ndk−i+αk) nkw−i+βnk−i+Vβ.P(z_i = k \mid z_{-i}, w) \;\propto\; \big(n_{dk}^{-i} + \alpha_k\big)\, \frac{n_{kw}^{-i} + \beta}{n_k^{-i} + V\beta} .
Proof.

Setting zi=kz_i = k changes only two counts, each by one: the count of topic kk in document dd, and the count of word ww in topic kk. Every other factor of p(w,z)p(w, z) is the same for all kk, so P(zi=k∣z−i,w)P(z_i = k \mid z_{-i}, w) is proportional to

B(α+nd⋅−i+ek)B(α+nd⋅−i)⋅B(β1+nk⋅−i+ew)B(β1+nk⋅−i).\frac{B(\alpha + n_{d\cdot}^{-i} + e_k)}{B(\alpha + n_{d\cdot}^{-i})} \cdot \frac{B(\beta\mathbf 1 + n_{k\cdot}^{-i} + e_w)}{B(\beta\mathbf 1 + n_{k\cdot}^{-i})} .

For any aa, B(a+ek)/B(a)=ak/∑jajB(a + e_k)/B(a) = a_k / \sum_j a_j, by Γ(x+1)=xΓ(x)\Gamma(x + 1) = x\Gamma(x) applied in the numerator and in the denominator. The first ratio is (ndk−i+αk)/(nd−1+∑jαj)(n_{dk}^{-i} + \alpha_k)/(n_d - 1 + \sum_j\alpha_j), whose denominator does not depend on kk; the second is (nkw−i+β)/(nk−i+Vβ)(n_{kw}^{-i} + \beta)/(n_k^{-i} + V\beta).

∎

Griffiths and Steyvers (2004, Eq. 5) wrote the conditional with the document’s denominator nd−1+Kαn_d - 1 + K\alpha, which we drop as a constant.

Algorithm 2 (Collapsed Gibbs sampling).

Assign every token a topic uniformly at random and tabulate the counts. Then sweep: for each token in turn, remove it from the counts, draw its new topic from Theorem 2’s conditional, and add it back. After the sweeps, estimate the topics and proportions by Proposition 6.

Corollary 1 (The posterior is the sampler's limit).

Each step of Algorithm 2 leaves p(z∣w)p(z \mid w) invariant. If α,β>0\alpha, \beta \gt 0, one sweep can move from any assignment to any other with positive probability, so the chain is irreducible and aperiodic on its finite state space, and the distribution of zz after tt sweeps converges to p(z∣w)p(z \mid w).

Proof.

A step that redraws one coordinate from its exact conditional is a Metropolis–Hastings step that always accepts, so it leaves the target invariant (formalStatistics, Bayesian Computation and MCMC, Theorem 2), and so does a composition of such steps. Every factor of Theorem 2’s conditional is positive, so each step can set its token to any topic, and a sweep can reach any assignment in one pass. A finite chain whose transition matrix is entrywise positive converges to its unique invariant distribution (ibid., Theorem 5).

∎

The harness checks Corollary 1 exactly on a corpus of two documents and seven tokens, small enough to enumerate all 27=1282^7 = 128 assignments. The product of the seven single-token kernels is entrywise positive, and its invariant vector equals the enumerated posterior to 10−1210^{-12}; the sampler itself, run for 40,00040{,}000 sweeps, matches every token’s posterior marginal to 0.010.01.

Proposition 6 (Point estimates from one sample).

Given an assignment zz,

E[φk(w)∣z,w]=nkw+βnk+Vβ,E[θdk∣z]=ndk+αknd+∑jαj.\mathbb E[\varphi_k(w) \mid z, w] = \frac{n_{kw} + \beta}{n_k + V\beta}, \qquad \mathbb E[\theta_{dk} \mid z] = \frac{n_{dk} + \alpha_k}{n_d + \sum_j\alpha_j} .
Proof.

Given zz and ww, the topic φk\varphi_k is Dir(β1+nk⋅)\mathrm{Dir}(\beta\mathbf 1 + n_{k\cdot}) and θd\theta_d is Dir(α+nd⋅)\mathrm{Dir}(\alpha + n_{d\cdot}), by conjugacy; these are their means.

∎

These are the Dirichlet-smoothed estimates of formalRAG’s query-likelihood topic (its Theorem 1). Averaging them over the sweeps of one run is safe; averaging across runs is not, because of Proposition 3(a).


Mean-field variational inference

The other classical engine replaces the posterior with the closest member of a factorized family and climbs a lower bound on log⁡p(w)\log p(w), the ELBO (formalML, Variational Inference, Definition 1). Its updates need one expectation.

Lemma 2 (The Dirichlet log-moment).

If θ∼Dir(γ)\theta \sim \mathrm{Dir}(\gamma), then E[log⁡θk]=ψ(γk)−ψ(∑jγj)\mathbb E[\log\theta_k] = \psi(\gamma_k) - \psi\big(\sum_j\gamma_j\big), where ψ=Γ′/Γ\psi = \Gamma'/\Gamma is the digamma function.

Proof.

B(γ)=∫ΔK−1∏jθjγj−1 dθB(\gamma) = \int_{\Delta^{K-1}} \prod_j \theta_j^{\gamma_j - 1}\, d\theta. Differentiating under the integral in γk\gamma_k, which dominated convergence permits on a neighborhood of γ\gamma where γk>0\gamma_k \gt 0, gives ∂kB(γ)=∫log⁡θk∏jθjγj−1 dθ\partial_k B(\gamma) = \int \log\theta_k \prod_j \theta_j^{\gamma_j - 1}\, d\theta, so

E[log⁡θk]=∂klog⁡B(γ)=ψ(γk)−ψ(∑jγj).\mathbb E[\log\theta_k] = \partial_k \log B(\gamma) = \psi(\gamma_k) - \psi\Big(\sum_j\gamma_j\Big).

This is the Dirichlet case, with sufficient statistic log⁡θ\log\theta, of the identity formalStatistics proves for one-parameter families (Exponential Families, Theorem 1), and Blei, Ng, and Jordan (2003, Appendix A.1) derive it the same way.

∎

Theorem 3 (Coordinate ascent for LDA).

Under the mean-field family in which the topics, each document’s proportions, and each token’s topic are independent,

q=∏kDir(φk;λk)∏d[Dir(θd;γd)∏nCat(zdn;rdn)],q = \prod_k \mathrm{Dir}(\varphi_k; \lambda_k) \prod_d \Big[ \mathrm{Dir}(\theta_d; \gamma_d) \prod_n \mathrm{Cat}(z_{dn}; r_{dn}) \Big],

the ELBO’s optimal coordinate updates are

rdnk∝exp⁡(Eqlog⁡θdk+Eqlog⁡φk(wdn)),γd=α+∑nrdn,r_{dnk} \propto \exp\big( \mathbb E_q\log\theta_{dk} + \mathbb E_q\log\varphi_k(w_{dn}) \big), \qquad \gamma_d = \alpha + \sum_n r_{dn},λkw=β+∑d,nrdnk 1[wdn=w],\lambda_{kw} = \beta + \sum_{d, n} r_{dnk}\, \mathbf 1[w_{dn} = w],

with both expectations given by Lemma 2.

Proof.

formalML’s Theorem 2 says the optimal factor for one block is proportional to the exponential of the expected log of that block’s complete conditional. Given everything else, log⁡p(zdn=k∣⋅)=log⁡θdk+log⁡φk(wdn)+const\log p(z_{dn} = k \mid \cdot) = \log\theta_{dk} + \log\varphi_k(w_{dn}) + \text{const}, which gives rr. The complete conditional of θd\theta_d is Dir(α+∑nezdn)\mathrm{Dir}(\alpha + \sum_n e_{z_{dn}}) and that of φk\varphi_k is Dir(β1+∑d,n1[zdn=k] ewdn)\mathrm{Dir}(\beta\mathbf 1 + \sum_{d,n} \mathbf 1[z_{dn} = k]\, e_{w_{dn}}), both conjugate, so by formalML’s Proposition 1 the optimal factors are Dirichlet with the expected natural parameters, which are γd\gamma_d and λk\lambda_k.

∎

These are Blei, Ng, and Jordan’s Eqs. 6–8, derived in their Appendix A.3, with the Dirichlet prior on the topics of their smoothed model (Section 5.4).

Corollary 2 (The ELBO never decreases).

Each update of Theorem 3 maximizes the ELBO over its block, so alternating them never lowers it, and since the ELBO is bounded above by log⁡p(w)\log p(w), its values converge.

Proof.

Each update is the exact maximizer in its block (formalML, Theorem 2), so the ELBO after it is at least the ELBO before it; a monotone sequence bounded above converges.

∎

The harness records the ELBO after every update of every run and checks that it never falls, and checks our closed form for the bound against scikit-learn’s to 10−810^{-8} relative. Corollary 2 promises convergence of the ELBO’s values, not to the best optimum, and the finance case study shows how far apart those can be.

Remark.

CVB0. Replacing Theorem 2’s counts with their expectations under qq turns the sampler’s conditional into a deterministic update, CVB0 (Asuncion et al. 2009, Eq. 13; Teh, Newman, and Welling 2006 for the collapsed bound). Asuncion et al. found that the main differences between inference algorithms are attributable to the amount of smoothing, and largely vanish once the hyperparameters are tuned.

The lab’s Gibbs vs. VI tab shows their point on one world. With the topic prior the world was drawn from, β=1\beta = 1, collapsed Gibbs recovers the topics best, at mean L1L^1 error 0.2930.293 against 0.4520.452 for coordinate ascent and 0.4390.439 for the anchors. With a sparse, misspecified β=0.01\beta = 0.01 the order reverses: 0.7870.787 for Gibbs and 0.4610.461 for coordinate ascent.


Evaluating a topic model

The natural score is the probability of held-out documents, but p(w)=∑zp(w,z)p(w) = \sum_z p(w, z) sums over KNK^N assignments.

Definition 4 (Held-out likelihood and document completion).

The held-out log-likelihood per token of documents ww is 1Nlog⁡p(w∣Φ^,α)\frac{1}{N} \log p(w \mid \hat\Phi, \alpha), where NN is their number of tokens. Plug-in document completion splits each held-out document into its even and odd positions, estimates θ^d\hat\theta_d from the even positions with Φ^\hat\Phi fixed, and scores the odd positions by their mean of log⁡∑kθ^dk φ^k(w)\log \sum_k \hat\theta_{dk}\, \hat\varphi_k(w).

Completion needs no marginal likelihood, and it scores a single-membership model by the same rule, with θ^d\hat\theta_d its posterior over clusters. Estimating p(w)p(w) itself is a trap.

Theorem 4 (The harmonic-mean estimator).

Let z(1),…,z(S)z^{(1)}, \dots, z^{(S)} be draws from p(z∣w)p(z \mid w) and p^HM=(1S∑s1/p(w∣z(s)))−1\hat p_{\mathrm{HM}} = \big( \frac1S \sum_s 1/p(w \mid z^{(s)}) \big)^{-1}.

(a) Ep(z∣w)[1/p(w∣z)]=1/p(w)\mathbb E_{p(z \mid w)}\big[ 1/p(w \mid z) \big] = 1/p(w), so p^HM\hat p_{\mathrm{HM}} is consistent.

(b) E[p^HM]≥p(w)\mathbb E[\hat p_{\mathrm{HM}}] \ge p(w): it overestimates in expectation.

(c) With Φ\Phi fixed and the proportions θ\theta continuous, the variance of 1/p(w∣θ)1/p(w \mid \theta) under p(θ∣w)p(\theta \mid w) is finite if and only if ∫p(θ)/p(w∣θ) dθ<∞\int p(\theta)/p(w \mid \theta)\, d\theta \lt \infty. If Φ\Phi is separable and the document holds c≥αkc \ge \alpha_k tokens of anchor words of topic kk, the integral diverges and the variance is infinite.

Proof.

(a) ∑zp(z∣w)/p(w∣z)=∑zp(z)/p(w)=1/p(w)\sum_z p(z \mid w)/p(w \mid z) = \sum_z p(z)/p(w) = 1/p(w), and the average of the 1/p(w∣z(s))1/p(w \mid z^{(s)}) converges to it. (b) x↦1/xx \mapsto 1/x is convex, so by Jensen’s inequality E[p^HM]≥1/E[1S∑s1/p(w∣z(s))]=p(w)\mathbb E[\hat p_{\mathrm{HM}}] \ge 1/\mathbb E[\frac1S\sum_s 1/p(w \mid z^{(s)})] = p(w). (c) The second moment is

∫p(θ∣w)p(w∣θ)2 dθ=1p(w)∫p(θ)p(w∣θ) dθ.\int \frac{p(\theta \mid w)}{p(w \mid \theta)^2}\, d\theta = \frac{1}{p(w)} \int \frac{p(\theta)}{p(w \mid \theta)}\, d\theta .

Every factor of p(w∣θ)=∏n(Φ⊤θ)wnp(w \mid \theta) = \prod_n (\Phi^\top\theta)_{w_n} is at most one, and an anchor token of topic kk contributes (Φ⊤θ)a=θk φk(a)(\Phi^\top\theta)_{a} = \theta_k\, \varphi_k(a). So p(w∣θ)≤C θk cp(w \mid \theta) \le C\, \theta_k^{\,c} for a constant CC, and the integral is at least C−1 E[θk−c]C^{-1}\, \mathbb E[\theta_k^{-c}], where θk∼Beta(αk,α0−αk)\theta_k \sim \mathrm{Beta}(\alpha_k, \alpha_0 - \alpha_k) with α0=∑jαj\alpha_0 = \sum_j \alpha_j. That expectation is ∫01tαk−c−1(1−t)α0−αk−1 dt/B(αk,α0−αk)\int_0^1 t^{\alpha_k - c - 1}(1 - t)^{\alpha_0 - \alpha_k - 1}\, dt / B(\alpha_k, \alpha_0 - \alpha_k), which diverges at 00 when c≥αkc \ge \alpha_k.

∎

With the common choice αk=0.1\alpha_k = 0.1, a single anchor token makes the variance infinite. Newton and Raftery (1994) proposed the estimator, Neal (2008) called it the worst Monte Carlo method ever because its infinite variance can hide behind a small sample variance, and Wallach et al. (2009, Section 6.2) found that it wildly overestimated topic models’ held-out likelihood. The harness checks (a) exactly on the seven-token corpus (log⁡p(w)=−9.015\log p(w) = -9.015), (b) by 4,0004{,}000 replicates of 2020 exact posterior draws, and (c) on a one-anchor document, whose tail integral over [ε,1][\varepsilon, 1] grows tenfold each time ε\varepsilon shrinks a hundredfold, like ε−1/2\varepsilon^{-1/2}.

Proposition 7 (Importance sampling from the prior is unbiased).

For draws z(s)∼p(z)z^{(s)} \sim p(z), the average 1S∑sp(w∣z(s))\frac1S \sum_s p(w \mid z^{(s)}) is an unbiased estimator of p(w)p(w) with finite variance, and its logarithm underestimates log⁡p(w)\log p(w) in expectation.

Proof.

Ep(z)[p(w∣z)]=∑zp(z) p(w∣z)=p(w)\mathbb E_{p(z)}[p(w \mid z)] = \sum_z p(z)\, p(w \mid z) = p(w), and p(w∣z)≤1p(w \mid z) \le 1 bounds the variance. Jensen’s inequality for the concave logarithm gives the last claim.

∎

Unbiased is not the same as useful. On one-document corpora of 44, 88, and 1212 tokens, a prior draw’s relative variance is 0.3870.387, 3.0333.033, and 17.42417.424, growing quickly with length (measured, not proved), while the harmonic mean’s is 0.2500.250, 0.6130.613, and 1.0151.015. On a finite collapsed state space the harmonic mean’s variance is finite, and smaller; its defects are the bias of (b) and, with continuous proportions, the infinite variance of (c). Wallach et al. recommend Chib-style and left-to-right estimators (their Algorithms 2 and 3); we compare models by document completion instead.

Definition 5 (Topic coherence).

For a topic’s top words v1,…,vMv_1, \dots, v_M and document frequencies D(⋅)D(\cdot), the UMass coherence is

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

and the NPMI coherence is the mean over pairs of log⁡P(v,v′)P(v)P(v′)/(−log⁡P(v,v′))\log\frac{P(v, v')}{P(v)P(v')} \big/ \big(-\log P(v, v')\big), with document-level probabilities.

UMass coherence is Mimno et al.’s (2011) Eq. 1, and the PMI form is Newman et al.’s (2010), here normalized to [−1,1][-1, 1]; unnormalized, it is the distributional semantics topic’s PMI (its Definition 2) between words. Coherence asks whether a topic’s words occur together, which held-out likelihood does not: Chang et al. (2009) found models with better held-out likelihood whose topics people found less meaningful.


Finance case study

Documents live in the topic triangle only in expectation
prior α
words per document n_d
show
word 1word 2word 3
topics φ_k and their triangleexpected p_d = Φᵀθ_dobserved frequencies p̂_dKL projection onto the triangle
observed documents outside the topic triangle
0.613

80 documents per setting; the same θ_d at every length, so only the sampling noise changes. Small α piles documents at the topics; short documents scatter their observed frequencies outside, and Proposition 2 maps each back to the nearest point in KL divergence.


Where this sits

The distributional semantics topic found the corpus’s sectors in the spectrum of a co-occurrence matrix. This page found them as the corners of a polytope. Documents live in the polytope of their topics (Proposition 1), and fitting a document’s proportions is a KL projection onto it (Proposition 2). The corners are determined only up to relabeling, not at all in general, and not for a topic every document shares at one weight (Propositions 3 and 4). Under separability, and with a nonsingular topic–topic matrix, the anchor words are the corners of the co-occurrence rows and give the topics by convex geometry (Theorem 1). Conjugacy collapses the posterior to one conditional in three counts (Theorem 2), and the digamma identity gives the mean-field updates (Theorem 3). The harmonic-mean estimator is the wrong way to compare the results (Theorem 4).

The capstone imports topic_mixtures as its topic stage, beside the Loughran–McDonald lexicon for tone and the knowledge-graph embeddings for the facts. Its topics are sectors, which every filing already declares; on real filings, without a planted answer, the structure a topic model finds is harder to name.


Honest caveats


Implementation

The companion notebook (notebookPath) imports the topic’s Python module, which owns every number on this page. It imports the distributional semantics topic’s module for the corpus’s generator and the linear text classifiers’ module for its rounding, and through them the finance corpus. The collapsed sampler is pure Python, a few hundredths of a second per sweep over the corpus’s 63,00063{,}000 tokens; coordinate ascent is NumPy, with every document’s E-step done at once on scikit-learn’s schedule. Its harness checks:

  • Theorem 2 and Corollary 1 by enumerating every assignment of a seven-token corpus, and the sampler against that posterior;
  • Theorem 1 at the population level, with and without a singular topic–topic matrix, and Algorithm 1 on sampled corpora;
  • Lemma 2, Theorem 3, and Corollary 2 against quadrature, scikit-learn, and every update of a run;
  • Theorem 4 and Proposition 7 exactly and by simulation, and every comparison this page states.

The laboratory reads its data from a JSON file that one of the harness’s tests requires to equal the module’s viz_payload() exactly, so the figure cannot drift from the code.

Connections

  • Document completion scores held-out tokens by their mean log-probability, the negative of that topic's cross-entropy, so −5.794 nats per token is a perplexity of about 328 over the content-noun vocabulary. perplexity-cross-entropy
  • The mixture of unigrams is that topic's multinomial naive Bayes with the class unobserved; started at the gold sectors, its EM keeps the supervised solution, and from random starts it stalls far below it. linear-text-classifiers
  • The finance corpus seats its content nouns in Pitman–Yor restaurants, the process that topic connects to Kneser–Ney; Proposition 6's point estimates are the same add-beta Dirichlet posterior means as its additive smoothing. n-gram-models-smoothing

References & Further Reading

  • paper Latent Dirichlet Allocation — David M. Blei, Andrew Y. Ng, and Michael I. Jordan (2003) Journal of Machine Learning Research 3: 993–1022. Section 4.3: pLSI; Section 4.4 and Figure 4: the topic simplex embedded in the word simplex; Section 5.2, Eqs. 6–8: the variational updates, derived in Appendix A.3; Appendix A.1: E[log θ_i] = Ψ(α_i) − Ψ(Σα_j) (an unnumbered display); Section 5.4 and Figure 7: smoothed LDA, with a Dirichlet prior on the topics
  • paper Finding Scientific Topics — Thomas L. Griffiths and Mark Steyvers (2004) Proceedings of the National Academy of Sciences 101, suppl. 1: 5228–35. Eq. 5: the collapsed full conditional, written with the document-length denominator that Theorem 2 drops as a constant
  • paper Probabilistic Latent Semantic Analysis — Thomas Hofmann (1999) Proceedings of UAI 1999, 289–96. Section 3.3 and Figure 2: the aspect model's sub-simplex, and maximum likelihood as minimizing the KL divergence from the empirical distribution
  • paper Probabilistic Latent Semantic Indexing — Thomas Hofmann (1999) Proceedings of SIGIR 1999, 50–57 (cited from its metadata)
  • paper Learning Topic Models—Going beyond SVD — Sanjeev Arora, Rong Ge, and Ankur Moitra (2012) Proceedings of FOCS 2012, 1–10 (full version arXiv 1204.1956). Definition 1.1: p-separable topic matrices (anchor words are introduced in Section 1's prose); Definition 1.3: the topic–topic matrix R; Theorem 1.4: polynomial-time recovery under a lower bound on R's ℓ1 condition number (Definition 2.1)
  • paper A Practical Algorithm for Topic Modeling with Provable Guarantees — Sanjeev Arora, Rong Ge, Yoni Halpern, David Mimno, Ankur Moitra, David Sontag, Yichen Wu, and Michael Zhu (2013) Proceedings of ICML 2013, PMLR 28 (2): 280–88. Section 3, Eqs. 1–2 and the text after them: the rows of the normalized co-occurrence matrix as convex combinations of the anchor rows with coefficients p(z = k | w); Algorithm 4: FastAnchorWords; RecoverL2 is defined in Section 3's prose; Appendix D.1 of the full version (arXiv 1212.4777): the unbiased per-document co-occurrence estimator
  • paper When Does Non-Negative Matrix Factorization Give a Correct Decomposition into Parts? — David Donoho and Victoria Stodden (2003) Advances in Neural Information Processing Systems 16. Section 5: the separability condition [R2] (Eq. 5) and Theorem 1, uniqueness of the factorization
  • paper Relation between PLSA and NMF and Implications — Eric Gaussier and Cyril Goutte (2005) Proceedings of SIGIR 2005, 601–2. PLSA solves non-negative matrix factorization under the generalized KL divergence (cited from its metadata; the publisher's page refused our request)
  • paper Evaluation Methods for Topic Models — Hanna M. Wallach, Iain Murray, Ruslan Salakhutdinov, and David Mimno (2009) Proceedings of ICML 2009, 1105–12. Section 4.2, Eq. 14: the harmonic mean method; Section 6.2: it wildly overestimated held-out likelihood; Algorithm 2: the Chib-style estimator; Algorithm 3: left-to-right evaluation
  • paper Approximate Bayesian Inference with the Weighted Likelihood Bootstrap — Michael A. Newton and Adrian E. Raftery (1994) Journal of the Royal Statistical Society, Series B 56 (1): 3–26. The harmonic-mean estimator of the marginal likelihood (Section 7, by Neal's discussion; the article itself is behind a paywall)
  • blog The Harmonic Mean of the Likelihood: Worst Monte Carlo Method Ever — Radford M. Neal (2008) The estimator's infinite variance, which may go undetected because the sample variance stays small
  • paper Reading Tea Leaves: How Humans Interpret Topic Models — Jonathan Chang, Jordan Boyd-Graber, Sean Gerrish, Chong Wang, and David M. Blei (2009) Advances in Neural Information Processing Systems 22. Models that score better on held-out likelihood can infer less semantically meaningful topics (word and topic intrusion)
  • paper Optimizing Semantic Coherence in Topic Models — David Mimno, Hanna M. Wallach, Edmund Talley, Miriam Leenders, and Andrew McCallum (2011) Proceedings of EMNLP 2011, 262–72. Section 4.2, Eq. 1: the coherence score from document co-occurrence counts
  • paper Automatic Evaluation of Topic Coherence — David Newman, Jey Han Lau, Karl Grieser, and Timothy Baldwin (2010) Proceedings of NAACL-HLT 2010, 100–108. PMI between a topic's top words, from co-occurrence in an external corpus
  • paper Rethinking LDA: Why Priors Matter — Hanna M. Wallach, David Mimno, and Andrew McCallum (2009) Advances in Neural Information Processing Systems 22. An asymmetric prior on the documents' proportions helps; an asymmetric prior on the topics does not
  • paper A Collapsed Variational Bayesian Inference Algorithm for Latent Dirichlet Allocation — Yee Whye Teh, David Newman, and Max Welling (2006) Advances in Neural Information Processing Systems 19 (MIT Press, 2007)
  • paper On Smoothing and Inference for Topic Models — Arthur Asuncion, Max Welling, Padhraic Smyth, and Yee Whye Teh (2009) Proceedings of UAI 2009, 27–34. Eq. 13: the CVB0 update, the collapsed sampler's conditional applied to expected counts; the main differences between inference algorithms are attributable to the amount of smoothing
  • paper The Structure of Economic News — Leland Bybee, Bryan Kelly, Asaf Manela, and Dacheng Xiu (2020) NBER Working Paper 26648. LDA fitted to the Wall Street Journal; published as 'Business News and Business Cycles,' Journal of Finance 79 (5): 3105–47 (2024), doi 10.1111/jofi.13377