Skip to content
BIASED

Fitting distributions with KL

Block 1 of 7~2 min

A training loop for two numbers

The topic Entropy, cross-entropy and KL showed that minimizing the forward KL DKL(P ∥ Qθ)D_{\mathrm{KL}}(P \,\|\, Q_\theta) is the same as maximizing the likelihood of samples from PP. Now we run that minimization and look at the answer it gives. The model is the simplest one from Multivariate Gaussians: a single one-dimensional Gaussian.

We write the model as Qθ=N(μ,σ2)Q_\theta = \mathcal N(\mu, \sigma^2) with parameters θ=(μ,s)\theta = (\mu, s), where s=log⁡σs = \log\sigma. The optimizer moves ss anywhere on the real line, and σ=es\sigma = e^s stays positive whatever step it takes.

In a toy problem we choose the target ourselves, so its density pp is known. Then the KL can be estimated by Monte Carlo from samples x1,…,xN∼Px_1, \dots, x_N \sim P:

DKL(P ∥ Qθ)≈1N∑i=1N[log⁡p(xi)−log⁡qθ(xi)].D_{\mathrm{KL}}(P \,\|\, Q_\theta) \approx \frac1N \sum_{i=1}^N \big[\log p(x_i) - \log q_\theta(x_i)\big].

The samples stay fixed during training. Each step builds QθQ_\theta from the current μ\mu and σ=es\sigma = e^s, evaluates log⁡qθ\log q_\theta at the samples, averages, and differentiates. Then gradient descent moves both parameters against their gradients with a learning rate η\eta:

μ←μ−η ∂L∂μ,s←s−η ∂L∂s.\mu \leftarrow \mu - \eta\,\frac{\partial \mathcal L}{\partial \mu}, \qquad s \leftarrow s - \eta\,\frac{\partial \mathcal L}{\partial s}.

In practice Adam replaces the plain step: it rescales each coordinate using running statistics of its gradients. Autograd computes the derivatives; here we will also find them by hand.

Answers are saved on the server and tied to this browser until you sign in.