Quant Memo
Advanced

Variational Autoencoders

A variational autoencoder compresses data into a probability distribution instead of a single fixed code, which forces the latent space to be smooth and continuous enough that sampling a new point from it produces a plausible, never-before-seen example.

Prerequisites: Autoencoders, Bayes' Theorem

An ordinary autoencoder compresses each input to one specific point in a latent space, and nothing in its training ever asks those points to be organized sensibly. Two similar inputs might land far apart; the empty gaps between training points might decode into garbage. That's fine if all you want is reconstruction, but it's fatal if you want to generate new examples by picking a fresh point and decoding it — you have no way of knowing which points in that latent space are "valid."

A variational autoencoder (VAE) fixes this by encoding each input not as a single point but as a small cloud of uncertainty around a point — a probability distribution. Picture the difference between pinning a single photograph of a person to a corkboard versus pinning a fuzzy, soft-edged region labeled "roughly here, give or take." When you train the whole board to have every fuzzy region overlap sensibly with its neighbors and blanket the space without gaps, picking any random point on the board — even one that isn't the exact center of anyone's photo — lands you somewhere plausible.

The mechanics, one symbol at a time

The encoder no longer outputs a code zz directly; it outputs the parameters of a distribution over zz — typically a mean μ\mu and a spread σ\sigma for a Gaussian. A sample is then drawn from that distribution and passed to the decoder, and training optimizes two objectives at once:

L=xx^2reconstruction+βDKL(N(μ,σ2)N(0,1))regularizer\mathcal{L} = \underbrace{\| x - \hat{x} \|^2}_{\text{reconstruction}} + \beta \cdot \underbrace{D_{\text{KL}}\big(\mathcal{N}(\mu, \sigma^2) \,\|\, \mathcal{N}(0, 1)\big)}_{\text{regularizer}}

In words: the first term is the same reconstruction error as an ordinary autoencoder — decode the sampled zz and check how close you got back to xx. The second term, the KL divergence, penalizes the encoder's distribution for straying from a plain, standard bell curve centered at 0 with spread 1; it's a measure of how different two probability distributions are, and pushing it toward zero pulls every input's fuzzy region toward a shared, overlapping, well-organized space rather than letting each input claim its own isolated corner. β\beta controls the trade-off: push it up and the latent space becomes tidier and more generative-friendly but reconstructions get blurrier; push it down and you get sharper reconstructions but a messier, less sample-able space.

Sampling from a distribution inside a network that needs to backpropagate is normally impossible — you can't take a gradient through a random draw. VAEs solve this with the reparameterization trick: instead of sampling zz directly, sample a fixed random number ϵN(0,1)\epsilon \sim \mathcal{N}(0,1) and compute z=μ+σϵz = \mu + \sigma \cdot \epsilon. The randomness is now isolated in ϵ\epsilon, which needs no gradient, while μ\mu and σ\sigma remain ordinary, differentiable outputs of the encoder.

Worked example 1: encoding, sampling, and decoding one input

An input encodes to μ=1.5\mu = 1.5, σ=0.3\sigma = 0.3 (a 1-dimensional latent space, for hand computation). Draw a random standard normal sample, say ϵ=0.8\epsilon = 0.8 (a value 0.8 standard deviations above the mean of a standard bell curve — a plausible, not extreme, draw).

z=μ+σϵ=1.5+0.3(0.8)=1.5+0.24=1.74z = \mu + \sigma \epsilon = 1.5 + 0.3(0.8) = 1.5 + 0.24 = 1.74

Decode z=1.74z=1.74 through the decoder — suppose it's the simple linear decoder x^=2.1z0.5\hat{x} = 2.1z - 0.5: x^=2.1(1.74)0.5=3.6540.5=3.15\hat{x} = 2.1(1.74) - 0.5 = 3.654 - 0.5 = 3.15. Run the same input through the encoder again and ϵ\epsilon will be different each time (it's freshly sampled), giving a slightly different zz and thus a slightly different reconstruction — the same input produces a small family of plausible outputs rather than one exact copy, which is the direct, mechanical consequence of encoding to a distribution instead of a point.

Worked example 2: the KL penalty, computed

For a Gaussian N(μ,σ2)\mathcal{N}(\mu, \sigma^2) against the standard normal N(0,1)\mathcal{N}(0,1), the KL divergence has a closed form:

DKL=12(μ2+σ2ln(σ2)1)D_{\text{KL}} = \frac{1}{2}\left(\mu^2 + \sigma^2 - \ln(\sigma^2) - 1\right)

Using μ=1.5\mu = 1.5, σ=0.3\sigma = 0.3: DKL=12(2.25+0.09+2.4081)1.87D_{\text{KL}} = \frac{1}{2}(2.25 + 0.09 + 2.408 - 1) \approx 1.87. Compare a better-behaved encoding, μ=0.2\mu = 0.2, σ=0.9\sigma = 0.9, close to the standard normal: DKL=12(0.04+0.81+0.2111)0.03D_{\text{KL}} = \frac{1}{2}(0.04+0.81+0.211-1) \approx 0.03, far smaller. The first encoding sits confidently far from the origin with a tight spread — good for accurate reconstruction, bad for the shared latent space the KL term wants; the second costs some reconstruction precision but is close to what the regularizer rewards.

Function explorer
-2222.8
x = 1.00f(x) = 0.000

The ln(σ2)-\ln(\sigma^2) term inside the KL formula is why a variance collapsing toward zero (an overconfident encoder claiming "this input is exactly this point, no uncertainty") is punished increasingly harshly — the explorer above shows how a log-based penalty blows up as its argument shrinks toward zero, exactly the shape of that term.

plain autoencoder: isolated points, gaps VAE: overlapping regions, continuous
The KL penalty pulls every input's encoded region toward a shared, overlapping space, so any point sampled from that space — not just the exact centers — decodes to something plausible.

What this means in practice

Once trained, a VAE can generate new synthetic examples by skipping the encoder entirely: sample zz straight from N(0,1)\mathcal{N}(0,1) and feed it to the decoder. In finance this is used to generate synthetic market scenarios or price paths for stress-testing a strategy against situations that never happened historically but are statistically plausible, and for anomaly detection using the same reconstruction-error logic as a plain autoencoder. The β\beta trade-off is the main practical knob: too high and reconstructions get blurry; too low and the latent space degenerates back toward a plain autoencoder's disorganized one, defeating the purpose.

A VAE encodes inputs as probability distributions rather than fixed points, and a KL penalty pulls those distributions toward a shared, overlapping space — the reparameterization trick makes that random sampling differentiable, and the payoff is a latent space you can sample from to generate new, plausible data.

The classic confusion: treating a VAE's latent samples as literally interchangeable with the original data. Generated samples are only as plausible as the training distribution the model saw and only as diverse as the latent space genuinely captures — a VAE trained on calm-market data will generate more calm-market scenarios, not crisis scenarios, no matter how many times you sample; it interpolates within what it learned, it does not extrapolate to what it never saw.

Related concepts

Practice in interviews

Further reading

  • Kingma & Welling, Auto-Encoding Variational Bayes
  • Goodfellow, Bengio & Courville, Deep Learning, ch. 20
ShareTwitterLinkedIn