Skip to content

Probabilistic inference, Monte Carlo, and posterior computation · Probabilistic computation and inference foundations · INF002 · Algorithm

Coordinate-ascent variational inference and variational EM

Approximates a latent posterior by optimizing a tractable distribution, often a product of factors. Coordinate-ascent VI updates one factor at a time;

Runs in CodeSplash Complete calculation CodeSplash's run and the reference's record

In CodeSplash

A CodeSplash method runs this entry in Python and R. Set it up from the method's page.

Do it in CodeSplash Run it on your own data, in Python or R.

Availability
Runs in CodeSplash
Code example
Complete calculation
Who ran it
CodeSplash's run and the reference's record
CodeSplash's run
Verified in Python and R through discover.topics. The reference's example ran in Python and R here, and they agree.
The reference's record
Python: Ran in the reference's review. The report doesn't record which version of the code ran. R: Reviewed but not run: R wasn't available to the reference's authors.

Purpose

Approximates a latent posterior by optimizing a tractable distribution, often a product of factors. Coordinate-ascent VI updates one factor at a time; variational EM additionally alternates these updates with optimization of model parameters.

Question / hypotheses

Within the chosen variational family, which distribution maximizes the evidence lower bound? This approximates posterior inference; the optimized variational parameters are not automatically the original model parameters or independent posterior samples.

Architecture / computational structure

Factorize q, evaluate the expected log joint under all other factors, normalize the resulting factor, and cycle. A conjugate graphical model can pass expected sufficient statistics between factors. The example solves the mean-field approximation of a known correlated bivariate Gaussian, revealing its variance reduction.

Assumptions

The log joint and required expectations must exist. Closed-form coordinate updates usually need conjugacy or tractable conditional structure. Mean-field factorization is an approximation that can discard important dependence; local optima remain possible.

Formula / computational definition

L(q,θ)=Eq[log⁡pθ(x,z)]−Eq[log⁡q(z)],log⁡qj∗(zj)=Eq−j[log⁡pθ(x,z)]+constant.\mathcal L(q,\theta)=E_q[\log p_\theta(x,z)]-E_q[\log q(z)],\quad \log q_j^*(z_j)=E_{q_{-j}}[\log p_\theta(x,z)]+constant.

Parameters and notation

Learned variational quantities are each factor’s location, scale, or natural parameters. In variational EM, theta is separately optimized in a model-parameter step. Hyperparameters include factorization, component families, update order, damping, stopping tolerance, and initializations. Increasing factor flexibility may matter more than tightening optimizer tolerance.

Fitting, fine-tuning, and adaptation

Refit or warm-start variational factors when observations change; if model parameters are frozen this is inference, not neural fine-tuning. A variational EM outer loop must also update theta. If adapting an encoder that predicts factors, that is amortized inference and introduces shared network weights beyond these coordinate updates.

How to use and calibrate

Monitor a consistently evaluated ELBO and compare several initializations. Check selected posterior moments against quadrature or well-diagnosed MCMC on a small problem. Plot marginal intervals and joint contours to expose dependence removed by factorization.

Example application

Approximate latent topic proportions or mixture allocations when analytic integration is impossible but expected log probabilities are available, then audit predictive performance and uncertainty against a smaller exact or sampling-based calculation.

Interpretation / pitfalls

Watch out

A converged ELBO need not indicate an accurate posterior. For a correlated Gaussian, factorized reverse-KL optimization can recover the mean but underestimate marginal variance. ELBO differences across unrelated observation definitions are not directly comparable evidence.

Python and R code examples

Scope: Complete coordinate updates for a specified two-dimensional Gaussian target; no generic latent-model parser or variational EM outer loop.

Implementation route: Both examples use native array arithmetic (NumPy/base R). Model-specific conjugate CAVI is straightforward to code in either language; a general autodifferentiation VI engine uses different gradient updates and should not be mislabeled CAVI.

Dependencies and validation: Python — executed successfully on the supplied synthetic inputs; imports identify NumPy/SciPy dependencies. R — base R, reviewed but not executed because Rscript is unavailable. Random-number streams differ between languages; matching seed integers do not imply matching draws.

Python and R

The reference's own programs, shown as written. A component demo shows one central piece of the method; it doesn't train a full model.

Python

Complete calculation — Complete coordinate updates for a specified two-dimensional Gaussian target; no generic latent-model parser or variational EM outer loop. · needs numpy

import numpy as np
rho=.8; target=np.array([1.,-1.]); m=np.zeros(2)
for _ in range(100):
    m[0]=target[0]+rho*(m[1]-target[1])
    m[1]=target[1]+rho*(m[0]-target[0])
v=1-rho*rho
assert np.allclose(m,target)
print('q means',m,'q marginal variance',v,'target marginal variance',1.)
R

Complete calculation — Complete coordinate updates for a specified two-dimensional Gaussian target; no generic latent-model parser or variational EM outer loop.

rho <- .8; target <- c(1,-1); m <- c(0,0)
for(i in 1:100) {
  m[1] <- target[1]+rho*(m[2]-target[2])
  m[2] <- target[2]+rho*(m[1]-target[1])
}
v <- 1-rho*rho; stopifnot(max(abs(m-target))<1e-8)
print(list(q.means=m,q.variance=v,target.variance=1))

Sources

From the CodeSplash reference, entry INF002.