Review: learning a distribution, divergences and the map of generative models
Review maximum likelihood as forward KL minimization and alternative divergences (reverse KL, Jensen-Shannon, Wasserstein and Fisher), focusing on the behavior each induces. Build a taxonomy based on likelihood access, investigate disjoint low-dimensional supports, and introduce the trade-off between quality, diversity and speed.
After this lesson you can
- Prove that maximizing expected log-likelihood minimizes KL(p_data ‖ p_θ).
- Predict whether a divergence objective may cover multiple modes or concentrate on one.
- Classify generative models by whether they provide an exact likelihood, a bound, or neither.
- Use disjoint supports to explain why JS has no gradient while Wasserstein distance does.
- Build the 2D and digit datasets used throughout the module.
Before you start
One distribution, several questions
An image classifier returns a label for an image. A generator must answer a different question: which images could appear, and how often? If it always produces a perfect image of a single digit, individual quality may be high and coverage poor. If it assigns probability to every possible image as well as much noise, it may cover the data while producing unconvincing samples.
Training samples are not the distribution. Memorizing the finite dataset may look convincing during training yet fail on new examples. The separation between training and evaluation matters here as much as it does for a classifier. Before choosing an architecture, consider which error matters. In the figure, a deliberately limited family, a single Gaussian, tries to represent two groups. Change the objective and observe both the fit and the region between groups.
Choosing an objective does not make an insufficient family expressive. The figure is a toy mathematical model, not a measurement of an image model. To understand its behavior, first establish the assumptions under which likelihood has an exact interpretation.
Maximum likelihood and coding in bits
Let and be densities with respect to the same measure. Assume , finite entropy and finite relevant integrals. With natural logarithms,
Since does not depend on , maximizing expected log-likelihood is equivalent to minimizing forward KL. If is zero where has mass, KL is infinite. Given independent observations from , replace the expectation by the empirical mean. This is the maximum-likelihood estimator, not a guarantee of having minimized population KL with a finite sample. The log-likelihood adds the contribution of each observation.
For discrete symbols, is the ideal code length in bits associated with ; its expectation is the cross-entropy. A loss of nats per example with discrete components corresponds to bits per dimension. Continuous densities are not probabilities of exact values: they change with the units and can exceed 1. Comparing discrete images with continuous models requires specifying quantization and dequantization. Adding uniform noise within each cell relates density and cell probability, but does not automatically turn a pointwise log-density into a probability mass.
The divergence determines what is penalized
Forward and reverse KL weight different regions. integrates under the data: ignoring a region of positive probability is costly if is small there. integrates under the model: assigning mass where is small is costly, whereas an ignored mode does not directly appear in the expectation under . This explains the tendency to cover modes or concentrate on one when a single Gaussian approximates a separated mixture. It does not prove that every reverse-KL optimization collapses, or that forward KL covers all modes well with finite data and capacity.
To see why a forward fit of a Gaussian covers the mixture, suppose in one dimension and that has finite positive variance. The part of the NLL depending on and is . Differentiation gives the optimum and . For two equally weighted components with centers and and variance , this gives zero mean and variance . If is large relative to , the optimal Gaussian necessarily assigns mass to the gap. Reverse KL penalizes this region of low density under . It can nevertheless have multiple local minima and its result depends on the optimization.
Jensen-Shannon uses and . It is symmetric and bounded by with natural logarithms. It belongs to the f-divergences; its bound avoids infinities but can leave a flat objective. The Wasserstein distance minimizes over all couplings with marginals and . It considers how far mass must move as well as overlap. Finite first moments make it finite.
Fisher divergence compares score fields for positive differentiable densities with finite integrals: . It does not require the normalizing constant of because its spatial gradient vanishes. It does require score information and regularity assumptions; it is not a universal distance between arbitrary measures.
The direction of evaluation matters too. A model assigning high probability to typical examples may assign excessive probability to out-of-distribution observations; pointwise density is not a universal measure of semantic similarity. Conversely, judging a handful of hand-picked samples can hide a missing mode. Useful evaluation combines held-out log-likelihood when available with diversity and quality, and checks memorization and splits. The evaluation lesson measures these properties separately.
The geometry of support
Take uniform on and uniform on , with . For the supports are disjoint: both KL divergences are infinite and . The coupling preserving moves every point by , so . The difference between the means of the second coordinate gives the lower bound , establishing equality. For , the derivative of JS is zero and that of is one. At zero the support changes; do not confuse this discontinuity with an ordinary gradient.
Adding positive-variance Gaussian noise to both distributions creates positive, overlapping densities and can provide a gradient signal. If noise is too small relative to separation, however, the numerical signal may remain tiny. Shifted supports and Wasserstein topology motivate the analysis of Arjovsky, Chintala and Bottou; changing divergence alone does not guarantee stable training.
From noise to data: a map of model families
If and , the generated distribution is the pushforward measure . We can sample without knowing how to evaluate . For example, if reduces dimension, its output may be singular even though has a density. In an invertible flow of equal dimension, a change of variables instead permits density evaluation if the inverse and Jacobian determinant are tractable.
| Family | What it provides | How to obtain a sample |
|---|---|---|
| Autoregressive | Exact product of evaluable conditionals | Sequential component sampling |
| Normalizing flow | Exact density when the inverse and Jacobian are tractable | Invertible transformation of noise |
| VAE | Variational bound on generally intractable marginal log-likelihood | Latent prior and decoder |
| GAN | Implicit procedure, generally without evaluable density | One generator pass |
| Energy | Unnormalized energy; partition function is often intractable | For example, a Markov chain |
| Score | Gradient of log-density, not necessarily normalized density | Iterative numerical dynamics |
| DDPM | Variational bound for the specified model | Denoising transitions |
| Flow matching | Continuous flow field; density can be obtained by integrating the change-of-variables ODE, usually approximately | Solve an ODE |
Evaluating a continuous density with a numerical ODE is not the same as a closed-form formula or an exact mass for discrete pixels. A score alone does not provide the normalizing constant for free. The review by Bond-Taylor and colleagues compares families and their trade-offs; Mohamed and Lakshminarayanan explain implicit models as generation procedures.
A GAN can produce samples in one pass and still miss modes; an iterative chain has a cost depending on its number of steps; an autoregressive model can evaluate the probabilities of an observed sequence in parallel in some architectures but generates sequentially. Do not compare call counts alone: the cost of each call can differ. The module derives these families, objectives and metrics before studying acceleration, guidance and generalization.
Lab: fitting models and building data
Start with two known isotropic Gaussians in , equally weighted, with centers and and standard deviation . The training sample uses one seed; the test set uses another. Variance is known to separate the decision about centers from scale. Python indices start at zero. This experiment is an explicit model, not a result on real images.
import numpy as np
centers = np.array([[-2., 0.], [2., 0.]])
sigma = 0.5
def sample_mixture(n, seed):
rng = np.random.default_rng(seed)
k = rng.integers(0, 2, n)
return centers[k] + sigma * rng.normal(size=(n, 2))
def log_mixture(x, means, scale):
z = (x[:, None, :] - means[None, :, :]) / scale
a = -0.5 * np.sum(z*z, axis=2) - np.log(2*np.pi*scale**2)
m = a.max(axis=1)
return m + np.log(np.exp(a - m[:, None]).mean(axis=1))
train = sample_mixture(2000, 7)
test = sample_mixture(2000, 8)
print('Formas:', train.shape, test.shape)
print('NLL de la mezcla verdadera en evaluación:', round(-log_mixture(test, centers, sigma).mean(), 3))Log-sum-exp prevents overflow. For an isotropic Gaussian with fixed scale , the gradient of NLL with respect to its mean is . Here the single Gaussian has fixed scale 2 and only its mean is fitted. We are not calculating the full optimum of mean and variance from the previous section. In the mixture, each point distributes responsibility among components according to posterior probability; each center’s gradient is the average of those responsibilities multiplied by . We implement this without an external optimizer.
def fit_single(x, steps=120, lr=0.1, scale=2.0):
mu = np.array([1., 1.])
for _ in range(steps):
mu -= lr * (mu - x.mean(axis=0)) / scale**2
return mu
def fit_mix(x, steps=100, lr=0.12, scale=0.5):
mu = np.array([[-1., 0.5], [1., -0.5]])
for _ in range(steps):
delta = mu[None, :, :] - x[:, None, :]
a = -0.5 * np.sum(delta*delta, axis=2) / scale**2
a -= a.max(axis=1, keepdims=True)
responsibility = np.exp(a)
responsibility /= responsibility.sum(axis=1, keepdims=True)
grad = (responsibility[:, :, None] * delta).mean(axis=0) / scale**2
mu -= lr * grad
return mu
single = fit_single(train)
mix = fit_mix(train)
print('Media de una gaussiana:', np.round(single, 2))
print('Centros de la mezcla:', np.round(mix, 2))
print('NLL de gaussiana simple en evaluación:', round(-log_mixture(test, single[None, :], 2.).mean(), 3))
print('NLL de mezcla ajustada en evaluación:', round(-log_mixture(test, mix, sigma).mean(), 3))The wide Gaussian also occupies the gap between modes. Now minimize the reverse KL of a Gaussian with fixed scale relative to the known mixture. With and , the entropy term of does not depend on ; the gradient is the expectation of . We reuse fixed noise within each fit to reduce gradient variation. This is a Monte Carlo estimate, not a proof of global optimality.
def reverse_fit(start, steps=100, lr=0.08):
rng = np.random.default_rng(12)
eps = rng.normal(size=(1000, 2))
mu = np.array(start, dtype=float)
for _ in range(steps):
x = mu + sigma * eps
delta = centers[None, :, :] - x[:, None, :]
a = -0.5 * np.sum(delta*delta, axis=2) / sigma**2
a -= a.max(axis=1, keepdims=True)
r = np.exp(a)
r /= r.sum(axis=1, keepdims=True)
score = (r[:, :, None] * delta).sum(axis=1) / sigma**2
mu += lr * score.mean(axis=0)
return mu
print('Inicialización izquierda:', np.round(reverse_fit([-1., 0.]), 2))
print('Inicialización derecha:', np.round(reverse_fit([1., 0.]), 2))This fit knows the true density, an advantage unavailable with arbitrary real data. The two initializations reveal different local solutions. Do not attribute the difference solely to divergence when changing the family, scale or optimization too. By contrast, the library estimator fits a mixture with learned covariances, so it does not solve exactly the same fixed-scale problem either.
Now use two components for reverse KL as well. If is their equally weighted mixture, we can reparameterize one sample from each component. The gradient with respect to their centers averages by component and weight. The explicit derivative of has zero expectation under provided differentiation and integration can be interchanged. Here the Gaussians are regular and scale is fixed. The experiment shows what happens for this initialization; others may lead to a different local optimum.
def mixture_score(x, means, scale):
delta = means[None, :, :] - x[:, None, :]
a = -0.5 * np.sum(delta*delta, axis=2) / scale**2
a -= a.max(axis=1, keepdims=True)
r = np.exp(a)
r /= r.sum(axis=1, keepdims=True)
return (r[:, :, None] * delta).sum(axis=1) / scale**2
def reverse_mix_fit(start, steps=100, lr=0.12):
rng = np.random.default_rng(21)
eps = rng.normal(size=(2, 600, 2))
mu = np.array(start, dtype=float)
for _ in range(steps):
x = mu[:, None, :] + sigma * eps
flat = x.reshape(-1, 2)
gradient = (mixture_score(flat, mu, sigma) -
mixture_score(flat, centers, sigma)).reshape(2, -1, 2)
mu -= lr * gradient.mean(axis=1) / 2
return mu
reverse_mix = reverse_mix_fit([[-1., 0.], [1., 0.]])
print('Centros de mezcla por KL inversa:', np.round(reverse_mix, 2))
print('NLL de esa mezcla en evaluación:', round(-log_mixture(test, reverse_mix, sigma).mean(), 3))Compare both centers and evaluation NLL, but remember that NLL measures the forward direction and is not the objective just optimized. A two-component model can represent the target mixture; a single Gaussian cannot. Success in this controlled construction does not prove that a mixture learned from real data covers every mode.
from sklearn.mixture import GaussianMixture
gm = GaussianMixture(n_components=2, random_state=7, reg_covar=1e-4).fit(train)
print('Centros de biblioteca:', np.round(gm.means_[np.argsort(gm.means_[:, 0])], 2))
print('NLL de biblioteca en evaluación:', round(-gm.score(test), 3))A distribution benchmark
The following benchmark generates each dataset from scratch and always returns an matrix. These are different synthetic distributions: moons and the roll add noise, the spiral and ring have their own scales, and the checkerboard alternates cells. When comparing models, use the same training seeds and different evaluation seeds, and record preprocessing. Do not standardize using statistics calculated on the evaluation set.
def make_dataset(name, n, seed):
if n < 1:
raise ValueError('n debe ser positivo')
rng = np.random.default_rng(seed)
if name == 'lunas':
t = rng.uniform(0, np.pi, n)
side = rng.integers(0, 2, n)
x = np.column_stack((np.cos(t), np.sin(t)))
x[side == 1] = np.column_stack((1-np.cos(t[side == 1]), 0.5-np.sin(t[side == 1])))
return x + 0.05*rng.normal(size=(n, 2))
if name == 'espiral':
t = rng.uniform(0, 4*np.pi, n)
return np.column_stack((t*np.cos(t), t*np.sin(t))) / (4*np.pi)
if name == 'anillo':
k = rng.integers(0, 8, n)
a = 2*np.pi*k/8
return 2*np.column_stack((np.cos(a), np.sin(a))) + 0.08*rng.normal(size=(n, 2))
if name == 'tablero':
i = rng.integers(0, 4, n)
j = (2*rng.integers(0, 2, n) + i % 2)
return np.column_stack((i, j)) + rng.uniform(size=(n, 2)) - 2
if name == 'rollo':
t = rng.uniform(1.5*np.pi, 4.5*np.pi, n)
return np.column_stack((t*np.cos(t), t*np.sin(t))) / (4.5*np.pi) + 0.02*rng.normal(size=(n, 2))
raise ValueError('dataset desconocido')
for name in ['lunas', 'espiral', 'anillo', 'tablero', 'rollo']:
x = make_dataset(name, 1000, 17)
print(name, x.shape, np.round(x.mean(axis=0), 2))Equal visual scaling on both axes avoids turning a circle into an ellipse. The next function accepts an evaluable density and a sample: it plots the density on a grid and overlays points. Its output cannot estimate a GAN density. In that case samples can be plotted, but a density function must not be invented.
import matplotlib.pyplot as plt
def plot_density_samples(log_density, samples, bounds=(-4, 4), size=80):
axis = np.linspace(bounds[0], bounds[1], size)
xx, yy = np.meshgrid(axis, axis)
grid = np.column_stack((xx.ravel(), yy.ravel()))
density = np.exp(log_density(grid)).reshape(xx.shape)
fig, ax = plt.subplots(figsize=(5, 5))
ax.contourf(xx, yy, density, levels=12, cmap='Blues')
ax.scatter(samples[:, 0], samples[:, 1], s=3, alpha=0.35, color='black')
ax.set_aspect('equal')
ax.set_xlabel('x₁')
ax.set_ylabel('x₂')
return fig, ax
fig, ax = plot_density_samples(lambda x: log_mixture(x, mix, sigma), test[:300])
plt.show()For small digits, sklearn.datasets.load_digits provides images and labels. Split indices before fitting transformations. Later stages use MNIST and Fashion-MNIST monochrome images of and CIFAR-10 RGB images of ; check each source’s license, split and normalization. An 8 GB GPU can host many small experiments, but this is not guaranteed by model family: activations, batch size, optimizer and resolution matter. Start with a small batch and measure memory. Full-scale training belongs to the relevant lab.
The scikit-learn digits, MNIST, Fashion-MNIST and CIFAR-10 pages describe their shapes and splits. load_digits is a copy of a digit dataset distinct from MNIST: do not interpret its intensities or results as MNIST results. To avoid confusing quality with input size, keep resolution, range and shape alongside each experiment.
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
digits = load_digits()
idx_train, idx_test = train_test_split(np.arange(len(digits.data)), test_size=0.2,
random_state=7, stratify=digits.target)
print('Imagen:', digits.images[0].shape)
print('Entrenamiento y evaluación:', len(idx_train), len(idx_test))Exercises
Step 1 of 3. How does the logarithm of the ratio decompose?
make_dataset(name, n, seed) for the five names and distributions specified in the lab: lunas, espiral, anillo, tablero and rollo. Return an (n, 2) array, use default_rng(seed) and raise ValueError if the name is unknown or n is not positive. Also implement plot_density_samples(log_density, samples): evaluate the vectorized function on a grid in the square [-4, 4]², plot its exponential and overlay the samples, returning (fig, ax).import numpy as np
import matplotlib.pyplot as plt
def make_dataset(name, n, seed):
pass
def plot_density_samples(log_density, samples):
passA generative model is a distribution or sampling procedure, not a promise of good samples. Likelihood, support geometry, model family and generation cost answer different questions. The rest of the module develops those answers and tests their limits.