Variational inference: fitting a simpler posterior
变分推断
Derive CAVI and check an exact binary posterior where mean-field means are correct but dependence is lost.
variational-inferenceA good average can conceal the wrong relationship
Two binary latent variables A and B have unnormalized posterior weights arranged as rows A, columns B: [[2,1],[1,2]]. Equal values are twice as likely as unequal values. Normalizing gives diagonal probabilities 1/3 and off-diagonal probabilities 1/6. Each marginal mean is 1/2, but A and B are positively associated.
Suppose an approximation is only allowed to store one Bernoulli probability for each variable, multiplying them to form q(A,B). It can match both means and still lose the association. This is the tradeoff behind a simple mean-field approximation: easier calculations inside a restricted family. Read KL divergence and Bayesian inference first.
Optimize a distribution within a chosen family
For a positive finite unnormalized target w(z), let Z=Σw and p(z)=w(z)/Z. Natural logarithms give the identity:
It follows by substituting log p=log w−log Z into the definition of KL. Nonnegative KL makes L a lower bound on log Z. When w(z)=p(z,x) for fixed observations x, Z is the evidence p(x), hence “evidence lower bound” or ELBO. Our weight table is a proportional target, so its Z=6 is a normalizer; it is not a separately specified probability of observed data.
Maximizing L over q is equivalent to minimizing reverse KL, q||p. The entropy term has a minus sign before E_q log q. No evaluation of Z is needed to update q. Blei, Kucukelbir and McAuliffe, v 9, Section 2.2, sets out this objective; Ng’s EM notes, PartIX, derives the related Jensen bound. Unlike an EM parameter-fitting loop, the model weights here remain fixed: only the approximating distribution changes.
For a mean-field family q(z)=∏qⱼ(zⱼ), hold all factors but one fixed. Its maximizing coordinate has the form:
To derive it, gather the terms involving qⱼ as its expected log score plus entropy, then rewrite them as a constant minus KL to the normalized exponentiated score. That KL is minimized at equality. Repeated exact coordinate updates cannot lower the objective in exact arithmetic. This does not establish a global optimum for every model. The review’s Section 2.4 gives coordinate-ascent variational inference, or CAVI.
A solvable dependence gap
Set r=q(A=1), s=q(B=1). For our table, one sequential sweep is:
Since σ′≤1/4, each scalar update has derivative at most log 2/2, less than one. Their composition contracts, so this example has a unique fixed point r=s=1/2. The objective’s entropy keeps a coordinate optimum inside(0,1), and any global maximum must obey the coordinate equations. Thus the fixed point is the global mean-field optimum here; the argument depends on this table, not just on calling the algorithm CAVI.
The optimum puts probability 1/4 on every joint state. Its KL is(1/2)log(9/8), about 0.05889, despite exact marginal means. True covariance is 1/3−1/4=1/12; product-family covariance is zero. Running more sweeps cannot represent a dependence that the family forbids.
Compute the bound and the exact posterior side by side
This complete Python 3.12 program performs sequential coordinate updates for any positive 2×2 table within the stated numeric bounds. The exact posterior is enumerated for diagnosis; it is not used by the update equations. A sweep updates r first and then uses that new r to update s.
from math import exp, isfinite, log
def mean_field(weights, start=(0.1,0.9), tol=1e-12, max_steps=1000):
w=[list(row) for row in weights];start=list(start)
if len(w)!=2 or any(len(row)!=2 for row in w):
raise ValueError('a two-by-two weight table required')
if any(type(v) not in (int,float) or not isfinite(v) or not 1e-6<=v<=1e6 for row in w for v in row):
raise ValueError('finite weights between1e-6 and1e6 required')
if len(start)!=2 or any(type(v) not in (int,float) or not isfinite(v) or not 1e-6<=v<=1-1e-6 for v in start):
raise ValueError('two starting probabilities away from endpoints required')
if type(tol) not in (int,float) or not isfinite(tol) or not 1e-14<=tol<=1e-3:
raise ValueError('tolerance between1e-14 and1e-3 required')
if type(max_steps) is not int or not 1<=max_steps<=1000:
raise ValueError('one to1000 sweeps required')
logs=[[log(v) for v in row] for row in w];z=sum(map(sum,w));logz=log(z)
exact=[[v/z for v in row] for row in w]
def sigmoid(v):return 1/(1+exp(-v)) if v>=0 else exp(v)/(1+exp(v))
def distribution(r,s):return [[(1-r)*(1-s),(1-r)*s],[r*(1-s),r*s]]
def bound(r,s):
q=distribution(r,s)
return sum(q[i][j]*(logs[i][j]-log(q[i][j])) for i in range(2) for j in range(2))
r,s=map(float,start);history=[bound(r,s)];converged=False;residual=float('inf')
for step in range(max_steps):
old_r,old_s=r,s
r=sigmoid((1-s)*(logs[1][0]-logs[0][0])+s*(logs[1][1]-logs[0][1]))
s=sigmoid((1-r)*(logs[0][1]-logs[0][0])+r*(logs[1][1]-logs[1][0]))
history.append(bound(r,s));residual=max(abs(r-old_r),abs(s-old_s))
if residual<=tol:converged=True;break
q=distribution(r,s);exact_r=sum(exact[1]);exact_s=exact[0][1]+exact[1][1]
return dict(q=q,means=(r,s),exact=exact,exact_means=(exact_r,exact_s),
exact_covariance=exact[1][1]-exact_r*exact_s,
elbo=history[-1],log_normalizer=logz,kl=logz-history[-1],
history=history,residual=residual,converged=converged,sweeps=step+1)
if __name__=='__main__':
result=mean_field([[2,1],[1,2]])
print('exact table:',result['exact'])
print('variational means:',*[f'{v:.12f}' for v in result['means']])
print('exact covariance:',f"{result['exact_covariance']:.12f}")
print('variational covariance: 0 (product family)')
for key in ('elbo','log_normalizer','kl','residual'):print(key,f'{result[key]:.12g}')
print('converged:',result['converged'],'sweeps:',result['sweeps'])
Output:
exact table: [[0.3333333333333333, 0.16666666666666666], [0.16666666666666666, 0.3333333333333333]]
variational means: 0.500000000000 0.500000000000
exact covariance: 0.083333333333
variational covariance: 0 (product family)
elbo 1.7328679514
log_normalizer 1.79175946923
kl 0.0588915178282
residual 1.28452803949e-13
converged: True sweeps: 15
The reported residual measures the largest change in a variational mean during the last sweep. converged means it met that stopping rule within the budget. It does not measure posterior accuracy. For this fixed two-variable model, each sweep takes constant work; storing objective history costs O(T) for T sweeps. A many-variable mean-field algorithm can still face expensive expectations even after factorization.
Separate optimization error from family error
The observed ELBO and KL use floating-point arithmetic. Their identity is evaluated numerically, so a factorizable target can produce a tiny signed roundoff value near zero. We do not silently interpret that as a negative mathematical KL. Tests compare against analytic values with tolerances.
Mean field rules out cross-factor dependence. It need not underestimate every marginal variance: here both marginal Bernoulli variances are exactly 1/4. The missing quantity is covariance. Other objectives, structured families or transformations change the approximation problem and can change which features are well preserved.
Hard zeros require care: assigning positive q mass where p=0 makes reverse KL infinite. The teaching API excludes zero weights. More general CAVI objectives can have multiple optima or poor stationary points; several initializations and bound values provide evidence, not a universal certificate. A larger ELBO across different models is also not automatically a larger evidence, because approximation gaps can differ.
What did the approximation actually learn?
- Why can updates omit the normalizer Z?
Answer 1: log Z is constant with respect to q; it cancels from the coordinate optimization.
- What is the exact covariance in the example?
Answer 2: E[AB]−E[A]E[B]=1/3−1/4=1/12.
- Does a small update residual imply small posterior error?
Answer 3: No. At the fixed point the means stop changing while the positive KL gap and missing covariance remain.
- Does this example underestimate marginal variance?
Answer 4: No. Both marginal means and variances match; joint dependence does not.
Spend approximation capacity where it matters
Project: replace the weights with [[1,2],[3,6]]. This target factorizes, so CAVI can recover the exact posterior with means(3/4,2/3) and zero KL up to roundoff. Then increase the diagonal weights in the original table and try several starts. Recheck the contraction bound before carrying over the uniqueness claim.
Structured variational families retain selected dependencies; stochastic VI estimates expensive updates; amortized inference predicts variational parameters from data. Each introduces its own computational or approximation choices. Compare MCMC and belief propagation using a specified posterior quantity and computational budget, rather than declaring a method universally more accurate.
Make a prediction, then check
What remains wrong at the optimum in this example?
Learning objectives
- Derive the ELBO identity and the coordinate update.
- Distinguish optimization convergence from approximation accuracy.
- Measure the dependence lost by a product family.
Prerequisites & connections
Explore related knowledge →References
- Variational Inference: A Review for Statisticians — arXiv v9
David M. Blei; Alp Kucukelbir; Jon D. McAuliffe · 2018 - CS229 Lecture Notes, PartIX — The EM Algorithm
Andrew Ng
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-06 · Codex single-agent authored technical review: cited primary-source scope, explicit assumptions, original calculations and counterexamples, runnable tests and bilingual review; not independent human or second-agent review.
- Single-agent authored technical review: bounded primary-source locations, assumptions, original derivations, exact/literal references and matching bilingual equations/examples/exercises. Not independent human or second-agent review.
- Four focused CPython3.12.4 tests passed per chapter. IS and decisions use exact fractions; VI and GP use floating-point calculations checked against analytic constants, invariance and meaningful boundaries. NumPy1.26.4 used for GP.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- Variational Inference: A Review for Statisticians — arXiv v9 · Fixed arXiv v9, title pageMay11,2018 versus arXiv footerMay9,2018; Sections2.2–2.4, equations11–18: KL direction, minus-entropy sign, mean field, coordinate updates. Binary contraction proof is original, not attributed to review.
- CS229 Lecture Notes, PartIX — The EM Algorithm · PartIX physical pages3–6: Jensen lower bound, posterior tightness and fixed-model variational distribution versus EM model-parameter updates.
Related topics