Autoencoders & VAE
Learning compressed representations — from dimensionality reduction to generative models
Autoencoder Basics
An autoencoder learns to compress data into a lower-dimensional representation and reconstruct it.
Architecture
Input → [Encoder] → Latent Code → [Decoder] → Reconstruction
x f(x) z g(z) x̂- Encoder
: Maps input to latent code - Latent/Bottleneck: Low-dimensional representation
- Decoder
: Reconstructs from latent code
Loss Function
Reconstruction loss: Minimize difference between input and output
For images, can also use perceptual loss or binary cross-entropy.
Why the Bottleneck?
Without the bottleneck, the network could just learn the identity function. The bottleneck forces the network to learn a compressed representation — keeping only the most important features.
| Autoencoder Type | Bottleneck | Result |
|---|---|---|
| Undercomplete | Compression | |
| Overcomplete | Needs regularization |
Autoencoder Applications
Dimensionality Reduction
Like PCA but non-linear:
encoder = train_autoencoder(data)
embeddings = encoder(data) # Low-dimensional representationsAdvantage over PCA: Can capture non-linear relationships.
Denoising Autoencoders (DAE)
Train to reconstruct clean input from corrupted input:
noisy_x = x + noise
loss = ||x - decoder(encoder(noisy_x))||²Forces the network to learn robust features that ignore noise.
Anomaly Detection
- Train autoencoder on normal data
- High reconstruction error = anomaly
error = ||x - autoencoder(x)||²
if error > threshold:
flag_as_anomaly(x)The Problem with Standard Autoencoders
Standard autoencoders have unstructured latent spaces:
- Gaps between encoded points
- No meaningful interpolation
- Can't sample new data points
Key limitation: Great for compression, poor for generation.
Variational Autoencoders (VAE)
VAEs add probabilistic structure to the latent space, enabling generation of new samples.
Key Idea
Instead of encoding to a point, encode to a distribution:
- Encoder outputs
and (mean and std of Gaussian) - Sample
from this distribution - Decoder reconstructs from
Architecture
x → Encoder → (μ, σ) → Sample z ~ N(μ, σ²) → Decoder → x̂VAE Loss (ELBO)
Reconstruction term: How well does the decoder reconstruct? KL term: How close is the encoded distribution to the prior (standard Gaussian)?
The Reparameterization Trick
Problem: Sampling is not differentiable. We can't backprop through
Solution: Reparameterize the sampling:
Now:
is a random constant (not a function of parameters) and are deterministic functions of the encoder - Gradients flow through
and
Implementation
def reparameterize(mu, log_var):
std = torch.exp(0.5 * log_var) # σ = exp(0.5 * log(σ²))
eps = torch.randn_like(std) # ε ~ N(0, 1)
return mu + std * eps # z = μ + σ * εELBO Derivation (Simplified)
We want to maximize
Evidence Lower Bound (ELBO):
Where:
= prior (standard Gaussian) = encoder (approximate posterior) = decoder (likelihood)
Maximizing ELBO:
- Maximizes reconstruction quality (
) - Minimizes distance to prior (
)
KL Divergence for Gaussians
For
This has a closed-form solution — no sampling needed.
VAE vs Standard Autoencoder
| Aspect | Standard AE | VAE |
|---|---|---|
| Latent | Point | Distribution $q(z |
| Structure | Unstructured | Smooth, regularized |
| Generation | Poor | Sample from prior |
| Interpolation | Gaps, artifacts | Smooth transitions |
| Loss | Reconstruction only | Reconstruction + KL |
VAE for Generation
Sampling New Data
# Sample from prior
z = torch.randn(batch_size, latent_dim)
# Decode to generate new data
x_generated = decoder(z)Latent Space Interpolation
# Encode two images
z1 = encoder(x1)
z2 = encoder(x2)
# Interpolate in latent space
for alpha in [0, 0.25, 0.5, 0.75, 1.0]:
z_interp = (1 - alpha) * z1 + alpha * z2
x_interp = decoder(z_interp)VAE's regularized latent space ensures smooth interpolation.
Advanced VAE Topics
Beta-VAE
Add weight to KL term for disentangled representations:
Higher
Conditional VAE (CVAE)
Condition on labels for controlled generation:
(x, y) → Encoder → z → Decoder(z, y) → x̂VQ-VAE
Vector-quantized VAE with discrete latent codes. Used in image generation (DALL-E 1) and audio (Jukebox).
Interview Questions
Q1: "Explain the reparameterization trick."
The problem: In VAE, we sample
where and come from the encoder. But sampling is not differentiable — we can't backprop through a random sample. The solution: Reparameterize the sampling:
Now:
is sampled from a fixed distribution (no parameters) is a deterministic function of , , and - Gradients flow through
and to the encoder Key insight: We moved the randomness to a parameter-free variable
, making the path from encoder to loss differentiable.
Q2: "What are the two terms in the VAE loss and what do they do?"
VAE loss (ELBO):
Reconstruction term (
):
- Measures how well the decoder reconstructs the input
- Typically MSE for images, cross-entropy for binary data
- Encourages accurate reconstruction
KL divergence term (
):
- Measures how close the encoder's distribution is to the prior (standard Gaussian)
- Regularizes the latent space
- Encourages smooth, structured latent space
Trade-off:
- High reconstruction weight → sharp outputs but gaps in latent space
- High KL weight → smooth latent space but blurry outputs
- Beta-VAE uses
to control this trade-off
Q3: "When would you use an autoencoder vs VAE?"
Use standard autoencoder when:
- Only need compression/encoding (not generation)
- Dimensionality reduction for downstream tasks
- Feature extraction for other models
- Anomaly detection (reconstruction error)
Use VAE when:
- Need to generate new samples
- Want meaningful interpolation in latent space
- Need a structured latent space for manipulation
- Semi-supervised learning with latent structure
Key difference: Standard AE may have gaps and discontinuities in latent space. VAE's regularization ensures you can sample anywhere in latent space and get realistic outputs.
Trade-off: VAE outputs are often blurrier than AE because KL regularization spreads the latent space, reducing reconstruction sharpness.
Key Takeaways
Autoencoders learn compressed representations through encoder-decoder architecture with reconstruction loss.
VAEs encode to distributions instead of points, enabling generation.
Reparameterization trick makes VAE training possible by moving randomness outside the gradient path.
ELBO combines reconstruction and regularization — balancing output quality and latent structure.
VAE's regularized latent space enables sampling new data and meaningful interpolation.
Use AE for compression, VAE for generation — choose based on whether you need to sample new data.