The prerequisite—and the new question
An ordinary autoencoder learns to compress an input and reconstruct it. Review Autoencoders and Their Variants first if encoder, bottleneck, decoder, or reconstruction is unfamiliar. This lesson asks the next question: how can we organize that bottleneck so that sampling a new point produces a meaningful new output?
A Variational Autoencoder, or VAE, makes the encoder describe a probability distribution instead of assigning each input one fixed latent point. It then samples from that distribution during training and encourages all input distributions to fit into an organized shared latent space.
Variational Autoencoders (VAEs) in Simple Words
Standard autoencoders compress images into single fixed points in space, creating empty "gaps" where invalid garbage sits. A VAE instead maps each input to a smooth cloud of probability (defined by mean $\mu$ and spread $\sigma$). Because every region of this cloud blends seamlessly into its neighbors, picking any random point produces a crisp, realistic new sample!
Encoder
Calculates mean μ and variance σ²
Reparameterize
Samples z = μ + σ ⊙ ε with random ε
Decoder
Reconstructs pixel output from z
KL Regularizer
Forces clouds to hug standard normal prior
Deterministic autoencoder versus VAE
| Question | Deterministic autoencoder | Variational Autoencoder |
|---|---|---|
| Encoder output | One fixed latent vector | Parameters μ and log σ² describing a distribution |
| Latent value used | The encoder vector itself | A sampled z calculated from μ, σ, and random ε |
| Training pressure | Reconstruct the input | Reconstruct while keeping latent distributions near a simple prior |
| Sampling unseen points | May land in gaps the decoder never learned | More likely to land in a smooth, trained region |
Figure 1 — A VAE learns a distribution, samples z, and reconstructs the input
Blue marks observed data, violet marks learned network outputs, amber marks sampled randomness, and green marks values calculated from them. Follow the arrows to see exactly where z comes from.
An input x enters a learned encoder. The encoder produces learned mean mu and log-variance. Independent epsilon is sampled from a standard normal distribution. Mean, log-variance, and epsilon enter the reparameterization calculation z equals mu plus exp of one half log-variance times epsilon. The calculated latent z enters a learned decoder, which produces reconstruction x hat.
The four values in reparameterization
μ (mu): learned centre
The encoder calculates one mean for each latent dimension and each input.
log σ²: learned log-variance
The encoder outputs log-variance because it can be any real number; exponentiation converts it to positive variance.
ε (epsilon): sampled noise
The framework draws ε from a standard normal distribution. It is random and is not a learned parameter.
z: calculated latent sample
z combines the learned centre and spread with ε. The decoder receives z.
Half converts log variance into log standard deviation because variance equals σ². Exponentiation then produces the positive standard deviation used to scale the random draw.
N(0, I) is a standard normal distribution with zero mean and unit variance. ⊙ means element-by-element multiplication. Randomness enters through ε, while z remains a differentiable calculation involving μ and σ, so backpropagation can train the encoder.
Worked example: calculate a two-dimensional z
| Value | Numbers | Source | Meaning |
|---|---|---|---|
| μ | [0.5, -1.0] | Calculated by the learned encoder | Centre of this input’s latent distribution |
| log σ² | [-1.3863, 1.3863] | Calculated by the learned encoder | Logs of variances 0.25 and 4.00 |
| σ | [0.5, 2.0] | Calculated as exp(0.5 × log σ²) | Standard deviation in each dimension |
| ε | [0.4, -0.3] | One sampled standard-normal draw, fixed here for reproducibility | Random offset before scaling |
z = [0.5, -1.0] + [0.5, 2.0] ⊙ [0.4, -0.3]
z = [0.5 + 0.2, -1.0 - 0.6] = [0.7, -1.6]
The first coordinate moved 0.2 above its mean; the second moved 0.6 below its mean. The decoder receives [0.7, -1.6], not μ or ε separately.
Why a VAE needs two loss terms
L_reconstruction measures how well the decoded output x̂ matches input x. The KL-divergence term measures how far the encoder distribution q(z | x) is from a simple prior p(z), usually N(0, I). β is a developer-chosen weight; ordinary VAE training commonly starts with β = 1.
Minimizing reconstruction alone can create isolated latent islands: excellent for known inputs, unreliable for points sampled between them. The KL term pulls distributions toward a shared prior, discouraging holes and making nearby samples more meaningful.
The same idea is often expressed by maximizing the Evidence Lower Bound, or ELBO. In beginner language: reward likely reconstructions while penalizing an irregular latent distribution. Training code usually minimizes the negative ELBO, which becomes reconstruction loss plus KL loss.
Continue the numerical example through the loss
Suppose the input is x = [1, 0] and the decoder produces x̂ = [0.8, 0.1]. Using mean squared error, the reconstruction term is ((1 - 0.8)² + (0 - 0.1)²) / 2 = (0.04 + 0.01) / 2 = 0.025.
Using μ and log σ² from the table gives approximately 0.443 for the first dimension and 1.307 for the second, so KL ≈ 1.750. With β = 1, total loss = 0.025 + 1.750 = 1.775. The large KL term says this example’s latent distribution is still far from the standard-normal prior.
VAE ELBO Loss Balance Across Training Epochs
Total Loss = Reconstruction Loss (negative log-likelihood) + KL Divergence (regularization to standard normal prior).
Reconstruction, generation, and interpolation
Reconstruction
Encode an existing x, sample near its μ, and decode. The result should resemble that input.
Generation
Sample z directly from the prior N(0, I) and decode it. No input example is encoded first.
Interpolation
Move gradually between two latent points and decode the intermediate points to observe smooth feature changes.
Figure 2 — An organized latent space makes new samples and smooth interpolation possible
Generation does not encode an existing input first. It samples a latent point from the prior and decodes it; nearby latent points tend to produce related outputs.
A standard-normal prior supplies a sampled latent point to an organized two-dimensional latent space. Nearby round, softly squared, and square regions are connected by an interpolation path. A learned decoder maps three nearby latent points to smoothly changing generated shapes, demonstrating why a VAE is generative rather than only compressive.
A complete one-step VAE mechanism
This runnable PyTorch example uses two four-value binary samples and a two-dimensional latent space. It shows where μ, log-variance, ε, z, reconstruction loss, and KL loss appear in one optimizer step.
import torch
from torch import nn
from torch.nn import functional as F
torch.manual_seed(7)
class TinyVAE(nn.Module):
def __init__(self):
super().__init__()
self.encoder = nn.Sequential(nn.Linear(4, 8), nn.ReLU())
self.to_mu = nn.Linear(8, 2)
self.to_logvar = nn.Linear(8, 2)
self.decoder = nn.Sequential(nn.Linear(2, 8), nn.ReLU(), nn.Linear(8, 4))
def forward(self, x):
hidden = self.encoder(x)
mu = self.to_mu(hidden)
logvar = self.to_logvar(hidden)
std = torch.exp(0.5 * logvar)
epsilon = torch.randn_like(std)
z = mu + std * epsilon
reconstruction_logits = self.decoder(z)
return reconstruction_logits, mu, logvar, z
model = TinyVAE()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)
x = torch.tensor([[1., 0., 1., 0.], [0., 1., 0., 1.]])
logits, mu, logvar, z = model(x)
reconstruction = F.binary_cross_entropy_with_logits(logits, x, reduction="sum") / x.size(0)
kl = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) / x.size(0)
loss = reconstruction + kl
optimizer.zero_grad()
loss.backward()
optimizer.step()
print({"reconstruction": reconstruction.item(), "kl": kl.item(), "total": loss.item()})Trade-offs and failure modes
| Symptom | Likely pressure | Meaning or diagnostic |
|---|---|---|
| Sharp reconstructions but poor random samples | Reconstruction dominates | Latent regions may be irregular or contain gaps |
| Smooth samples but blurry reconstructions | KL pressure is strong or decoder likelihood is simple | The organized space costs some detail |
| Posterior collapse | Decoder ignores z; KL falls near zero | Check whether changing z changes outputs; KL warm-up or a weaker decoder may help |
| β-VAE with β above 1 | Stronger latent regularization | May separate factors more clearly but can reduce reconstruction quality |
Summary / Key Takeaways
- A VAE encodes each input as a latent distribution described by μ and log σ² instead of one fixed latent point.
- The standard deviation is calculated as σ = exp(0.5 × log σ²), while ε is random noise sampled from N(0, I).
- Reparameterization uses z = μ + σ ⊙ ε so randomness enters through ε while gradients can still train the encoder.
- The VAE objective combines reconstruction loss with β-weighted KL divergence to balance detail against an organized latent space.
- Reconstruction starts from an input, generation samples z directly from the prior, and interpolation decodes points between latent locations.
- Too little latent regularization can leave gaps; too much can blur reconstructions, and posterior collapse means the decoder ignores z.
- A VAE is useful when a smooth, sampleable representation matters, but its generated fine detail may be softer than other model families.