Module contents
Lesson 18 of 27Core 110 min

Variational inference I: the ELBO, mean field and CAVI

Variational inference turns integration into optimization: it seeks the distribution closest to the posterior in a tractable family by maximizing the ELBO, the same EM bound from m12 with q restricted to a family. We study mean field and its consequences, coordinate ascent (CAVI), closed updates in conjugate-exponential models and variational EM, with Bayesian Gaussian mixtures and LDA as complete examples.

After this lesson you can

  • Formulate inference as ELBO optimization and compare it with Laplace, EP and MCMC in bias, cost and scalability.
  • Measure the ELBO-to-log-evidence gap and explain the effect of KL(q ‖ p) direction from m07 on variational dispersion.
  • Derive the optimal mean-field factor update, log q_j* = E_{-j}[log p] + constant.
  • Implement CAVI for a Bayesian Gaussian mixture and LDA, testing ELBO monotonicity.
  • Prove that mean field underestimates variances in a correlated Gaussian.

Before you start

Turning integration into optimization

A posterior may be easy to write and hard to normalize. Laplace approximates it around a mode; EP matches factor moments; MCMC and the particle filter use samples and have Monte Carlo error. Variational inference offers another compromise: choose a manageable family, search it for a nearby distribution and accept that the chosen shape can introduce bias. There is no universal winner: cost, geometry, dimension and required accuracy matter.

For data xx and latents zz, let q(z)q(z) be a density whose support is contained in that of p(x,z)p(x,z). Variational inference maximizes the evidence lower bound (ELBO)

L(q)=Eq[log⁡p(x,z)−log⁡q(z)]\mathcal L(q)=\E_q[\log p(x,z)-\log q(z)]

in a family Q\mathcal Q. If p(x)>0p(x)>0 and integrals exist, the exact identity is

log⁡p(x)=L(q)+KL⁡(q(z) ∥ p(z∣x)).\log p(x)=\mathcal L(q)+\KL(q(z)\,\|\,p(z\mid x)).

It follows by substituting log⁡p(x,z)=log⁡p(z∣x)+log⁡p(x)\log p(x,z)=\log p(z\mid x)+\log p(x) and using that qq integrates to one. KL is nonnegative, so ELBO is a lower bound; maximizing it is equivalent to minimizing that KL for fixed data and model. This is the same EM bound, but qq is restricted to a tractable family. ELBO improvement does not imply evidence changed: only the gap may have shrunk.

InteractiveThe family determines the gap
  • Posterior p
  • Approximation q
Contours at 20 %, 50 % and 80 % of each density maximum, not probability regions.
  • ELBO
  • KL gap
  • log evidence
Variational family
log evidence−3.183
ELBO−4.448
Approximate KL gap1.265
Select mean field, full Gaussian or a two-Gaussian mixture. Contours compare relative density levels. Evidence is fixed and its difference from ELBO is approximate KL.

The figure’s model is a,b∼iidN(0,1)a,b\iid\Normal(0,1) and y∣a,b∼N(ab,0.42)y\mid a,b\sim\Normal(ab,0.4^2) with y=2y=2. Its posterior has two curved regions: both two positive signs and two negative signs explain the product. Evidence is integrated in one dimension using Y∣a∼N(0,a2+0.42)Y\mid a\sim\Normal(0,a^2+0.4^2); displayed solutions were obtained by optimizing ELBO from multiple starts. The mixture uses two equal-weight components with common covariance; its entropy is integrated by order-40 Gauss-Hermite, also checked with orders 20, 60 and 80. Numbers are found solutions and numerical quadratures, not a global-optimum certificate. Model and approximation parameters are in the figure data.

This cell recalculates evidence and ELBO with found parameters rounded to eight decimals. Mixture entropy is not the average of component entropies: integrate −log⁡q-\log q under the mixture itself. The two components are symmetric in this solution.

[ ]Check the gap in the multiplicative modelBrowser
import numpy as np
from scipy.integrate import quad
from numpy.polynomial.hermite import hermgauss

y_obs, noise = 2., .4
def evidence_integrand(a):
    var=a*a+noise**2
    return np.exp(-a*a/2)/np.sqrt(2*np.pi)*np.exp(-y_obs*y_obs/(2*var))/np.sqrt(2*np.pi*var)
logZ=np.log(quad(evidence_integrand,-np.inf,np.inf,epsabs=1e-12)[0])

def expected_log_joint(m,S):
    a,b=m; va,vb=S[0,0],S[1,1]; c=S[0,1]
    eab=a*b+c
    ea2b2=a*a*b*b+a*a*vb+b*b*va+4*a*b*c+va*vb+2*c*c
    return -np.log(2*np.pi)-.5*(a*a+b*b+va+vb)-.5*(np.log(2*np.pi*noise**2)+(y_obs*y_obs-2*y_obs*eab+ea2b2)/noise**2)

nodes,w=hermgauss(40)
z=np.stack(np.meshgrid(nodes,nodes,indexing='ij'),axis=-1).reshape(-1,2)*np.sqrt(2)
weights=np.outer(w,w).ravel()/np.pi
def mixture_bound(means,S):
    L=np.linalg.cholesky(S); norm=-np.log(2*np.pi)-np.log(np.diag(L)).sum()
    eqlogq=0.
    for m in means:
        [email protected]
        logps=[]
        for other in means:
            diff=np.linalg.solve(L,(points-other).T).T
            logps.append(norm-.5*np.sum(diff*diff,axis=1))
        logq=np.logaddexp.reduce(np.stack(logps),axis=0)-np.log(len(means))
        eqlogq+=np.dot(weights,logq)/len(means)
    return np.mean([expected_log_joint(m,S) for m in means])-eqlogq

mf_mean=np.array([1.32664985,1.32664993]); mf_cov=np.diag([.0800000053,.0800000218])
full_mean=np.array([1.38060500,1.38060503]); full_cov=np.array([[.15001258,-.10804141],[-.10804141,.15001259]])
for name,means,S in [('campo medio',[mf_mean],mf_cov),('completa',[full_mean],full_cov),('mezcla',[full_mean,-full_mean],full_cov)]:
    bound=mixture_bound(means,S)
    print(name,'ELBO',round(bound,4),'KL',round(logZ-bound,4))
print('log evidencia',round(logZ,4))

Direction matters. When minimizing KL⁡(q∥p)\KL(q\|p), placing mass of qq where pp has almost no density is costly; a unimodal family may prefer one mode and omit another. This is a tendency dependent on problem and family, not a theorem that every variational approximation always underestimates all uncertainty. Even an approximation with high ELBO can be poor for a particular decision quantity.

Mean field and coordinates

A mean-field family factors q(z)=∏j=1mqj(zj)q(z)=\prod_{j=1}^m q_j(z_j). Independence is a restriction of the approximation, not necessarily the model. Hold every factor except qjq_j fixed and define hj(zj)=Eq−j[log⁡p(x,z)]h_j(z_j)=\E_{q_{-j}}[\log p(x,z)]. Then

log⁡qj∗(zj)=hj(zj)−log⁡ ⁣∫ehj(u) ⁣du,\log q_j^*(z_j)=h_j(z_j)-\log\!\int e^{h_j(u)}\dd u,

if the integral is finite. The proof is direct: ELBO terms depending on qjq_j are ∫qjhj−∫qjlog⁡qj\int q_jh_j-\int q_j\log q_j, equivalent to a constant minus KL⁡(qj∥q~j)\KL(q_j\|\tilde q_j) with q~j∝ehj\tilde q_j\propto e^{h_j}. KL is minimized at zero. This underlies coordinate ascent variational inference (CAVI): update one factor, then another, and repeat. An exact update does not decrease ELBO, but the joint problem can have local maxima.

For a Gaussian posterior p=N(μ,Λ−1)p=\Normal(\vb\mu,\mat\Lambda\inv), the update of factor jj has precision Λjj\Lambda_{jj} and mean μj−Λjj−1∑k≠jΛjk(mk−μk)\mu_j-\Lambda_{jj}^{-1}\sum_{k\ne j}\Lambda_{jk}(m_k-\mu_k). At a fixed point means solve Λ(m−μ)=0\mat\Lambda(\vb m-\vb\mu)=0, so m=μ\vb m=\vb\mu if Λ≻0\mat\Lambda\succ0, but each variance remains 1/Λjj1/\Lambda_{jj}. By the Schur complement, that conditional variance does not exceed marginal Σjj\Sigma_{jj}.

InteractiveMean field shrinks
  • True posterior
  • Optimal mean field
0.80
True marginal variance1.00
Variance of each q factor0.360
KL(q ‖ p)0.511
Move the true Gaussian correlation. Curves are ellipses at Mahalanobis distance 2; each factor variance is the conditional 1−ρ21-\rho^2, while the true marginal remains 1.

With correlation 0.90.9, each factor variance is 1−0.92=0.191-0.9^2=0.19, although each true marginal has variance 1. The optimal KL in this example is −12log⁡(1−ρ2)-\tfrac12\log(1-\rho^2). The conclusion holds for this Gaussian mean field and that KL; it does not establish that a more general family cannot overestimate some variance.

In conjugate exponential models, expectations of sufficient statistics from other factors are added to the prior’s natural parameters. Conditionals have the same family as the updated factor. The Markov blanket identifies which joint terms affect each factor: others disappear into the normalization constant.

Mixtures: responsibilities and pruning

Consider KK components, π∼Dir⁡(α01)\vb\pi\sim\operatorname{Dir}(\alpha_0\vb1), μk∼N(0,τ2I)\vb\mu_k\sim\Normal(\vb0,\tau^2\mat I), zi∣π∼Cat⁡(π)z_i\mid\vb\pi\sim\operatorname{Cat}(\vb\pi) and xi∣zi=k,μk∼N(μk,σ2I)\vb x_i\mid z_i=k,\vb\mu_k\sim\Normal(\vb\mu_k,\sigma^2\mat I), with σ2\sigma^2 known. Use q(π)∏kq(μk)∏iq(zi)q(\vb\pi)\prod_kq(\vb\mu_k)\prod_iq(z_i). For responsibilities rik=q(zi=k)r_{ik}=q(z_i=k) and Nk=∑irikN_k=\sum_i r_{ik},

αk=α0+Nk,sk2=(τ−2+Nk/σ2)−1,mk=sk2σ2∑irikxi.\alpha_k=\alpha_0+N_k,\quad s_k^2=\left(\tau^{-2}+N_k/\sigma^2\right)^{-1},\quad \vb m_k=\frac{s_k^2}{\sigma^2}\sum_i r_{ik}\vb x_i.

The update of rikr_{ik} normalizes exponentials of ψ(αk)−ψ(∑jαj)−[∥xi−mk∥2+dsk2]/(2σ2)\psi(\alpha_k)-\psi(\sum_j\alpha_j)-[\norm{\vb x_i-\vb m_k}^2+d s_k^2]/(2\sigma^2). Term dsk2d s_k^2 integrates mean uncertainty; replacing it with a single point gives another approximation. A small Dirichlet prior favors sparse concentrations but does not guarantee recovering the true number of groups.

InteractiveCAVI and extra components
  • Simulated data
  • Variational means
0
ELBO−299.73
Weights greater than 0.0110
Advance iteration. Circles are variational means and their radius encodes expected weight; the lower chart shows ELBO for that same run.

Data are 40 samples from each of three isotropic Gaussians centered at (−2,0)(-2,0), (2,0)(2,0) and (0,2.5)(0,2.5), with standard deviation 0.35 and seed 7. The inferred model uses 10 components, α0=0.1\alpha_0=0.1, τ2=9\tau^2=9 and σ2=0.16\sigma^2=0.16; asymmetric initialization uses seed 3. The value of σ2\sigma^2 is a model assumption, distinct from generating variance 0.3520.35^2. In this run three weights remain dominant; the smallest ELBO increase is of rounding order. The figure comes from the lab below.

In a complete Bayesian mixture, precisions are also unknown. With a Normal-Wishart prior for (μk,Λk)(\vb\mu_k,\mat\Lambda_k), updates add weighted counts and statistics to the prior; Elog⁡∣Λk∣\E\log|\mat\Lambda_k| uses digammas and likelihood uses d/βk+νk(x−mk)⊤Wk(x−mk)d/\beta_k+\nu_k(\vb x-\vb m_k)\T\mat W_k(\vb x-\vb m_k). The lab calculates the complete ELBO, including the cost of weight and Normal-Wishart factors, not just likelihood. Solutions can depend on initialization and prior.

Variational EM and topic models

Variational EM alternates approximate optimization of qq with a model-parameter update that increases the same ELBO. In exact EM the E-step uses the exact posterior and the bound touches log likelihood; with mean field the gap may remain positive. An ELBO increase each step does not mean each ELBO is evidence or a global maximum is reached.

In LDA, with fixed topics βkv\beta_{kv} and document prior Dir⁡(α)\operatorname{Dir}(\vb\alpha), approximation q(θd)=Dir⁡(γd)q(\theta_d)=\operatorname{Dir}(\gamma_d) and q(zdn)=Cat⁡(ϕdn)q(z_{dn})=\operatorname{Cat}(\phi_{dn}) leads to

ϕdnk∝βk,wdnexp⁡ ⁣[ψ(γdk)−ψ ⁣(∑jγdj)],γdk=αk+∑nϕdnk.\phi_{dnk}\propto\beta_{k,w_{dn}}\exp\!\left[\psi(\gamma_{dk})-\psi\!\left(\sum_j\gamma_{dj}\right)\right],\qquad \gamma_{dk}=\alpha_k+\sum_n\phi_{dnk}.

These equations alternate until convergence. With unknown topics as parameters, the M-step normalizes expected word counts by topic; random topics require additional factors and prior terms. Topic names are interchangeable: when comparing two fits, align components before measuring their difference. The original work of Blei, Ng and Jordan develops variational inference and EM for LDA.

Bethe free energy offers another variational approximation over local marginals and consistency constraints. On trees it connects with exact message passing; with cycles it can have multiple stationary points and loopy message passing has no general convergence guarantee. It is not the same mean-field ELBO: the family and entropy approximation change.

Lab: mixture with known covariance

The following code generates the figure’s data and runs mean-field updates. ELBO sums expected likelihood and categorical term and subtracts KLs of Dirichlet and Gaussian factors from their priors. We measure monotonicity after each complete cycle, not after an initialization that is not a coordinate update.

[ ]CAVI with Gaussian meansBrowser
import numpy as np
from scipy.special import digamma, gammaln, logsumexp

def make_data():
    rg = np.random.default_rng(7)
    centers = np.array([[-2.,0.],[2.,0.],[0.,2.5]])
    return np.vstack([c+rg.normal(0,.35,(40,2)) for c in centers])

def elbo_known(X,r,alpha,m,s2,alpha0=.1,tau2=9.,noise2=.16):
    n,d=X.shape; k=r.shape[1]
    elogpi=digamma(alpha)-digamma(alpha.sum())
    kl_dir=gammaln(alpha.sum())-gammaln(alpha).sum()-gammaln(k*alpha0)+k*gammaln(alpha0)+np.sum((alpha-alpha0)*elogpi)
    kl_mean=.5*np.sum((d*s2+np.sum(m*m,axis=1))/tau2-d+d*np.log(tau2/s2))
    assignment=np.sum(r*(elogpi[None,:]-np.log(np.maximum(r,1e-300))))
    residual=np.sum((X[:,None,:]-m[None,:,:])**2,axis=2)+d*s2[None,:]
    likelihood=np.sum(r*(-.5*d*np.log(2*np.pi*noise2)-residual/(2*noise2)))
    return likelihood+assignment-kl_dir-kl_mean

def cavi_known(X,K=10,steps=60):
    rg=np.random.default_rng(3); n,d=X.shape
    starts=X[rg.choice(n,K,replace=False)]
    logits=-np.sum((X[:,None,:]-starts[None,:,:])**2,axis=2)/(.8**2)
    r=np.exp(logits-logsumexp(logits,axis=1,keepdims=True))
    history=[]
    for _ in range(steps+1):
        counts=r.sum(axis=0); alpha=.1+counts
        s2=1/(1/9+counts/.16); m=s2[:,None]*(r.T@X)/.16
        history.append(elbo_known(X,r,alpha,m,s2))
        log_r=digamma(alpha)[None,:]-digamma(alpha.sum())-.5*(np.sum((X[:,None,:]-m[None,:,:])**2,axis=2)+d*s2[None,:])/.16
        r=np.exp(log_r-logsumexp(log_r,axis=1,keepdims=True))
    return alpha,m,np.array(history)

X=make_data()
alpha,m,history=cavi_known(X)
print('ELBO inicial y final',round(history[0],4),round(history[-1],4))
print('mínimo incremento',np.diff(history).min())
print('pesos finales',np.round(alpha/alpha.sum(),4))
assert np.all(np.diff(history)>-1e-9)

Initialization uses distinct centers taken from data. The 0.01 display threshold is a convention for counting dominant components, not literal deletion: with a proper Dirichlet prior remaining expected weights stay positive.

Lab: complete Normal-Wishart

Precision is now unknown. We use the Normal-Wishart convention E[Λ]=νW\E[\mat\Lambda]=\nu\mat W. For each component, βk=β0+Nk\beta_k=\beta_0+N_k, νk=ν0+Nk\nu_k=\nu_0+N_k, mk=(β0m0+∑irikxi)/βk\vb m_k=(\beta_0\vb m_0+\sum_i r_{ik}\vb x_i)/\beta_k and

Wk−1=W0−1+∑irik(xi−xˉk)(xi−xˉk)⊤+β0Nkβk(xˉk−m0)(xˉk−m0)⊤.\mat W_k\inv=\mat W_0\inv+\sum_i r_{ik}(\vb x_i-\bar{\vb x}_k)(\vb x_i-\bar{\vb x}_k)\T+\frac{\beta_0 N_k}{\beta_k}(\bar{\vb x}_k-\vb m_0)(\bar{\vb x}_k-\vb m_0)\T.

The cell separately calculates observation, assignment, weight and Normal-Wishart terms. For nearly zero NkN_k, division by its sum is protected; quantities it multiplies also tend to zero. Wishart normalization uses Γd\Gamma_d, the multivariate gamma.

[ ]Normal-Wishart CAVI and its ELBOBrowser
from scipy.special import multigammaln
from scipy.linalg import cho_solve, cho_factor

def kl_dir(alpha,alpha0):
    k=len(alpha); elog=digamma(alpha)-digamma(alpha.sum())
    return gammaln(alpha.sum())-gammaln(alpha).sum()-gammaln(k*alpha0)+k*gammaln(alpha0)+np.sum((alpha-alpha0)*elog)

def log_wishart_norm(W,nu):
    d=W.shape[0]
    return -.5*nu*d*np.log(2)-.5*nu*np.linalg.slogdet(W)[1]-multigammaln(nu/2,d)

def nw_update(X,r,m0,beta0,W0,nu0,alpha0):
    n,d=X.shape; k=r.shape[1]
    N=r.sum(axis=0); beta=beta0+N; nu=nu0+N; alpha=alpha0+N
    m=(beta0*m0[None,:]+r.T@X)/beta[:,None]
    W=[]; prior_prec=np.linalg.solve(W0,np.eye(d))
    for j in range(k):
        mean=(r[:,j,None]*X).sum(axis=0)/max(N[j],1e-300)
        xc=X-mean; scatter=(r[:,j,None]*xc).T@xc; delta=mean-m0
        invW=prior_prec+scatter+(beta0*N[j]/beta[j])*np.outer(delta,delta)
        W.append(cho_solve(cho_factor(invW,lower=True),np.eye(d)))
    return alpha,beta,nu,m,np.array(W)

def nw_elbo(X,r,params,m0,beta0,W0,nu0,alpha0):
    alpha,beta,nu,m,W=params; n,d=X.shape; k=r.shape[1]
    elogpi=digamma(alpha)-digamma(alpha.sum())
    prior_inv=np.linalg.solve(W0,np.eye(d))
    assignment=np.sum(r*(elogpi[None,:]-np.log(np.maximum(r,1e-300))))
    likelihood=0.; normalwishart=0.
    for j in range(k):
        elogdet=sum(digamma((nu[j]+1-i)/2) for i in range(1,d+1))+d*np.log(2)+np.linalg.slogdet(W[j])[1]
        delta=X-m[j]; quad=np.einsum('ni,ij,nj->n',delta,W[j],delta)
        likelihood+=.5*np.sum(r[:,j]*(elogdet-d*np.log(2*np.pi)-d/beta[j]-nu[j]*quad))
        q_inv=np.linalg.solve(W[j],np.eye(d))
        wish=log_wishart_norm(W0,nu0)-log_wishart_norm(W[j],nu[j])+.5*(nu0-nu[j])*elogdet-.5*nu[j]*np.trace((prior_inv-q_inv)@W[j])
        dm=m[j]-m0
        normal=.5*d*np.log(beta0/beta[j])+.5*d-.5*beta0*(d/beta[j]+nu[j]*dm@W[j]@dm)
        normalwishart+=wish+normal
    return likelihood+assignment-kl_dir(alpha,alpha0)+normalwishart

def cavi_nw(X,K=10,steps=60):
    n,d=X.shape; rg=np.random.default_rng(3)
    starts=X[rg.choice(n,K,replace=False)]
    logits=-np.sum((X[:,None,:]-starts[None,:,:])**2,axis=2)/(.8**2)
    r=np.exp(logits-logsumexp(logits,axis=1,keepdims=True))
    m0=np.zeros(d); beta0=1.; nu0=d+2.; W0=.3*np.eye(d); alpha0=.1
    history=[]
    for _ in range(steps+1):
        params=nw_update(X,r,m0,beta0,W0,nu0,alpha0)
        alpha,beta,nu,m,W=params
        history.append(nw_elbo(X,r,params,m0,beta0,W0,nu0,alpha0))
        log_r=np.empty((n,K))
        for j in range(K):
            elogdet=sum(digamma((nu[j]+1-i)/2) for i in range(1,d+1))+d*np.log(2)+np.linalg.slogdet(W[j])[1]
            delta=X-m[j]; quad=np.einsum('ni,ij,nj->n',delta,W[j],delta)
            log_r[:,j]=digamma(alpha[j])-digamma(alpha.sum())+.5*(elogdet-d/beta[j]-nu[j]*quad)
        r=np.exp(log_r-logsumexp(log_r,axis=1,keepdims=True))
    return params,np.array(history)

params,bounds=cavi_nw(X)
print('ELBO inicial y final',round(bounds[0],4),round(bounds[-1],4))
print('mínimo incremento',np.diff(bounds).min())
print('pesos',np.round(params[0]/params[0].sum(),4))
assert np.all(np.diff(bounds)>-1e-9)

Compare with the professional implementation, aligning dominant centers. The scikit-learn prior covariance_prior corresponds here to W0−1\mat W_0\inv and a finite Dirichlet mixture is used. Do not expect equality for different initializations or conventions; this comparison checks one configuration, not a general proof.

[ ]Compare with BayesianGaussianMixtureBrowser
from sklearn.mixture import BayesianGaussianMixture
from scipy.optimize import linear_sum_assignment

sk=BayesianGaussianMixture(n_components=10,weight_concentration_prior_type='dirichlet_distribution',weight_concentration_prior=.1,mean_precision_prior=1.,mean_prior=np.zeros(2),degrees_of_freedom_prior=4.,covariance_prior=np.eye(2)/.3,max_iter=1000,tol=1e-7,reg_covar=0.,random_state=3).fit(X)
weights=params[0]/params[0].sum(); own=np.flatnonzero(weights>.01); other=np.flatnonzero(sk.weights_>.01)
cost=np.linalg.norm(params[3][own,None,:]-sk.means_[None,other,:],axis=2)
rows,cols=linear_sum_assignment(cost)
print('convergió sklearn',sk.converged_,'componentes activas',len(own),len(other))
print('distancias de centros alineados',np.round(cost[rows,cols],8))

Lab: LDA on the m14-l09 corpus

We use exactly the m14-l09 generator: 250 documents of 60 words, 3 topics, vocabulary 12, seed 2026 and symmetric priors α=0.3\alpha=0.3, η=0.12\eta=0.12. This is a synthetic corpus with known true topics, not real document text. The module is available to download lda_corpus.py; the first cell reproduces it so the lab works in an independent session.

[ ]Corpus generator from m14-l09Browser
"""Corpus LDA sintético reproducible para m14-l09, l18 y l22."""
import numpy as np


def synthetic_lda(seed=2026, n_docs=250, n_words=60, n_topics=3,
                  n_vocab=12, alpha=.3, beta=.12):
    """Devuelve (conteos, theta, temas, asignaciones, palabras).

    Temas: (K,V); theta: (D,K); asignaciones y palabras: (D,N).
    Los temas y proporciones se generan de priors Dirichlet simétricos,
    cada palabra tiene su propio tema, y las filas de conteos suman N.
    """
    if min(n_docs,n_words,n_topics,n_vocab)<1 or alpha<=0 or beta<=0:
        raise ValueError('tamaños y concentraciones deben ser positivos')
    rng=np.random.default_rng(seed)
    topics=rng.dirichlet(np.full(n_vocab,beta),size=n_topics)
    theta=rng.dirichlet(np.full(n_topics,alpha),size=n_docs)
    assignments=np.empty((n_docs,n_words),dtype=int)
    words=np.empty_like(assignments)
    counts=np.zeros((n_docs,n_vocab),dtype=int)
    for d in range(n_docs):
        assignments[d]=rng.choice(n_topics,size=n_words,p=theta[d])
        for n,z in enumerate(assignments[d]):
            words[d,n]=rng.choice(n_vocab,p=topics[z])
        counts[d]=np.bincount(words[d],minlength=n_vocab)
    return counts,theta,topics,assignments,words

In CAVI we maintain q(θd)=Dir⁡(γd)q(\theta_d)=\operatorname{Dir}(\gamma_d), q(βk)=Dir⁡(λk)q(\beta_k)=\operatorname{Dir}(\lambda_k) and probabilities ϕdvk\phi_{dvk} shared across all appearances of word vv in document dd. Update

ϕdvk∝exp⁡(Elog⁡θdk+Elog⁡βkv),γdk=α+∑vndvϕdvk,λkv=η+∑dndvϕdvk.\phi_{dvk}\propto\exp(\E\log\theta_{dk}+\E\log\beta_{kv}),\quad \gamma_{dk}=\alpha+\sum_v n_{dv}\phi_{dvk},\quad \lambda_{kv}=\eta+\sum_d n_{dv}\phi_{dvk}.

The second method performs variational EM with topics as point parameters: the E-step updates γ\gamma and ϕ\phi with log⁡β\log\beta, and the M-step normalizes expected counts by topic. It introduces no prior in the M-step; hence its bound and the CAVI bound with Dirichlet topic prior belong to different objectives and must not be directly compared as evidence. Each local update iterates to tolerance or 100 steps. ELBO includes corresponding entropies and Dirichlet constants.

[ ]CAVI, variational EM and ELBOBrowser
import numpy as np
from scipy.special import digamma,gammaln,logsumexp
from scipy.optimize import linear_sum_assignment
from sklearn.decomposition import LatentDirichletAllocation
counts,theta,truth,z,words=synthetic_lda()
D,V=counts.shape;K=3;alpha=.3;beta=.12

def elog_dir(x):return digamma(x)-digamma(x.sum(axis=-1,keepdims=True))
def dir_prior_minus_q(q,a):
    k=q.shape[-1];e=elog_dir(q)
    lp=gammaln(k*a)-k*gammaln(a)+(a-1)*e.sum(axis=-1)
    lq=gammaln(q.sum(axis=-1))-gammaln(q).sum(axis=-1)+((q-1)*e).sum(axis=-1)
    return (lp-lq).sum()
def local_update(counts,elog_beta,gamma,steps=100):
    for _ in range(steps):
        logphi=elog_dir(gamma)[:,None,:]+elog_beta.T[None,:,:]
        logphi-=logsumexp(logphi,axis=2,keepdims=True);phi=np.exp(logphi)
        next_gamma=alpha+np.einsum('dv,dvk->dk',counts,phi)
        if np.max(np.abs(next_gamma-gamma))<1e-7:gamma=next_gamma;break
        gamma=next_gamma
    logphi=elog_dir(gamma)[:,None,:]+elog_beta.T[None,:,:]
    logphi-=logsumexp(logphi,axis=2,keepdims=True)
    return gamma,np.exp(logphi)
def lda_elbo(gamma,phi,elog_beta,lam=None):
    terms=elog_dir(gamma)[:,None,:]+elog_beta.T[None,:,:]-np.log(np.maximum(phi,1e-300))
    value=dir_prior_minus_q(gamma,alpha)+np.sum(counts[:,:,None]*phi*terms)
    if lam is not None:value+=dir_prior_minus_q(lam,beta)
    return value
def initialize(method):
    rng=np.random.default_rng(17);gamma=np.full((D,K),alpha+counts.sum(1)[:,None]/K)
    if method=='cavi':
        lam=beta+rng.gamma(1,30,size=(K,V));elog=elog_dir(lam)
    else:
        topics=rng.dirichlet(np.ones(V),size=K);elog=np.log(topics)
    return {'method':method,'gamma':gamma,'elog':elog,'history':[]}
def advance(state,steps=10):
    for _ in range(steps):
        gamma,phi=local_update(counts,state['elog'],state['gamma'])
        suff=np.einsum('dv,dvk->kv',counts,phi)
        if state['method']=='cavi':
            lam=beta+suff;elog=elog_dir(lam);topics=lam/lam.sum(axis=1,keepdims=True)
            value=lda_elbo(gamma,phi,elog,lam)
        else:
            topics=np.maximum(suff,1e-300);topics/=topics.sum(axis=1,keepdims=True);elog=np.log(topics)
            value=lda_elbo(gamma,phi,elog)
        state.update(gamma=gamma,elog=elog,topics=topics)
        state['history'].append(value)
def match(a,b):
    cost=np.abs(a[:,None,:]-b[None,:,:]).sum(axis=2)
    i,j=linear_sum_assignment(cost)
    return j,cost[i,j]
cavi=initialize('cavi');em=initialize('em')
print('corpus',counts.shape,'tokens',counts.sum(),'prior alpha',alpha,'beta',beta)

Four blocks of ten steps let us observe the trajectory. Both initializations use the same seed, but families and objectives differ. Expected monotonicity assumes exact updates; finite calculations can have small differences from tolerance and rounding.

[ ]Steps 1 to 10Browser
advance(cavi);advance(em)
print('CAVI, EM',cavi['history'][-1],em['history'][-1])
[ ]Steps 11 to 20Browser
advance(cavi);advance(em)
print('CAVI, EM',cavi['history'][-1],em['history'][-1])
[ ]Steps 21 to 30Browser
advance(cavi);advance(em)
print('CAVI, EM',cavi['history'][-1],em['history'][-1])
[ ]Steps 31 to 40Browser
advance(cavi);advance(em)
for name,s in [('CAVI',cavi),('EM',em)]:
    h=np.array(s['history'])
    print(name,'ELBO inicial y final',h[0],h[-1],'mínimo incremento',np.diff(h).min())

Compare topics by L1L_1 distance, aligning permutations via Hungarian assignment. Since generating topics are known in this simulation, we can also measure error against them. The sklearn comparison uses the same matrix and priors for Bayesian LDA; its initialization and optimization differ.

[ ]Aligned comparison with sklearnBrowser
sk=LatentDirichletAllocation(n_components=K,doc_topic_prior=alpha,topic_word_prior=beta,
    learning_method='batch',max_iter=40,random_state=17,n_jobs=1).fit(counts)
sk_topics=sk.components_/sk.components_.sum(axis=1,keepdims=True)
for name,state in [('CAVI',cavi),('EM',em)]:
    print(name,'L1 por tema frente a generador',match(truth,state['topics'])[1])
    print(name,'L1 por tema frente a sklearn',match(sk_topics,state['topics'])[1])
print('iteraciones sklearn',sk.n_iter_,'perplejidad de entrenamiento',sk.bound_)

Displayed perplexity is training perplexity, not an out-of-sample result. Topic labels are interchangeable, and small error in this single simulation does not establish general recovery or superiority of a method.

Exercises

NumericA strong correlation
The two-dimensional Gaussian posterior has unit marginal variances and correlation 0.90.9. What is the variance of the first optimal mean-field factor for KL⁡(q∥p)\KL(q\|p)?
QuizBounds for different models
Model A has a higher ELBO than B. What can you conclude about their evidences?
ProofUpdating a factor
Prove: With the other factors fixed, the optimal mean-field factor is proportional to the exponential of expected log joint.
0
Define hj(zj)=Eq−j[log⁡p(x,z)]h_j(z_j)=\E_{q_{-j}}[\log p(x,z)] and assume Zj=∫ehj(u) ⁣duZ_j=\int e^{h_j(u)}\dd u finite and positive.

Step 1 of 3. Which part of ELBO depends on qjq_j?

ProofConditional versus marginal variance
Prove: In a Gaussian posterior with positive-definite precision, the optimal mean-field factor variance is at most its corresponding marginal.
0
Partition Λ=[ab⊤bC]\mat\Lambda=\begin{bmatrix}a&\vb b\T\\\vb b&\mat C\end{bmatrix}, where a=Λjja=\Lambda_{jj} and C≻0\mat C\succ0.

Step 1 of 3. What is the optimal factor variance?

CodeELBO of a scalar mixture
Implement gmm_elbo(x, r, alpha, m, s2, alpha0, tau2, noise2) for the lesson's mixture of Gaussian means and Dirichlet weights with scalar data. r has shape (n,k), alpha, m and s2 have length k; alpha0, tau2 and noise2 are positive scalars. Return the complete ELBO.
def gmm_elbo(x, r, alpha, m, s2, alpha0, tau2, noise2):
  pass
Shift+Enter to run

Summary

Key idea
Variational inference optimizes an evidence bound within a family. The chosen shape determines which uncertainty it can represent and KL measures its gap from the posterior.
  • Mean field turns each step into a factor update; exact CAVI does not decrease ELBO, though it can converge to a local maximum.
  • In correlated Gaussians the optimal factor has conditional variance at most the marginal. This conclusion does not cover every family.
  • In mixtures and LDA, responsibilities and expected statistics connect inference with EM. ELBO helps monitor the algorithm but does not automatically replace evidence.