AI Wiki中文/EN

Variational autoencoders: learning a decoder and its posterior

变分自编码器

Train a six-parameter Gaussian VAE and compare reconstruction, marginal likelihood and posterior approximation.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Reconstructing a point and learning a distribution

Consider six scalar observations for teaching: −2, −1, −0.4, 0.4, 1 and 2. An ordinary autoencoder can compress each input into a code and reconstruct it. Reconstruction error alone does not determine whether decoding an arbitrarily drawn code samples the learned data distribution.

A variational autoencoder, or VAE, specifies a generative model: draw a latent variable from a prior, then draw data from a conditional observation distribution. Its encoder reads an observation and approximates which latent variables could have generated it. The encoder therefore outputs distribution parameters, as does the decoder; they are not simply two symmetric deterministic mappings. AEVB Sections 2–3 give this construction; Rezende and colleagues’ early work also jointly learns a recognition model and a latent-variable generative model.

Begin with autoencoders, Gaussian distributions and maximum likelihood. We use a VAE with a tractable posterior to check every quantity before discussing which computations change with neural networks.

Compare the exact bound, marginal likelihood, posterior densities and one sampled estimate in the six-parameter Gaussian VAE.
Compare the exact bound, marginal likelihood, posterior densities and one sampled estimate in the six-parameter Gaussian VAE.

Three distributions with different jobs

The prior p(z)p(z) supplies latents for unconditional generation. The decoder pθ(x∣z)p_\theta(x\mid z) describes observations given a latent. The encoder qϕ(z∣x)q_\phi(z\mid x) approximates the current model’s true posterior. The joint and single-observation objective are:

pθ(x,z)=p(z)pθ(x∣z),L=Eqϕ(z∣x)log⁡pθ(x∣z)−DKL(qϕ(z∣x)∥p(z)).p_\theta(x,z)=p(z)p_\theta(x\mid z),\qquad\mathcal L=\mathbb E_{q_\phi(z\mid x)}\log p_\theta(x\mid z)-D_{\rm KL}(q_\phi(z\mid x)\Vert p(z)).

Here θ\theta denotes generative parameters and ϕ\phi encoder parameters. Maximizing the ELBO, or minimizing its negative, places reconstruction and prior KL in one probabilistic objective. The bound is log evidence minus the KL from qq to the true posterior, rather than an arbitrary combination of two losses. AEVB Equations 1–3 explain this decomposition.

A diagonal Gaussian encoder and its scale

A common choice outputs mean vector μϕ(x)\mu_\phi(x) and log-variance vector ℓϕ(x)\ell_\phi(x). With dd latent dimensions, the noise also has dd dimensions:

qϕ(z∣x)=N(z;μϕ(x),diag⁡(eℓϕ(x))),z=μϕ(x)+eℓϕ(x)/2⊙ϵ,ϵ∼N(0,I).q_\phi(z\mid x)=\mathcal N(z;\mu_\phi(x),\operatorname{diag}(e^{\ell_\phi(x)})),\qquad z=\mu_\phi(x)+e^{\ell_\phi(x)/2}\odot\epsilon,\quad\epsilon\sim\mathcal N(0,I).

Exponentiation is elementwise and ⊙\odot denotes elementwise multiplication. Log variance need not be positive, while the resulting variance must be; numerical implementations should also control large exponents. Noise is multiplied by standard deviation eℓ/2e^{\ell/2}, not variance eℓe^\ell. AEVB Section 3 uses a diagonal Gaussian; lines 60–63 of the pinned PyTorch example likewise exponentiate half of logvar.

For a standard-normal prior, the KL is analytic:

DKL(qϕ∥N(0,I))=12∑j[μj2+eℓj−1−ℓj].D_{\rm KL}(q_\phi\Vert\mathcal N(0,I))=\frac12\sum_j[\mu_j^2+e^{\ell_j}-1-\ell_j].

Use Eq(zj−μj)2=eℓj\mathbb E_q(z_j-\mu_j)^2=e^{\ell_j} and Eqzj2=μj2+eℓj\mathbb E_qz_j^2=\mu_j^2+e^{\ell_j} in the expected difference of Gaussian log densities to obtain each dimension’s term. At μ=0,ℓ=0\mu=0,\ell=0, the encoder distribution equals the prior and KL is zero. This removes distance to the prior, not necessarily distance to an observation’s true posterior.

Six parameters suffice for a complete training example

Let x,zx,z be scalars and use linear encoder and decoder functions. The six parameters are a,c,w,b,r,sa,c,w,b,r,s:

μ=wx+b,ℓ=r+sx,p(z)=N(0,1),pθ(x∣z)=N(x;az+c,τ2),τ2=0.25.\mu=wx+b,\quad\ell=r+sx,\quad p(z)=\mathcal N(0,1),\quad p_\theta(x\mid z)=\mathcal N(x;az+c,\tau^2),\quad\tau^2=0.25.

Fix observation-noise variance τ2=0.25\tau^2=0.25. Parameters a,ca,c control the generative model; the remaining four make the encoder distribution depend on the input. A shared encoder quickly gives an approximate posterior for different observations. This is amortized inference: it avoids storing a separate set of optimized variational parameters for every observation.

The decoder is linear, so expected reconstruction error expands directly. Averaging over NN observations gives negative ELBO:

J=1N∑n{12[log⁡(2πτ2)+(aμn+c−xn)2+a2eℓnτ2]+12[μn2+eℓn−1−ℓn]}.J=\frac1N\sum_n\left\{\frac12\left[\log(2\pi\tau^2)+\frac{(a\mu_n+c-x_n)^2+a^2e^{\ell_n}}{\tau^2}\right]+\frac12[\mu_n^2+e^{\ell_n}-1-\ell_n]\right\}.

The term a2eℓna^2e^{\ell_n} is the contribution of latent uncertainty through the decoder. Reconstructing only from the encoder mean and measuring squared error omits it. The Gaussian log-normalization constant is retained too. Removing constants may leave some fixed-variance gradients unchanged, but changes the reported probabilistic objective.

To expose backpropagation, the code still follows the graph z=μ+eℓ/2ϵz=\mu+e^{\ell/2}\epsilon. Its default noise nodes are −1 and +1 with equal weights. They match the standard normal’s first two moments, making integration exact for this quadratic reconstruction term. This is deterministic integration, not random SGVB or a general exact method for nonlinear neural decoders.

For one observation, define the scaled residual dd and apply the chain rule:

d=az+c−xτ2,∂aJx=E[dz],∂cJx=E[d],∂μJx=E[ad]+μ,∂ℓJx=E[ad eℓ/2ϵ/2]+(eℓ−1)/2.d=\frac{az+c-x}{\tau^2},\quad\partial_a J_x=\mathbb E[d z],\quad\partial_cJ_x=\mathbb E[d],\quad\partial_\mu J_x=\mathbb E[a d]+\mu,\quad\partial_\ell J_x=\mathbb E[a d\,e^{\ell/2}\epsilon/2]+(e^\ell-1)/2.

The first two derivatives update the decoder. The next two propagate through encoder mean and log variance. Using μ=wx+b,ℓ=r+sx\mu=wx+b,\ell=r+sx then gives:

∂wJx=x∂μJx,∂bJx=∂μJx,∂rJx=∂ℓJx,∂sJx=x∂ℓJx.\partial_wJ_x=x\partial_\mu J_x,\quad\partial_bJ_x=\partial_\mu J_x,\quad\partial_rJ_x=\partial_\ell J_x,\quad\partial_sJ_x=x\partial_\ell J_x.

Average each derivative across observations. A neural decoder generally loses the analytic reconstruction expectation, but can estimate it with parameter-independent standard-normal noise while retaining these chain-rule paths. AEVB Section 2.3 and Rezende’s coordinate transformation support this construction.

Compare training against the true model

Completing the square also gives this model’s true marginal and posterior:

pθ(x)=N(x;c,a2+τ2),pθ(z∣x)=N ⁣(z;a(x−c)a2+τ2,τ2a2+τ2).p_\theta(x)=\mathcal N(x;c,a^2+\tau^2),\quad p_\theta(z\mid x)=\mathcal N\!\left(z;\frac{a(x-c)}{a^2+\tau^2},\frac{\tau^2}{a^2+\tau^2}\right).

They provide an independent check of the objective:

−L(x)=−log⁡pθ(x)+DKL(qϕ(z∣x)∥pθ(z∣x)).-\mathcal L(x)=-\log p_\theta(x)+D_{\rm KL}(q_\phi(z\mid x)\Vert p_\theta(z\mid x)).

Expected reconstruction, marginal likelihood and posterior approximation gap can be calculated separately. Renaming a variable loss to likelihood would not reveal whether these quantities were confused.

Train every encoder and decoder parameter

Save this as vae.py and run it with Python 3.12 and NumPy 1.26.4. The six synthetic observations are included; no external data is needed. Each iteration uses the whole dataset, updating all six parameters with learning rate 0.01 for 1200 steps. A separate seed-12 calculation uses 32 Gaussian samples per observation to illustrate a Monte Carlo objective.

"""Six-parameter linear Gaussian VAE. Exact quadratic quadrature, optional fixed-noise MC."""
import json
import numpy as np

DATA = np.array([-2., -1., -.4, .4, 1., 2.])
INITIAL = np.array([.5, 0., .2, 0., -.2, 0.])  # a,c,w,b,r,s
TAU2 = .25


def inputs(params, x):
    params, x = np.asarray(params, float), np.asarray(x, float)
    if (params.shape != (6,) or x.ndim != 1 or not 1 <= x.size <= 128
            or not np.isfinite(params).all() or not np.isfinite(x).all()
            or np.max(abs(params)) > 10 or np.max(abs(x)) > 4):
        raise ValueError('Six bounded parameters and 1..128 scalar observations in [-4,4] required.')
    a, c, w, b, r, s = params
    mu, lv = w*x+b, r+s*x
    if np.max(abs(lv)) > 8:
        raise ValueError('Encoder log variance must remain in [-8,8].')
    return params, x, mu, lv


def objective(params, x=DATA, eps=None):
    params, x, mu, lv = inputs(params, x)
    a, c, w, b, r, s = params
    if eps is None:
        eps = np.broadcast_to([-1., 1.], (x.size, 2))
    eps = np.asarray(eps, float)
    if (eps.ndim != 2 or eps.shape[0] != x.size or not 1 <= eps.shape[1] <= 256
            or not np.isfinite(eps).all() or np.max(abs(eps)) > 20):
        raise ValueError('Noise must have shape (observations, 1..256), finite and bounded by 20.')
    std = np.exp(.5*lv)
    z = mu[:, None] + std[:, None]*eps
    residual = a*z+c-x[:, None]
    reconstruction = .5 * (np.log(2*np.pi*TAU2) + np.mean(residual**2, axis=1)/TAU2)
    kl = .5 * (mu**2 + np.exp(lv) - 1 - lv)
    error = residual/TAU2
    dmu = a*error.mean(axis=1) + mu
    dlv = np.mean(a*error*.5*std[:, None]*eps, axis=1) + .5*(np.exp(lv)-1)
    gradient = np.array([np.mean(error*z), np.mean(error), np.mean(dmu*x),
                         np.mean(dmu), np.mean(dlv), np.mean(dlv*x)])
    return float(np.mean(reconstruction+kl)), gradient


def analytic(params, x=DATA):
    """Independent closed-form expectation and true marginal/posterior."""
    params, x, mu, lv = inputs(params, x)
    a, c = params[:2]; v = np.exp(lv)
    reconstruction = .5*(np.log(2*np.pi*TAU2) + ((a*mu+c-x)**2 + a*a*v)/TAU2)
    kl = .5*(mu*mu+v-1-lv)
    marginal_variance = a*a+TAU2
    marginal_nll = .5*(np.log(2*np.pi*marginal_variance)+(x-c)**2/marginal_variance)
    post_mu, post_v = a*(x-c)/marginal_variance, TAU2/marginal_variance
    gap = .5*(np.log(post_v/v)+(v+(mu-post_mu)**2)/post_v-1)
    return dict(negative_elbo=float(np.mean(reconstruction+kl)),
                reconstruction_nll=float(reconstruction.mean()), kl_prior=float(kl.mean()),
                marginal_nll=float(marginal_nll.mean()), posterior_kl=float(gap.mean()),
                posterior_mean=post_mu.tolist(), posterior_variance=float(post_v))


def fit(steps=1200, rate=.01):
    if isinstance(steps, bool) or not isinstance(steps, int) or not 0 <= steps <= 5000 or not 0 < rate <= .02:
        raise ValueError('Use 0..5000 integer steps and learning rate in (0,.02].')
    p = INITIAL.copy(); history = [objective(p)[0]]
    for i in range(steps):
        _, grad = objective(p)
        p -= rate*grad
        if (i+1) % 100 == 0 or i+1 == steps:
            history.append(objective(p)[0])
    return p, history


def demo():
    p, history = fit()
    noise = np.random.default_rng(12).normal(size=(len(DATA), 32))
    return dict(parameters=p.tolist(), exact_quadrature_loss=history,
                analytic=analytic(p), fixed_seed_mc_negative_elbo=objective(p, eps=noise)[0],
                setting='Six synthetic scalar observations; no held-out accuracy or paper reproduction.')


if __name__ == '__main__':
    print(json.dumps(demo(), indent=2, allow_nan=False))

Exact negative ELBO falls from 3.465322 to 1.691041 nats/observation. The final reconstruction NLL is about 0.745127 and prior KL about 0.945914, which sum to that objective. True marginal NLL is about 1.690697, with remaining posterior KL about 0.000343866: close, but not equal.

One fixed-seed sampled negative ELBO is 1.672002, below true marginal NLL. The probability identity has not failed. Exact negative ELBO is an upper bound; a finite-sample estimator need not exceed true NLL on every realization.

Companion checks take finite differences of all six parameters, both with exact nodes and common random noise, and use independent analytic formulas for reconstruction and the posterior gap. The six observations have mean zero and variance 1.72. The model can match marginal variance 1.72 using a2=1.47a^2=1.47, but the 1200-step result is not certified as a global optimum.

For NN scalar observations and SS nodes or samples each, a step uses O(NS)O(NS) time and stored-array space; fixed S=2S=2 gives O(N)O(N). A neural VAE adds encoder/decoder depth, width and activation storage. This six-parameter cost is not an estimate for image training.

Implementation choices can change the interpretation

Match the observation distribution first. Binary observations can use a Bernoulli likelihood; real observations can use a Gaussian with a specified variance or another density. The pinned PyTorch example uses ToTensor grayscale inputs, summed BCE and summed KL. With fractional targets, BCE can be a soft-label cross-entropy, but should not be called a Bernoulli probability density over continuous grayscale. Comparisons must also align sums and means over pixels, latent dimensions and batches.

For generation, draw zz from the prior, then sample the decoder’s observation distribution. Returning only az+caz+c yields a conditional mean and omits observation variance τ2\tau^2; its distribution differs from that of a full generated xx. Reconstruction instead begins with q(z∣x)q(z\mid x). Mixing these procedures obscures the relationship between good reconstruction and good unconditional generation.

A diagonal Gaussian restricts posterior shape, and a shared encoder may not express every observation’s best approximation simultaneously. If qq equals the prior and the decoder ignores zz, the prior KL is zero but the latent communicates no input information. Low KL alone is therefore not a success measure. This linear example checks the computation; it neither reproduces high-dimensional image quality nor has a separate real-data test set.

Check four parts of the generative model

  1. With μ=0,ℓ=log⁡4\mu=0,\ell=\log4, what multiplies standard-normal noise, and what is the KL to the standard normal?

Answer: The multiplier is two and the variance is four. KL is (4−1−log⁡4)/2≈0.806853(4-1-\log4)/2\approx0.806853. Multiplying noise by four instead produces variance sixteen and a different qq.

  1. At a=1,c=0,τ2=0.25,x=1a=1,c=0,\tau^2=0.25,x=1, which encoder distribution makes the posterior gap zero?

Answer: q=N(0.8,0.2)q=\mathcal N(0.8,0.2) matches both true posterior mean and variance. Merely making the reconstruction mean close to one is a different requirement.

  1. Why do duplicating every observation leave the code’s mean objective and gradient unchanged? What if mean is changed to sum?

Answer: Duplication doubles both the numerator and observation count, preserving their mean. The same averaging applies to gradients. With a sum instead, both objective and gradient double; at the same learning rate, the update magnitude doubles too. Both the logging scale and optimization scale change.

  1. At a=1,c=0a=1,c=0, compare the marginal variance when generation returns only decoder mean zz versus actually sampling x∣zx\mid z.

Answer: Mean-only output has variance one. Full generation adds independent observation noise, giving variance 1+0.25=1.251+0.25=1.25. A cleaner-looking mean output is not a sample from the model’s full observation distribution.

Papers, a runnable reference and teaching simplifications

AEVB was first submitted on 2013-12-20; this article uses the method sections 2–3 of v11 dated 2022-12-10. The read Rezende v1 is dated 2014-01-16 and covers Gaussian derivatives, coordinate transformations and the opening bound discussion; its title differs from the final PMLR paper. Together they explain joint learning of stochastic encoders and generative models without reducing attribution to an unqualified invention claim.

The PyTorch VAE example is pinned to commit acc295d dated 2025-09-01. Reading covered lines 35–89, its README and the complete root BSD3-Clause license; upstream training was not executed and its implementation was not copied. This article’s original six-parameter Gaussian model deliberately uses a tractable posterior, two-node exact integration and a small dataset.

Make a prediction, then check

An encoder outputs log variance ℓ. What multiplies standard-normal noise?

Choose one answer

Learning objectives

  • Distinguish encoder, decoder and prior roles.
  • Derive Gaussian KL and log-variance scaling.
  • Train and gradient-check all six model parameters.
  • Separate exact integration, sampled bounds and generative likelihood.

Prerequisites & connections

Explore related knowledge →

References

  1. Auto-Encoding Variational Bayes (v11): bound and reparameterization
    Diederik P. Kingma; Max Welling · 2022
  2. Stochastic Back-propagation and Variational Inference in Deep Latent Gaussian Models (v1)
    Danilo Jimenez Rezende; Shakir Mohamed; Daan Wierstra · 2014
  3. PyTorch examples: VAE implementation at acc295d
    PyTorch examples contributors · 2025

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-13 · Single AI author checked AEVB v11 method sections, Rezende v1 Gaussian transforms and fixed PyTorch VAE code. Nine paired equations and four explained exercises; six-parameter Gaussian VAE with exact quadratic quadrature, full gradients, true marginal/posterior and a sampled-bound counterexample. No image benchmark replication.

  • Verified all6 parameter gradients for exact two-node integration and fixed Gaussian noise, independent analytic objective, posterior KL identity,1200 updates, mean scaling and sampled negative ELBO below true NLL.
  • Four computed SVGs per topic bind the exact bilingual MDX. The four-topic group passed15 numeric/geometry checks and24 isolated language/width cases with four fallback fonts; eight representative screenshots were actually inspected. VAE heading changed from draw to estimate; original figures preserved, data unchanged. Literal-prose AST checked before freezing. Full article-page acceptance is separate; no independent human review.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.