An autoencoder can reconstruct a handwritten digit from a compressed representation. But what happens when you give its decoder a randomly selected latent vector instead of encoding an existing image?
There is no guarantee that the result will resemble a meaningful handwritten digit. Learning to reconstruct data and learning to generate data are different problems.
A Variational Autoencoder (VAE) addresses this distinction by combining representation learning, probabilistic modeling, and variational inference. Instead of encoding an input as a fixed latent vector, it represents the input as a probability distribution over possible latent codes.
Understanding how these components fit together explains why VAEs use probabilistic encoders and decoders, how their training objective is constructed, and how they generate new data.
From Autoencoders to Generative Models
A conventional encoder–decoder architecture transforms an input into an internal representation and uses that representation to produce an output.
An autoencoder specializes this architecture for input reconstruction:
Here, and are the encoder and decoder, and are their trainable parameters, and is the latent representation.
A typical reconstruction objective is mean squared error (MSE):
Here, is the dimensionality of the input. By minimizing reconstruction error, the model learns to preserve information needed to reconstruct its inputs.
Because the input itself serves as the reconstruction target, separate labels are unnecessary. The learned representations can also support tasks such as classification and clustering.
However, low reconstruction error does not necessarily indicate that the encoder has learned useful features. A sufficiently flexible model could simply learn to copy its input.
An undercomplete autoencoder uses a latent representation with fewer dimensions than the input, encouraging the encoder to retain important information. An overcomplete autoencoder uses a latent representation with more dimensions than the input, allowing richer representations but potentially requiring additional constraints to prevent simple copying.
Neither architecture inherently defines how to select latent vectors for generating new data. To move from reconstruction to generation, we need a distribution from which latent variables can be sampled and a model that describes how those variables produce observations.
Define a Generative Process Before Learning an Encoder
Consider handwritten images. Changing the thickness or slant of a digit affects multiple pixels simultaneously. A latent variable can represent an underlying factor that influences several observed components.
A probabilistic latent variable model defines generation in two steps:
The resulting joint distribution is:
The prior determines how latent variables are selected. The conditional distribution determines how observations are generated from them.
This structure allows dependencies between observed components to emerge through shared latent variables, even when those components are modeled as conditionally independent given .
Marginal likelihood
Different latent variables can produce similar observations. Evaluating how well the model explains an observed input therefore requires considering all possible latent variables:
This operation is called marginalization. The resulting marginal probability or density is the marginal likelihood of the observed data. For discrete latent variables, the integral becomes a sum.
VAEs belong to the likelihood-based family of generative models. Unlike implicit models such as GANs, they define probability distributions and optimize a likelihood-related objective.
Computing the marginal likelihood exactly can become intractable when the latent space is high-dimensional and the conditional distribution is parameterized by a complex neural network. Variational inference and the ELBO provide a way to train the model without evaluating this integral directly.
Variational Inference: Learning the Reverse Direction
Generation proceeds from latent variables to observations. Learning also requires the reverse direction: given an observation, which latent variables could explain it?
Bayes' theorem defines the posterior:
The numerator combines the prior with the conditional likelihood. The denominator is the marginal likelihood, which normalizes the posterior but is difficult to compute directly.
Monte Carlo estimation using samples from the prior is possible. However, it can be inefficient when the latent variables that explain an observation occupy only a narrow region of the latent space.
Variational inference addresses this problem by introducing a computationally manageable approximation to the true posterior.
Given a variational family , the objective is:
KL divergence measures the discrepancy between the approximate and true posterior:
KL divergence is non-negative and becomes zero when the distributions match. It is generally asymmetric, so it is not a distance metric in the usual mathematical sense.
A mean-field approximation simplifies inference by factorizing the approximate distribution:
This independence assumption belongs to the approximation, not necessarily to the true posterior. It improves computational tractability but may prevent the approximation from capturing complex dependencies between latent variables.
Amortized inference
Using a Gaussian approximation allows inference to focus on distribution parameters such as means and variances. Optimizing a separate set of parameters for every observation, however, would require substantial computation.
A VAE instead trains a shared encoder to predict those parameters:
Here, denotes the variational distribution parameters associated with input .
This approach is called amortized inference. Once trained, the encoder can construct an approximate posterior for a new observation through a forward pass rather than performing a separate iterative optimization.
The encoder is therefore more than a feature extractor: it is a learned inference function.
ELBO: Turning Intractable Inference into a Trainable Objective
Directly minimizing KL divergence from the true posterior still appears to require access to that posterior. Substituting Bayes' theorem into the divergence reveals a more useful formulation:
For fixed and , the log marginal likelihood does not depend on the approximate distribution. Its exact value is therefore unnecessary when optimizing that distribution.
This leads to the Evidence Lower Bound (ELBO):
The relationship between the ELBO and the log marginal likelihood is:
Because KL divergence is non-negative:
For a fixed generative model, maximizing the ELBO is equivalent to minimizing the divergence between the approximate and true posterior. The bound becomes exact when the two distributions match.
The two terms that define VAE learning
Substituting the factorized joint distribution into the ELBO gives the familiar VAE objective:
The objective contains two complementary terms:
- Reconstruction term: measures how well latent variables sampled from the approximate posterior explain the observed data.
- Regularization term: measures how far the input-specific approximate posterior deviates from the shared prior used for generation.
The two KL divergences appearing in the derivation serve different purposes:
- The divergence from the true posterior measures the gap between the ELBO and the log marginal likelihood.
- The divergence from the prior acts as a regularization term inside the ELBO.
A small prior KL divergence does not, by itself, imply accurate posterior approximation.
During joint optimization of the encoder and decoder, the generative model also changes. Increasing the ELBO therefore does not guarantee an increase in the exact log marginal likelihood at every optimization step.
What a VAE Actually Computes
The architecture follows directly from the probabilistic model and its inference objective.
Input
↓
Encoder
↓
Approximate posterior parameters
↓
Latent sampling
↓
Latent vector
↓
Decoder
↓
Output distribution parameters
Unlike a deterministic autoencoder, a VAE uses an encoder and decoder that parameterize conditional probability distributions, with a sampled latent vector connecting them.
Encoder: predict a distribution
A common VAE uses a Gaussian approximate posterior with diagonal covariance:
For a latent space with dimensions, the encoder determines means and variances.
The mean vector specifies the center of the distribution, while the variances determine the spread along each latent dimension. Using diagonal covariance constrains the conditional covariances between different latent dimensions to zero.
Even when the distribution parameters remain the same for a given input, sampling from that distribution can produce different latent vectors. The decoder receives a sampled vector, not the entire posterior distribution.
Prior: define where generation starts
Generating data without an existing input requires a shared distribution from which latent variables can be sampled.
A standard choice is the multivariate standard normal distribution:
This prior is easy to sample from and allows a closed-form KL divergence calculation when the approximate posterior is Gaussian with diagonal covariance.
What makes a latent space useful for generation?
A latent space suitable for generation should exhibit two desirable properties:
- Continuity: nearby latent vectors decode into similar observations, allowing gradual changes in latent codes to produce gradual changes in generated data.
- Completeness: sampling from relevant regions of the latent space produces meaningful observations.
A conventional autoencoder can leave untrained regions between latent codes associated with actual observations. Probabilistic encoding and KL regularization help alleviate this problem.
However, a standard normal prior and KL regularization do not guarantee continuity or completeness. Independence between prior dimensions does not automatically imply that meaningful factors of variation will be disentangled.
Decoder Design Determines the Reconstruction Loss
A VAE decoder defines a conditional probability distribution rather than directly returning a reconstructed value:
The reconstruction objective follows from the negative log-likelihood:
The interpretation of a decoder output depends on the chosen distribution. For example, a pixel output of 0.8 could represent a mean intensity under a Gaussian decoder or the probability of a pixel being 1 under a Bernoulli decoder.
Gaussian decoder
For continuous observations, the decoder can parameterize a Gaussian distribution:
With diagonal covariance:
The decoder can predict both the mean and variance, or it can predict only the mean while keeping the variance fixed.
With fixed isotropic covariance and variance , the negative log-likelihood becomes:
Under this assumption, minimizing negative log-likelihood is equivalent to minimizing squared reconstruction error up to a fixed scaling factor and additive constant.
If the variance is learned, the objective also depends on the variance parameters and is no longer equivalent to ordinary MSE.
Bernoulli decoder
For binary observations, the decoder predicts the probability that each output component equals 1.
A conditionally independent Bernoulli decoder defines:
Its negative log-likelihood is:
This corresponds to the sum of binary cross-entropy terms.
Categorical decoder
For categorical observations, the decoder predicts a probability for each possible category, typically using softmax:
The category probabilities satisfy:
For a one-hot observation, the negative log-likelihood is:
This is categorical cross-entropy.
| Decoder distribution | Observation type | Distribution parameters | Reconstruction loss |
|---|---|---|---|
| Gaussian | Continuous | Mean and variance | Gaussian NLL; squared error under fixed isotropic covariance |
| Bernoulli | Binary | Success probabilities | Binary cross-entropy |
| Categorical | Categorical | Category probabilities | Categorical cross-entropy |
The implementation principle is straightforward: choose the observation distribution first, then derive the reconstruction loss from its likelihood.
Distribution means versus generated samples
Returning a representative value from the output distribution is different from sampling an actual observation.
The distribution mean is:
An actual sample is obtained through:
A Gaussian mean can serve as a representative continuous output. A Bernoulli mean, however, represents a success probability rather than an actual binary sample.
The VAE Loss: Reconstruction and Latent Regularization
Neural network optimization typically minimizes a loss, so the VAE minimizes the negative ELBO:
Equivalently:
Optimizing reconstruction alone does not ensure that latent representations align with the prior. Conversely, optimizing only the KL term can cause input-specific approximate posteriors to match the prior and lose information that distinguishes different observations.
Computing the Gaussian KL divergence
For a diagonal Gaussian approximate posterior and a standard normal prior, the KL term has a closed-form expression:
In practice, the encoder commonly predicts log variance rather than variance directly:
The variance and standard deviation are recovered through:
Exponentiating the log variance ensures a positive variance. The KL loss can then be computed directly from the encoder outputs:
Estimating the reconstruction expectation
The reconstruction term is an expectation over the approximate posterior. With a neural network decoder, this expectation is generally difficult to evaluate analytically.
Monte Carlo estimation approximates it with a sample average:
Here, is the number of latent samples used to estimate the expectation.
Increasing the number of samples generally reduces estimation variability but increases computational cost. Mini-batch training and repeated parameter updates make it practical to use relatively few samples per observation.
Both loss terms are now computable, but one problem remains: propagating gradients through the latent sampling step.
The Reparameterization Trick: Enabling Backpropagation Through Latent Sampling
The reconstruction loss must update not only the decoder but also the encoder that produced the latent distribution.
Direct sampling from the encoder's distribution does not explicitly provide the differentiable path required by ordinary backpropagation.
The reparameterization trick separates randomness from the trainable distribution parameters:
Using log variance, the same operation becomes:
Here, is a random noise vector sampled independently of the encoder parameters, and denotes element-wise multiplication.
The resulting latent vector follows the same Gaussian distribution as a direct sample. Once the random noise is sampled, however, the transformation is differentiable with respect to the distribution parameters:
Reparameterization preserves randomness while providing a differentiable path from the sampled latent vector to the encoder parameters.
Monte Carlo estimation and reparameterization therefore solve complementary problems:
- Monte Carlo estimation approximates the expected reconstruction loss.
- Reparameterization allows gradients from that estimate to reach the encoder.
Putting the Training Pipeline Together
Combining the closed-form Gaussian KL term with the sampled reconstruction term gives the practical VAE objective:
Each latent sample is obtained through reparameterization:
The training procedure consists of five operations:
- Encoding: compute the mean and log variance from the input.
- Sampling: draw standard normal noise and construct a latent vector through reparameterization.
- Decoding: use the latent vector to parameterize the output distribution.
- Loss calculation: compute the negative log-likelihood and KL divergence.
- Backpropagation: compute gradients from the combined loss and update the encoder and decoder parameters.
The important implementation detail is that the reconstruction loss has a gradient path through the decoder, sampled latent vector, and encoder.
For a standard VAE with a fixed prior, the encoder receives gradients from both loss terms:
The decoder receives gradients from the reconstruction term:
Both networks are jointly optimized over the training dataset:
Training, Reconstruction, and Generation Are Different Operations
A VAE uses the same decoder for all three operations. What changes is the origin of the latent vector and the purpose of the computation.
| Operation | Latent source | Encoder required? | Purpose |
|---|---|---|---|
| Training | Approximate posterior | Yes | Optimize encoder and decoder |
| Reconstruction | Approximate posterior | Yes | Reconstruct an existing observation |
| Generation | Prior distribution | No | Produce a new observation |
During training and reconstruction, latent variables are conditioned on an existing input:
During generation, latent variables come directly from the prior:
The decoder then defines the distribution from which a new observation can be sampled:
The generation pipeline does not require an encoder or an existing observation:
Prior distribution
↓
Sample z
↓
Decoder
↓
Output distribution
↓
Sample data
This explains why the prior matters during training. The decoder must learn to interpret latent representations in a space that will also be used when no original observation is available.
Limitations of the Standard VAE
The standard VAE makes several modeling choices that improve computational tractability but also introduce limitations.
A diagonal Gaussian approximate posterior may fail to capture complex dependencies in the true posterior. Likewise, a standard normal prior provides a convenient sampling distribution but does not guarantee that every relevant region of the latent space produces meaningful observations.
The choice of observation distribution also constrains how reconstruction quality is evaluated. Gaussian and Bernoulli decoders, for example, make different probabilistic assumptions about the observed data.
Takeaway
A VAE is a probabilistic latent variable model with a learned inference network. The encoder approximates the posterior, the decoder defines the observation distribution, and the ELBO provides a tractable objective for learning both. Monte Carlo estimation approximates the expected reconstruction loss, while reparameterization allows gradients from that estimate to reach the encoder. Together, these components connect representation learning, probabilistic inference, and data generation within a single trainable architecture.
Originally published at zeromathai.com.
Original article: https://zeromathai.com/en/variational-autoencoder-vae-course-en/
Top comments (0)