Course contents 11 / 15

11 / 15 · Nonparametric and Topic Models

Dirichlet processes

Mixture models without a fixed number of components: the Dirichlet process as a limit of finite mixtures, the Chinese restaurant and stick-breaking constructions, how fast clusters appear, and collapsed Gibbs sampling.

On this page 10

Two hundred points in the plane form a few round clouds. How many? A mixture of Gaussians needs the answer before it starts. The usual remedy is to fit the mixture for K=2,3,…,8K = 2, 3, \dots, 8 and keep the KK with the best BIC or evidence. That treats a quantity we are uncertain about as a choice made from outside: each KK is a separate fit, the answer is one number with no uncertainty attached, and when new points arrive, perhaps from a cluster never seen before, the whole procedure starts again.

The Gaussian process let a regression function become as complex as the data required. Can a mixture do the same, with a number of clusters that is inferred together with everything else and grows as data arrive? It can, if we let the number of components go to infinity in the right way.

A Bayesian mixture with KK chosen in advance#

A finite Bayesian mixture draws the weights π=(π1,…,πK)\pi = (\pi_1, \dots, \pi_K) from a symmetric Dirichlet distribution and the cluster parameters θk\theta_k from a base distribution HH, then generates each point xix_i from one cluster:

π∼Dir(αK,…,αK),θk∼H,zi∼Categorical(π),xi∼F(θzi),\begin{aligned} \pi &\sim \mathrm{Dir}\big(\tfrac{\alpha}{K}, \dots, \tfrac{\alpha}{K}\big), \\ \theta_k &\sim H, \\ z_i &\sim \mathrm{Categorical}(\pi), \\ x_i &\sim F(\theta_{z_i}) , \end{aligned}

where ziz_i is the cluster label of point ii and F(θ)F(\theta) the distribution of a point in a cluster with parameter θ\theta. It is the Gaussian mixture of the EM note with priors on its parameters, and Gibbs sampling or variational inference fits it.

Two properties of the Dirichlet distribution, both from the conjugate priors note, do the work. It is conjugate to the categorical distribution: after observing labels with counts n1,…,nKn_1, \dots, n_K, the weights are Dir(α/K+n1,…,α/K+nK)\mathrm{Dir}(\alpha/K + n_1, \dots, \alpha/K + n_K). And it has a closed-form predictive. Integrating π\pi out,

p(zn+1=k∣z1,…,zn)=nk+α/Kn+α,p(z_{n+1} = k \mid z_1, \dots, z_n) = \frac{n_k + \alpha/K}{n + \alpha} ,

the posterior mean of πk\pi_k: the pseudo-count rule of the beta–binomial. The model still needs KK.

From the Dirichlet distribution to the Dirichlet process#

Let KK grow while the total concentration α\alpha stays fixed. Suppose the first nn labels occupy KnK_n clusters. Each occupied cluster keeps its predictive probability, and the K−KnK - K_n empty ones share the rest:

p(zn+1=k∣z1:n)=nk+α/Kn+α  →  nkn+α,p(zn+1 is new∣z1:n)=(K−Kn) α/Kn+α  →  αn+α.\begin{aligned} p(z_{n+1} = k \mid z_{1:n}) &= \frac{n_k + \alpha/K}{n + \alpha} \;\to\; \frac{n_k}{n + \alpha}, \\ p(z_{n+1} \text{ is new} \mid z_{1:n}) &= \frac{(K - K_n)\, \alpha/K}{n + \alpha} \;\to\; \frac{\alpha}{n + \alpha} . \end{aligned}

The limit is a well-defined prior on partitions of the data that never mentions KK: an occupied cluster attracts the next point in proportion to its size, and a new cluster opens with probability proportional to α\alpha (Neal, 2000; Rasmussen, 2000). The labels themselves lose their meaning; only which points share a cluster remains.

What becomes of the weights? There are infinitely many, so they no longer form a vector, but they still define a random distribution. Attach to each component its parameter θk∼H\theta_k \sim H and form G=∑kπkδθkG = \sum_k \pi_k \delta_{\theta_k}, which puts mass πk\pi_k at θk\theta_k; δθ\delta_\theta is a point mass at θ\theta. Ferguson (1973) characterized the law of GG directly. GG follows a Dirichlet process, G∼DP(α,H)G \sim \mathrm{DP}(\alpha, H), if for every partition of the parameter space into measurable sets A1,…,ArA_1, \dots, A_r,

(G(A1),…,G(Ar))∼Dir(αH(A1),…,αH(Ar)).\big(G(A_1), \dots, G(A_r)\big) \sim \mathrm{Dir}\big(\alpha H(A_1), \dots, \alpha H(A_r)\big) .

The definition is consistent because of the aggregation property of the Dirichlet distribution: merging two components of a Dirichlet vector gives a Dirichlet vector whose parameter is the sum of the two, so refining or coarsening the partition never contradicts itself.

Derivation of the aggregation property

Let (π1,…,πK)∼Dir(a1,…,aK)(\pi_1, \dots, \pi_K) \sim \mathrm{Dir}(a_1, \dots, a_K) and s=π1+π2s = \pi_1 + \pi_2. The change of variables from (π1,π2)(\pi_1, \pi_2) to (π1,s)(\pi_1, s) has Jacobian 1, so the density of (s,π3,…,πK)(s, \pi_3, \dots, \pi_K) is the Dirichlet density integrated over π1∈[0,s]\pi_1 \in [0, s]. Only two factors involve π1\pi_1, and the substitution π1=su\pi_1 = s u gives

∫0sπ1a1−1(s−π1)a2−1 dπ1=sa1+a2−1∫01ua1−1(1−u)a2−1 du=sa1+a2−1 B(a1,a2).\begin{aligned} \int_0^s \pi_1^{a_1 - 1} (s - \pi_1)^{a_2 - 1}\, d\pi_1 &= s^{a_1 + a_2 - 1} \int_0^1 u^{a_1 - 1} (1 - u)^{a_2 - 1}\, du \\ &= s^{a_1 + a_2 - 1}\, \mathrm B(a_1, a_2) . \end{aligned}

The density of (s,π3,…,πK)(s, \pi_3, \dots, \pi_K) is therefore proportional to sa1+a2−1∏k≥3πkak−1s^{a_1 + a_2 - 1} \prod_{k \ge 3} \pi_k^{a_k - 1}, which is Dir(a1+a2,a3,…,aK)\mathrm{Dir}(a_1 + a_2, a_3, \dots, a_K).

Consistent finite-dimensional laws do not by themselves give one random distribution GG that has all of them. Ferguson obtained it from Kolmogorov’s consistency theorem and by normalizing a gamma process, Blackwell and MacQueen from the Pólya urn and de Finetti’s theorem; Teh (2010), section “Dirichlet Process”, reviews both. The proofs need measure theory beyond the course; the stick-breaking construction below builds such a GG explicitly.

The partition {A,Ac}\{A, A^c\} gives (G(A),1−G(A))∼Dir(αH(A),α(1−H(A)))\big(G(A), 1 - G(A)\big) \sim \mathrm{Dir}\big(\alpha H(A), \alpha (1 - H(A))\big). Moments of a Dirichlet follow from its normalizing constant B(a)=∏kΓ(ak)/Γ(a0)\mathrm B(a) = \prod_k \Gamma(a_k) / \Gamma(a_0), with a0=∑kaka_0 = \sum_k a_k: multiplying the density by πk\pi_k raises aka_k by one, and Γ(x+1)=x Γ(x)\Gamma(x + 1) = x\, \Gamma(x) gives E[πk]=ak/a0\mathbb E[\pi_k] = a_k / a_0 and E[πk2]=ak(ak+1)/(a0(a0+1))\mathbb E[\pi_k^2] = a_k (a_k + 1) / \big(a_0 (a_0 + 1)\big). With ak=αH(A)a_k = \alpha H(A) and a0=αa_0 = \alpha:

E[G(A)]=αH(A)α=H(A),E[G(A)2]=αH(A) (αH(A)+1)α(α+1),var⁡[G(A)]=E[G(A)2]−H(A)2=H(A) (1−H(A))α+1.\begin{aligned} \mathbb E[G(A)] &= \frac{\alpha H(A)}{\alpha} = H(A), \\ \mathbb E[G(A)^2] &= \frac{\alpha H(A)\, \big(\alpha H(A) + 1\big)}{\alpha (\alpha + 1)}, \\ \operatorname{var}[G(A)] &= \mathbb E[G(A)^2] - H(A)^2 \\ &= \frac{H(A)\,\big(1 - H(A)\big)}{\alpha + 1} . \end{aligned}

The base distribution HH is the mean of the random distribution, and the concentration α\alpha says how tightly GG clusters around it. For a set with H(A)=0.5H(A) = 0.5, the mass that GG gives it has standard deviation 0.25/2=0.354\sqrt{0.25/2} = 0.354 when α=1\alpha = 1 and 0.25/100=0.05\sqrt{0.25/100} = 0.05 when α=99\alpha = 99.

Even with a large α\alpha, GG is discrete with probability one: a countable sum of point masses, however smooth HH is. The stick-breaking construction below writes GG as exactly such a sum (Ferguson, 1973; Teh, 2010, section “Stick-breaking Construction”). Discreteness is what makes it a clustering prior. Draws θ1,θ2,…\theta_1, \theta_2, \dots from GG repeat values, and points with the same value form a cluster.

The construction parallels the Gaussian process of the previous note, a comparison drawn both by Teh (2010) and in the notes of Vetrov and Kropotov’s course (Osokin, 2014):

Gaussian processDirichlet process
indexed byinputs xxsets AA
a draw isa function ffa distribution GG
finite-dimensional marginalsGaussianDirichlet
specified bymean mm and kernel kkbase HH and concentration α\alpha

The posterior of GG#

Optional depth: the conjugacy of the Dirichlet process itself. The rest of the note does not depend on it.

The Dirichlet process is conjugate to sampling from it. Given θ1,…,θn∼G\theta_1, \dots, \theta_n \sim G independently, the counts njn_j of the θi\theta_i in the sets AjA_j update the Dirichlet distribution of (G(A1),…,G(Ar))(G(A_1), \dots, G(A_r)) by Dirichlet–categorical conjugacy, for every partition at once. Each updated parameter can be written as

αH(Aj)+nj=(α+n) αH(Aj)+∑i=1nδθi(Aj)α+n,\alpha H(A_j) + n_j = (\alpha + n)\, \frac{\alpha H(A_j) + \sum_{i=1}^n \delta_{\theta_i}(A_j)}{\alpha + n} ,

a concentration α+n\alpha + n times one fixed distribution evaluated on AjA_j. These are the marginals of a Dirichlet process, so

G∣θ1:n  ∼  DP(α+n, αH+∑i=1nδθiα+n).G \mid \theta_{1:n} \;\sim\; \mathrm{DP}\Big(\alpha + n,\ \frac{\alpha H + \sum_{i=1}^n \delta_{\theta_i}}{\alpha + n}\Big) .

The posterior base distribution mixes the prior HH, with weight α/(α+n)\alpha/(\alpha + n), and the empirical distribution of the observations, with weight n/(α+n)n/(\alpha + n): α\alpha is the strength of the prior counted in observations. Its mean is the predictive distribution of the next draw, the Pólya urn of Blackwell and MacQueen (1973). The draw θn+1\theta_{n+1} equals one of the previous values θi\theta_i with probability 1/(α+n)1/(\alpha + n) each, or is a fresh draw from HH with probability α/(α+n)\alpha/(\alpha + n). Grouping equal values gives the limit rule above.

The Chinese restaurant process#

The limit rule has a picture, the Chinese restaurant process, named by Dubins and Pitman (Aldous, 1985; Teh, 2010). Customers enter a restaurant with infinitely many tables, one at a time. The first sits at the first table. Customer n+1n + 1 sits at an occupied table kk with probability nk/(n+α)n_k / (n + \alpha), or at a new table with probability α/(n+α)\alpha / (n + \alpha):

Figure

The Chinese restaurant process

The tables of the Chinese restaurantThree tables with four, two and one customer and an empty new table; arrows from the eighth customer to all four, with a probability under each table.n1 = 44/8 = 0.50n2 = 22/8 = 0.25n3 = 11/8 = 0.125newα/8 = 0.125customer 8123The tables of the Chinese restaurantThree tables with four, two and one customer and an empty new table; arrows from the eighth customer to all four, with a probability under each table.n1 = 44/8 = 0.50n2 = 22/8 = 0.25n3 = 11/8 = 0.125newα/8 = 0.125customer 8123
Concentration α = 1. Seven customers already sit at three tables (1). The eighth picks an occupied table k with probability proportional to the number n_k already there, 0.50, 0.25 and 0.125 (2), or a new table with probability proportional to α, 0.125 (3). The denominator n + α = 8 normalizes the four choices.

Tables are clusters and customers are data points. A large table attracts more customers, a rich-get-richer effect that produces a few large clusters and a tail of small ones. Multiplying the seating probabilities of all nn customers gives the probability of a partition into KK tables of sizes n1,…,nKn_1, \dots, n_K. The numerators contribute α\alpha for every table opened and 1,2,…,nk−11, 2, \dots, n_k - 1 for the later customers of table kk; the denominators are α,α+1,…,α+n−1\alpha, \alpha + 1, \dots, \alpha + n - 1 whatever happens. So

p(z1,…,zn)=αK Γ(α)Γ(α+n)∏k=1K(nk−1)! ,p(z_1, \dots, z_n) = \frac{\alpha^K\, \Gamma(\alpha)}{\Gamma(\alpha + n)} \prod_{k=1}^K (n_k - 1)! \,,

where Γ\Gamma is the gamma function. It depends only on the table sizes; the order in which the customers arrived drops out. The process is exchangeable: any customer can be treated as the last to arrive, the property the Gibbs sampler below relies on.

Check it on four customers with α=1\alpha = 1: customers 1, 2 and 4 at one table and customer 3 alone. Seating them in order and using the formula give the same number:

1⋅12⋅13⋅24=112,1⋅Γ(1)Γ(5)⋅2!⋅0!=224=112.\begin{aligned} 1 \cdot \tfrac12 \cdot \tfrac13 \cdot \tfrac24 &= \tfrac1{12}, \\ \frac{1 \cdot \Gamma(1)}{\Gamma(5)} \cdot 2! \cdot 0! = \frac{2}{24} &= \tfrac1{12} . \end{aligned}

How many clusters#

Customer ii opens a new table with probability α/(α+i−1)\alpha / (\alpha + i - 1), whatever happened before. The number of tables KnK_n is a sum of these independent indicators, so

E[Kn]=∑i=1nαα+i−1=α(ψ(α+n)−ψ(α))≈αlog⁡(1+nα)\begin{aligned} \mathbb E[K_n] &= \sum_{i=1}^n \frac{\alpha}{\alpha + i - 1} \\ &= \alpha\big(\psi(\alpha + n) - \psi(\alpha)\big) \\ &\approx \alpha \log\Big(1 + \frac n\alpha\Big) \end{aligned}

(Antoniak, 1974), where ψ\psi is the digamma function, the logarithmic derivative of Γ\Gamma. The middle form uses ψ(x+1)=ψ(x)+1/x\psi(x + 1) = \psi(x) + 1/x. The approximation replaces the sum by the integral α∫0ndt/(α+t)\alpha \int_0^n dt / (\alpha + t). Since 1/(α+t)1/(\alpha + t) decreases, each term α/(α+i)\alpha/(\alpha + i) lies between the integral over [i,i+1][i, i + 1] and α/(α+i+1)\alpha/(\alpha + i + 1). So the approximation is a little low, and the gaps add up to at most α(1/α−1/(α+n))<1\alpha\big(1/\alpha - 1/(\alpha + n)\big) < 1, a telescoping sum. For n≫αn \gg \alpha, E[Kn]≈αlog⁡n\mathbb E[K_n] \approx \alpha \log n: the number of clusters grows without bound, but only logarithmically, and doubling the data adds about αlog⁡2\alpha \log 2 clusters.

α\alphannexact E[Kn]\mathbb E[K_n]αlog⁡(1+n/α)\alpha \log(1 + n/\alpha)200 simulated restaurants
11005.1875.1874.6154.6155.235.23
5100027.0327.0326.5226.5226.8326.83

With α=1\alpha = 1 the exact value is the harmonic number h100h_{100}.

Figure

How many clusters the Chinese restaurant opens

The expected number of clustersThree curves growing like the logarithm of n, steeper for larger α. The dashed approximations run slightly below the solid curves.010203040110100100010⁴number of points n (log scale)α = 0.5α = 1α = 5exactα log(1 + n/α)The expected number of clustersThree curves growing like the logarithm of n, steeper for larger α. The dashed approximations run slightly below the solid curves.010203040110100100010⁴number of points n (log scale)α = 0.5α = 1α = 5exactα log(1 + n/α)
The expected number of occupied tables after n customers (solid) and the approximation α log(1 + n/α) (dashed), for α = 0.5, 1 and 5. On a log axis the curves become lines of slope α: with α = 1, 5.19 tables at n = 100 and 7.49 at n = 1000; with α = 5, 27.0 at n = 1000 and 38.5 at n = 10,000.

The concentration therefore sets the prior number of clusters, and the data can revise it. In practice α\alpha is either chosen from the expected number of clusters, by inverting the formula above, or given a gamma prior and sampled along with everything else (Escobar and West, 1995). It has a strong effect on the number of clusters and a weak one on predictions (Murphy, 2023, Supplementary Section 31.2.5).

Stick-breaking#

The restaurant describes the partition with GG integrated out. Sethuraman (1994) constructed GG itself. Break a stick of unit length: take a fraction v1v_1 of it as the first weight, a fraction v2v_2 of what remains as the second, and so on, with everything independent:

vk∼Beta(1,α),πk=vk∏j<k(1−vj),θk∼H,G=∑k=1∞πk δθk.\begin{aligned} v_k &\sim \mathrm{Beta}(1, \alpha), \\ \pi_k &= v_k \prod_{j \lt k} (1 - v_j), \\ \theta_k &\sim H, \\ G &= \sum_{k=1}^\infty \pi_k\, \delta_{\theta_k} . \end{aligned}

Then G∼DP(α,H)G \sim \mathrm{DP}(\alpha, H).

Why Beta(1,α)\mathrm{Beta}(1, \alpha)? Watch only the first table of the restaurant. It starts with one customer; call everything else “elsewhere”, with the weight α\alpha of a new table. Each later customer joins the first table with probability proportional to its size and goes elsewhere with probability proportional to the rest, n−n1+αn - n_1 + \alpha. Whichever side a customer joins grows by one. This is a Pólya urn started with weights 11 and α\alpha, and the long-run share of such an urn is Beta(1,α)\mathrm{Beta}(1, \alpha), the urn scheme for the Dirichlet distribution (Osokin, 2014, Section 1.2.3).

Why the long-run share is Beta(1, α)

Take mm later customers, kk of whom join the first table, in a fixed order. The joins contribute the numerators 1,2,…,k1, 2, \dots, k; the others α,α+1,…,α+m−k−1\alpha, \alpha + 1, \dots, \alpha + m - k - 1; the denominators are 1+α,…,m+α1 + \alpha, \dots, m + \alpha whatever the order. With B(1,α)=1/α\mathrm B(1, \alpha) = 1/\alpha,

P(sequence)=k!  Γ(α+m−k)/Γ(α)Γ(1+α+m)/Γ(1+α)=B(1+k, α+m−k)B(1,α)=∫01vk(1−v)m−k Beta(v∣1,α) dv.\begin{aligned} P(\text{sequence}) &= \frac{k!\; \Gamma(\alpha + m - k) / \Gamma(\alpha)}{\Gamma(1 + \alpha + m) / \Gamma(1 + \alpha)} \\ &= \frac{\mathrm B(1 + k,\, \alpha + m - k)}{\mathrm B(1, \alpha)} \\ &= \int_0^1 v^k (1 - v)^{m - k}\, \mathrm{Beta}(v \mid 1, \alpha)\, dv . \end{aligned}

The urn is therefore the same as drawing v∼Beta(1,α)v \sim \mathrm{Beta}(1, \alpha) once and then letting each customer join independently with probability vv. Given vv, the law of large numbers sends the table’s share to vv.

The customers who went elsewhere form a restaurant of their own, so the second table takes a Beta(1,α)\mathrm{Beta}(1, \alpha) share of them, and so on. The sticks list the clusters in the order the restaurant opens them. In 1000 simulated restaurants of 300 customers with α=2\alpha = 2, the first table’s share has mean 0.3380.338 and standard deviation 0.2410.241, and the second table’s share of the rest 0.3270.327 and 0.2330.233, against 0.3330.333 and 0.2360.236 for Beta(1,2)\mathrm{Beta}(1, 2).

The mean of Beta(1,α)\mathrm{Beta}(1, \alpha) is 1/(1+α)1/(1 + \alpha). By induction on TT, the mass left after TT sticks is ∏k≤T(1−vk)\prod_{k \le T} (1 - v_k): removing πT=vT∏k<T(1−vk)\pi_T = v_T \prod_{k < T}(1 - v_k) from ∏k<T(1−vk)\prod_{k < T} (1 - v_k) leaves ∏k≤T(1−vk)\prod_{k \le T} (1 - v_k). Since the vkv_k are independent, the expectation of each product is the product of expectations:

E[πk]=11+α(α1+α)k−1,E[1−∑k=1Tπk]=(α1+α)T.\begin{aligned} \mathbb E[\pi_k] &= \frac{1}{1 + \alpha}\Big(\frac{\alpha}{1 + \alpha}\Big)^{k - 1}, \\ \mathbb E\Big[1 - \sum_{k=1}^{T} \pi_k\Big] &= \Big(\frac{\alpha}{1 + \alpha}\Big)^{T} . \end{aligned}

The weights decay geometrically on average. With α=1\alpha = 1 the expected first three weights are 0.50.5, 0.250.25 and 0.1250.125; with α=5\alpha = 5 they are 0.1670.167, 0.1390.139 and 0.1160.116, and the mass left after T=20T = 20 sticks is (5/6)20=0.026(5/6)^{20} = 0.026 on average. A small α\alpha breaks off a few large pieces first, a large one many small pieces:

Figure

Stick-breaking for two values of α

Two broken sticksThe upper stick, α = 1, is broken into a few large pieces; the lower one, α = 5, into many small ones.α = 10.510.260.14first three: 0.91 (expected 0.875)α = 50.050.090.08first three: 0.23 (expected 0.421)Two broken sticksThe upper stick, α = 1, is broken into a few large pieces; the lower one, α = 5, into many small ones.α = 10.510.260.14first three: 0.91 (expected 0.875)α = 50.050.090.08first three: 0.23 (expected 0.421)
One random draw of the weights π_k = v_k ∏(1 − v_j), v_k ~ Beta(1, α), 30 pieces. With α = 1 the first three weights, 0.512, 0.259 and 0.140, take 0.91 of the stick (0.875 on average); with α = 5 they are 0.053, 0.093 and 0.084, together 0.23 (0.421 on average).

The expected leftover mass is what makes truncation safe. Replace the infinite sum by TT sticks, the last one taking the rest. The truncated and the full GG agree on the first T−1T - 1 sticks and differ only in how they place the remaining mass, so their total variation distance is at most that mass, (α/(1+α))T−1(\alpha/(1 + \alpha))^{T - 1} on average. Ishwaran and James (2001) bound the resulting change in the distribution of nn observations. Truncated stick-breaking is the basis of variational inference for Dirichlet process mixtures (Blei and Jordan, 2006).

Dirichlet process mixtures#

A Dirichlet process mixture uses GG as the mixing distribution of a mixture model:

G∼DP(α,H),θi∣G∼G,xi∣θi∼F(θi).\begin{aligned} G &\sim \mathrm{DP}(\alpha, H), \\ \theta_i \mid G &\sim G, \\ x_i \mid \theta_i &\sim F(\theta_i) . \end{aligned}

Because GG is discrete, the θi\theta_i repeat, and points with equal parameters form a cluster. Integrating GG out gives the form used for inference: the labels follow the Chinese restaurant process, each occupied cluster gets a parameter θk∼H\theta_k \sim H, and xi∼F(θzi)x_i \sim F(\theta_{z_i}). It is the finite mixture of the first section in the limit K→∞K \to \infty, the infinite mixture model (Rasmussen, 2000). For Gaussian clusters, F(x∣θ)F(x \mid \theta) is a Gaussian with parameters θ\theta and HH a prior on them.

Collapsed Gibbs sampling with the restaurant#

The posterior over partitions has no closed form, but its conditionals do. With a conjugate HH, the cluster parameters can be integrated out, and the sampler works on the labels alone: the collapsed Gibbs sampler of the Gibbs sampling note, here Algorithm 3 of Neal (2000). By Bayes’ rule, the label of point ii given everything else is proportional to its prior given the other labels times the likelihood of xix_i. By exchangeability, point ii can be treated as the last customer, so the prior is the seating rule, n−i,k/(n−1+α)n_{-i,k}/(n - 1 + \alpha) or α/(n−1+α)\alpha/(n - 1 + \alpha), with a denominator that does not depend on kk. Given the partition, the points of a cluster share one parameter drawn from HH, independently of other clusters, so the likelihood is the cluster’s predictive density of xix_i. Remove the point from its table, then reseat it with

p(zi=k∣z−i,x)  ∝  {n−i,k  p(xi∣x−i,k)occupied k,α  p(xi)a new cluster.p(z_i = k \mid z_{-i}, x) \;\propto\; \begin{cases} n_{-i,k}\; p(x_i \mid x_{-i,k}) & \text{occupied } k, \\[2pt] \alpha\; p(x_i) & \text{a new cluster.} \end{cases}

Here a subscript −i-i means “without point ii”: n−i,kn_{-i,k} and x−i,kx_{-i,k} are the size and the points of cluster kk without it. p(xi∣x−i,k)=∫F(xi∣θ) p(θ∣x−i,k) dθp(x_i \mid x_{-i,k}) = \int F(x_i \mid \theta)\, p(\theta \mid x_{-i,k})\, d\theta is the posterior predictive of that cluster, and p(xi)=∫F(xi∣θ) H(dθ)p(x_i) = \int F(x_i \mid \theta)\, H(d\theta) the prior predictive of an empty one. The first factor is the restaurant’s prior, the second how well the cluster explains the point. A cluster emptied by removing point ii disappears; choosing “new” creates one. The uncollapsed alternative keeps the θk\theta_k and samples them in turn (Neal, 2000; Osokin, 2014, Section 3.2.2).

For Gaussian clusters with known variance, let F(x∣μ)=N(μ,σ2I)F(x \mid \mu) = \mathcal N(\mu, \sigma^2 I) in dd dimensions and H=N(μ0,τ2I)H = \mathcal N(\mu_0, \tau^2 I). For a cluster holding mm points with sum ss, precisions add, as in the normal update:

λ=1τ2+mσ2,μ^=1λ(μ0τ2+sσ2),p(x∣cluster)=N(x  ∣  μ^, (1λ+σ2)I),\begin{aligned} \lambda &= \frac{1}{\tau^2} + \frac{m}{\sigma^2}, \\ \hat\mu &= \frac{1}{\lambda}\Big(\frac{\mu_0}{\tau^2} + \frac{s}{\sigma^2}\Big), \\ p(x \mid \text{cluster}) &= \mathcal N\Big(x \;\Big|\; \hat\mu,\ \big(\tfrac1\lambda + \sigma^2\big) I\Big) , \end{aligned}

the uncertainty about the cluster mean plus the noise: a new point is x=μ+ex = \mu + e with μ∼N(μ^,λ−1I)\mu \sim \mathcal N(\hat\mu, \lambda^{-1} I) and independent noise e∼N(0,σ2I)e \sim \mathcal N(0, \sigma^2 I), and the variances of independent Gaussians add. With m=0m = 0 this is the prior predictive N(μ0,(τ2+σ2)I)\mathcal N(\mu_0, (\tau^2 + \sigma^2) I) of a new cluster. A sweep keeps the counts and sums of each cluster, so reseating a point costs O(Knd)O(K_n d).

In one dimension, take σ2=1\sigma^2 = 1, τ2=10\tau^2 = 10, μ0=0\mu_0 = 0 and α=1\alpha = 1. The other points form cluster A, five points with mean 0, and cluster B, three points with mean 4. Reseat xi=3x_i = 3:

prior weightpredictive meanpredictive variancedensity at 3probability
A55001.1961.1960.00850.00850.0470.047
B333.8713.8711.3231.3230.26040.26040.8650.865
newα=1\alpha = 10011110.07990.07990.0880.088

Cluster B wins although it is smaller, because the point is close to it. A new cluster is more likely than cluster A, despite a prior weight five times smaller: its predictive is wide and gives some density everywhere, while A’s is narrow and centred three units away. For a non-conjugate HH the integrals have no closed form, and Algorithm 8 of Neal (2000) replaces them with a few auxiliary parameters drawn from HH.

An experiment: four clusters, an unknown number#

The Code section draws 200 points in the plane from four round clusters of 80, 60, 40 and 20 points with standard deviation 0.5, centred at the corners of a square of side 4. It runs the collapsed sampler with the true σ2=0.25\sigma^2 = 0.25, a vague prior on the means (τ=3\tau = 3 around the data mean) and α=1\alpha = 1, for 100 sweeps, starting with all points in one cluster.

With seed 1 the final state has clusters of 80, 60, 40 and 20 points, an adjusted Rand index of 1.01.0 against the truth, and the same log joint probability log⁡p(x,z)=−601.1\log p(x, z) = -601.1 as the true partition.

The number of clusters is still a distribution. Over sweeps 21–100 of that run the sampler has four clusters in 21% of the sweeps and 5.2 on average, because points in the tails of the clusters keep opening and closing clusters of one or two points. The concentration sets the price of a new cluster:

α\alphamean number of clustersshare of sweeps with four
0.14.084.0892%
15.25.221%
1011.4811.480%

scikit-learn’s BayesianGaussianMixture with a Dirichlet process prior, the variational method truncated at 10 sticks, agrees. It gives weights 0.3970.397, 0.2810.281, 0.1950.195 and 0.1030.103 to four components and at most 0.0050.005 to each of the other six, against the data’s proportions 0.40.4, 0.30.3, 0.20.2 and 0.10.1.

Where it breaks#

Run the same sampler from five seeds, 0 to 4. Only seed 1 ends at the true partition. Seed 0 ends with the four clusters plus three stray points, close enough. The other three end with the 80-point cluster still split:

seedthe 80-point cluster ends aslog⁡p(x,z)\log p(x, z)below the truth
270+6+470 + 6 + 4−641.9-641.940.8 nats
371+971 + 9−623.2-623.222.1 nats
461+1961 + 19−642.6-642.641.5 nats

The sampler has not mixed, and it cannot within 100 sweeps. To merge two halves of a cluster it must move points one at a time, and every intermediate state, with a few points stranded between the halves, is much less probable than either end. Split–merge moves, which propose to merge or split whole clusters in one Metropolis–Hastings step, fix this (Jain and Neal, 2004); comparing runs from several starts is how you find out that you need them.

The prior itself has two limits. The single parameter α\alpha sets both the expected number of clusters and the rich-get-richer pattern of their sizes. Data with many clusters of similar size, or with a power law of cluster sizes, need another prior; the Pitman–Yor process adds a discount dd, so that a table of nkn_k customers attracts nk−dn_k - d and a new table α+Kd\alpha + K d, and the number of clusters then grows faster than logarithmically (Teh, 2010; Murphy, 2023, Supplementary Section 31.3). And even when the data come from a finite mixture of the assumed form, the posterior keeps mass on extra small clusters and does not concentrate on the true number as nn grows. Miller and Harrison (2013) show it in the simplest case: data from one standard normal, modelled by a Dirichlet process mixture of unit-variance normals, where the posterior probability of a single cluster goes to 0. The intuition: every point keeps a prior chance, proportional to α\alpha, of opening a cluster, and a tiny cluster in the tail costs almost nothing in likelihood. For density estimation this does no harm; for counting clusters it does. The process chooses how many components, while their shape is still set by FF: a curved or heavy-tailed cluster is covered by several Gaussians.

What you should remember#

  • DP(α,H)\mathrm{DP}(\alpha, H) is a random discrete distribution whose masses on any partition are Dirichlet: mean HH, concentration α\alpha.
  • It is the K→∞K \to \infty limit of a mixture with a Dir(α/K,…,α/K)\mathrm{Dir}(\alpha/K, \dots, \alpha/K) prior on the weights.
  • Chinese restaurant: join table kk with probability nk/(n+α)n_k/(n + \alpha), open one with α/(n+α)\alpha/(n + \alpha); exchangeable.
  • E[Kn]=∑i=1nα/(α+i−1)≈αlog⁡(1+n/α)\mathbb E[K_n] = \sum_{i=1}^n \alpha/(\alpha + i - 1) \approx \alpha \log(1 + n/\alpha).
  • Stick-breaking with Beta(1,α)\mathrm{Beta}(1, \alpha) sticks builds GG; the leftover after TT sticks is (α/(1+α))T(\alpha/(1 + \alpha))^T on average.
  • Collapsed Gibbs reseats each point with weight n−i,kn_{-i,k} times the cluster’s predictive, or α\alpha times the prior predictive; it mixes slowly between partitions.

Code#

The restaurant and the sticks, the reseating example, then a collapsed Gibbs sampler for a Dirichlet process mixture of Gaussians on 2-D data, its sensitivity to the start and to α\alpha, and scikit-learn’s variational version. It runs in about fifteen seconds; exact numbers can vary across platforms and library versions.

import numpy as np
from scipy.special import digamma, gammaln, logsumexp
from scipy.stats import norm
from sklearn.metrics import adjusted_rand_score
from sklearn.mixture import BayesianGaussianMixture

# the Chinese restaurant process: simulated number of tables against the exact expectation
def crp(n, alpha, rng):
    counts = []
    for i in range(n):                                   # customer i + 1 sees i seated customers
        p = np.array(counts + [alpha]) / (i + alpha)
        k = rng.choice(len(p), p=p)
        if k == len(counts): counts.append(1)
        else: counts[k] += 1
    return counts

rng = np.random.default_rng(0)
for alpha, n in ((1.0, 100), (5.0, 1000)):
    sim = np.mean([len(crp(n, alpha, rng)) for _ in range(200)])
    exact = alpha * (digamma(alpha + n) - digamma(alpha))     # = sum of alpha / (alpha + i) over i = 0, ..., n - 1
    print(alpha, n, round(sim, 2), round(exact, 3), round(alpha * np.log(1 + n / alpha), 3))
# 1.0 100 5.23 5.187 4.615 | 5.0 1000 26.83 27.031 26.517

# stick-breaking: expected weights (1/(1+alpha)) (alpha/(1+alpha))^(k-1), and the expected mass left after 20 sticks
for alpha in (1.0, 5.0):
    print(alpha, [round(1 / (1 + alpha) * (alpha / (1 + alpha)) ** (k - 1), 3) for k in (1, 2, 3)], round((alpha / (1 + alpha)) ** 20, 4))
# 1.0 [0.5, 0.25, 0.125] 0.0 | 5.0 [0.167, 0.139, 0.116] 0.0261

# why the sticks are Beta(1, alpha): the share of customers at the first table, and the second table's share of the rest
r2 = np.random.default_rng(2)
sims = [crp(300, 2.0, r2) for _ in range(1000)]
v1 = np.array([c[0] / 300 for c in sims])
v2 = np.array([c[1] / (300 - c[0]) for c in sims])
print(v1.mean().round(3), v1.std().round(3), v2.mean().round(3), v2.std().round(3))   # Beta(1, 2): mean 0.333, sd 0.236
# 0.338 0.241 0.327 0.233

# reseating x = 3 in one dimension: sigma^2 = 1, tau^2 = 10, mu0 = 0, alpha = 1; cluster A (5 points, sum 0), B (3 points, sum 12), new
lam = 0.1 + np.array([5, 3, 0])                              # posterior precisions of the cluster means
mean, var = np.array([0.0, 12.0, 0.0]) / lam, 1 / lam + 1   # predictive mean and variance of each cluster
w = np.array([5, 3, 1.0]) * norm.pdf(3, mean, np.sqrt(var))
print(mean.round(3), var.round(3), (w / w.sum()).round(3))    # [0. 3.871 0.] [1.196 1.323 11.] [0.047 0.865 0.088]

# 2-D data: four spherical clusters of 80, 60, 40 and 20 points with standard deviation 0.5
centres = np.array([[0.0, 0.0], [4.0, 0.0], [0.0, 4.0], [4.0, 4.0]])
sizes = (80, 60, 40, 20)
truth = np.repeat(np.arange(4), sizes)
X = np.vstack([c + 0.5 * rng.normal(size=(m, 2)) for c, m in zip(centres, sizes)])
n, d = X.shape

# DP mixture of Gaussians with known covariance s2 I and a conjugate prior N(mu0, t2 I) on each cluster mean
s2, t2, mu0 = 0.25, 9.0, X.mean(axis=0)

def log_pred(x, cnt, tot):
    """log predictive density of x for clusters with cnt points summing to tot (cnt = 0: a new cluster)"""
    prec = 1 / t2 + cnt / s2                             # posterior precision of the cluster mean
    mean = (mu0 / t2 + tot / s2) / prec[:, None]
    var = 1 / prec + s2                                  # posterior variance of the mean plus the noise
    return -0.5 * d * np.log(2 * np.pi * var) - 0.5 * ((x - mean) ** 2).sum(axis=1) / var

def collapsed_gibbs(X, alpha, sweeps, rng):
    z = np.zeros(len(X), dtype=int)                      # start with every point in one cluster
    cnt, tot = np.array([len(X)]), X.sum(axis=0, keepdims=True)
    trace = []
    for _ in range(sweeps):
        for i in rng.permutation(len(X)):
            k = z[i]; cnt[k] -= 1; tot[k] -= X[i]        # take point i out of its cluster
            if cnt[k] == 0:                              # drop an empty cluster: move the last one into its slot
                cnt[k], tot[k] = cnt[-1], tot[-1]; z[z == len(cnt) - 1] = k
                cnt, tot = cnt[:-1], tot[:-1]
            logp = np.log(np.append(cnt, alpha)) + log_pred(X[i], np.append(cnt, 0), np.vstack([tot, np.zeros(d)]))
            k = rng.choice(len(logp), p=np.exp(logp - logsumexp(logp)))   # n_k p(x | cluster k), or alpha p(x)
            if k == len(cnt):                            # open a new cluster
                cnt, tot = np.append(cnt, 0), np.vstack([tot, np.zeros(d)])
            z[i] = k; cnt[k] += 1; tot[k] += X[i]
        trace.append(len(cnt))
    return z, cnt, np.array(trace)

def log_joint(z, alpha):                                 # log p(x, z): CRP prior times the cluster marginal likelihoods
    ks, cs = np.unique(z, return_counts=True)
    lp = len(ks) * np.log(alpha) + gammaln(alpha) - gammaln(alpha + len(z)) + gammaln(cs).sum()
    for k in ks:                                         # chain rule: each point given the earlier points of its cluster
        Xk = X[z == k]
        cum = np.vstack([np.zeros(d), np.cumsum(Xk, axis=0)[:-1]])
        lp += sum(log_pred(x, np.array([j]), cum[j][None]) [0] for j, x in enumerate(Xk))
    return lp

print(round(log_joint(truth, 1.0), 1))                   # -601.1 for the true partition
for seed in range(5):                                    # final sizes, adjusted Rand index, log p(x, z), counts of K = 4..8 after burn-in
    z, cnt, trace = collapsed_gibbs(X, 1.0, 100, np.random.default_rng(seed))
    print(seed, np.sort(cnt)[::-1], round(adjusted_rand_score(truth, z), 3), round(log_joint(z, 1.0), 1), np.bincount(trace[20:], minlength=9)[4:9])
# 0 [80 59 38 20  2  1] 0.984 -607.0 [22 32 25  1  0]
# 1 [80 60 40 20] 1.0 -601.1 [17 36 21  6  0]
# 2 [70 59 38 20  6  4  2  1] 0.892 -641.9 [20 30 11 11  7]
# 3 [71 60 40 20  9] 0.921 -623.2 [ 0 23 28 16  8]
# 4 [61 60 35 20 19  5] 0.828 -642.6 [ 4 18 23 18 13]
for alpha in (0.1, 1.0, 10.0):                           # the number of clusters after 20 sweeps of burn-in: mean, share of K = 4
    K = collapsed_gibbs(X, alpha, 100, np.random.default_rng(1))[2][20:]
    print(alpha, round(K.mean(), 2), round((K == 4).mean(), 2))
# 0.1 4.08 0.92 | 1.0 5.2 0.21 | 10.0 11.48 0.0

# the variational alternative: scikit-learn's truncated stick-breaking with 10 components
bgm = BayesianGaussianMixture(n_components=10, weight_concentration_prior_type='dirichlet_process',
                              weight_concentration_prior=1.0, covariance_type='spherical', max_iter=1000, random_state=0).fit(X)
print(np.sort(bgm.weights_)[::-1].round(3), (bgm.weights_ > 0.01).sum())
# [0.397 0.281 0.195 0.103 0.005 0.005 0.005 0.005 0.002 0.001] 4

Next#

A Dirichlet process mixture gives each data point one cluster. A document is not like that: an article on the economics of football mixes words from a sports topic and from an economics topic, and a collection of documents shares the same topics in different proportions. The next note gives every document its own mixture over a common set of topics, latent Dirichlet allocation, and fits it with a collapsed Gibbs sampler like the one above and with variational inference. Its nonparametric version, the hierarchical Dirichlet process, shares the atoms of one Dirichlet process among many (Teh et al., 2006).

References#