Overview
Ordinary regression predicts one value per input, which is a poor answer when several different outputs are plausible. A mixture density network predicts a whole distribution instead: several Gaussian bumps, each with its own centre, width and weight, all depending on the input. The loss asks how probable the observed target is under that mixture and takes the negative log. A target that lands on a tall, well-weighted bump costs little. Training moves the bumps toward the data, and each bump is updated in proportion to how responsible it was for the target.
A short history
Christopher Bishop introduced mixture density networks in a 1994 technical report. A network trained with squared error predicts the average of the possible targets, which is wrong when one input has several distinct valid answers. Bishop had the network output the weights, means and widths of a mixture of Gaussians and trained it by maximum likelihood. Alex Graves used the idea in 2013 to generate handwriting.
How it works
- The network outputs, for each example, mixing scores, means of dimension , and log standard deviations of dimension .
- Turn the scores into mixing weights with softmax, and clip the log standard deviations to the configured range.
- For each component compute the log of its weight plus the log-density of the target under its diagonal Gaussian.
- Combine the values with log-sum-exp and negate. That is the loss for the example.
- Reduce over the batch with
reduction. - In
backward, compute each component's responsibility for the target and use it to scale that component's gradients. - Use
meanorsampleto read a prediction off the mixture.
Watch out for
- A component can collapse onto a single training point with a width near zero, sending the density to infinity. The clip on the log standard deviation is what stops this.
- The mean of a mixture with two separated bumps lies in the gap between them, where the density is low. Use
sampleor the strongest component, notmean, for multi-modal outputs. - Components can go unused: once a weight is near zero it gets almost no gradient. Careful initialisation of the means helps.
- The Gaussians here are diagonal, so within one component the output dimensions are treated as independent. Correlations must be captured by using several components.
- Multiplying densities directly underflows. The loss must be computed in log space, as the template does.
Use cases
When to use it
Regression where one input can have several valid outputs, such as inverse problems, trajectory prediction and handwriting generation, or whenever you need the uncertainty and not just a point estimate.
In industry
- Handwriting and speech synthesis
- Graves's handwriting generator predicts a mixture over the next pen position, so it can produce varied strokes for the same text.
- Robotics
- Inverse kinematics has several joint settings that reach one hand position, and a mixture output can represent all of them instead of their average.
- Reinforcement learning
- The World Models agent of Ha and Schmidhuber uses a recurrent mixture density network to predict a distribution over the next latent state.
Choosing it: what must hold
- A regression target that can take several distinct values for the same input, or whose spread varies with the input.
- A choice of the number of mixture components, and enough data to fit them.
- Numerically careful code: log-sum-exp for the likelihood and a floor on the widths to prevent collapse.
When to choose something else
| If | Use instead |
|---|---|
| Each input has one plausible target value | Mean squared error or Huber loss |
| The spread varies but there is only one mode | A single Gaussian negative log-likelihood |
| The target is high dimensional, such as an image | A variational autoencoder trained with the ELBO |
Math foundations
The predicted density
A weighted sum of Gaussians. The weights, means and standard deviations are all outputs of the network, so the shape of the distribution changes with the input.
Keeping the parameters valid
Softmax makes the weights positive and sum to 1. The exponential makes every standard deviation positive. The network outputs the unconstrained and .
One Gaussian component in log form
The standardised error says how many standard deviations the target is from the component's centre. A narrow component gains from only if the target is really close.
The loss
The negative log-likelihood, written as a log-sum-exp so that tiny densities do not underflow.
Responsibilities
The posterior probability that component produced the target. The responsibilities sum to 1 and decide how the gradient is shared.
The gradients
Weights move toward the responsibilities. Means move toward the target, scaled by responsibility. A width grows when the target is more than one standard deviation away and shrinks when it is closer.
Symbols
- the input and the target; the target has D dimensions
- the number of mixture components and the target dimension
- mixing weight of component k
- mixing score of component k,
pi_logits - mean of component k in dimension d,
mu - standard deviation of component k in dimension d
- log standard deviation,
log_sigma - the standardised error of the target under component k
- the Gaussian density
- responsibility of component k for the target
- the loss for one example
Worked by hand
One dimension, two components with equal weights 0.5, means 0 and 4, both with . The target is . The standard normal density gives and .
The loss is 2.0939. The first component takes 98 percent of the responsibility, so its mean is pulled toward the target and its weight is pushed up, while the second barely moves.
Visual example
Loading the example.
Try this
- Move across the curve: the height is what the model is charged.
- Move each control and watch which part of the curve it changes.
Code sample
import numpy as np
from impl import MDNLoss
from config import MDNLossConfig
loss = MDNLoss(MDNLossConfig())
rng = np.random.default_rng(0)
n, k, d = 4, 3, 2 # batch, mixture components, target dimensions
pi_logits = rng.normal(size=(n, k)) # the three heads of your network
mu = rng.normal(size=(n, k, d))
log_sigma = np.zeros((n, k, d))
target = rng.normal(size=(n, d))
print(loss.forward(pi_logits, mu, log_sigma, target)) # mean negative log-likelihood
g_logits, g_mu, g_log_sigma = loss.backward(pi_logits, mu, log_sigma, target)
prediction = loss.sample(pi_logits, mu, log_sigma, rng) # (4, 2), one draw per rowRead the implementation (100 lines)
"""Mixture density network loss: negative log-likelihood of the target under a mixture of K diagonal Gaussians whose
parameters the network outputs.
NumPy only. `forward` returns the loss, `backward` its gradients with respect to the mixing logits, the means and
the log standard deviations; `sample` and `mean` read predictions off the mixture.
"""
from __future__ import annotations
import math
import numpy as np
try:
from .config import MDNLossConfig
except ImportError: # run from the template's own folder
from config import MDNLossConfig
def _log_softmax(z: np.ndarray, axis: int = -1) -> np.ndarray:
"""log(softmax(z)) along `axis`, with the maximum subtracted first so exp cannot overflow."""
shifted = z - z.max(axis=axis, keepdims=True)
return shifted - np.log(np.exp(shifted).sum(axis=axis, keepdims=True))
def _logsumexp(x: np.ndarray, axis: int) -> np.ndarray:
"""log(sum(exp(x))) along `axis`, with the maximum taken out first so exp cannot overflow."""
top = x.max(axis=axis, keepdims=True)
return (top + np.log(np.exp(x - top).sum(axis=axis, keepdims=True))).squeeze(axis)
class MDNLoss:
"""-log sum_k pi_k N(y; mu_k, diag(sigma_k^2)), with pi = softmax(pi_logits) and sigma = exp(log_sigma)."""
def __init__(self, config: MDNLossConfig | None = None) -> None:
self.config = config or MDNLossConfig()
def _prepare(self, pi_logits, mu, log_sigma, target=None) -> tuple:
"""Checked float arrays: pi_logits (N, K), mu (N, K, D), clipped log_sigma (N, K, D), target (N, D).
Also returns the mask (N, K, D) of log_sigma entries inside the clip range, where its gradient flows.
"""
pi_logits, mu, log_sigma = (np.asarray(x, dtype=float) for x in (pi_logits, mu, log_sigma))
if pi_logits.ndim != 2 or mu.ndim != 3 or mu.shape[:2] != pi_logits.shape or log_sigma.shape != mu.shape:
raise ValueError(f"expected pi_logits (N, K), mu (N, K, D), log_sigma (N, K, D); got {pi_logits.shape}, "
f"{mu.shape}, {log_sigma.shape}")
inside = (log_sigma >= self.config.log_sigma_min) & (log_sigma <= self.config.log_sigma_max)
log_sigma = np.clip(log_sigma, self.config.log_sigma_min, self.config.log_sigma_max)
if target is not None:
target = np.asarray(target, dtype=float)
if target.shape != (mu.shape[0], mu.shape[2]):
raise ValueError(f"target must have shape (N, D) = {(mu.shape[0], mu.shape[2])}, got {target.shape}")
return pi_logits, mu, log_sigma, target, inside
def _joint(self, pi_logits, mu, log_sigma, target) -> tuple[np.ndarray, np.ndarray]:
"""log(pi_k * N(y; mu_k, sigma_k)) for every row and component (N, K), and the scaled error (N, K, D)."""
z = (target[:, None, :] - mu) / np.exp(log_sigma)
log_density = (-0.5 * z**2 - log_sigma - 0.5 * math.log(2.0 * math.pi)).sum(axis=2)
return _log_softmax(pi_logits, axis=1) + log_density, z
def forward(self, pi_logits, mu, log_sigma, target):
"""pi_logits: (N, K) mixing scores. mu: (N, K, D) component means. log_sigma: (N, K, D) log standard
deviations. target: (N, D). Returns a float, or (N,) for "none"."""
pi_logits, mu, log_sigma, target, _ = self._prepare(pi_logits, mu, log_sigma, target)
per_row = -_logsumexp(self._joint(pi_logits, mu, log_sigma, target)[0], axis=1)
if self.config.reduction == "none":
return per_row
return float(per_row.mean()) if self.config.reduction == "mean" else float(per_row.sum())
def backward(self, pi_logits, mu, log_sigma, target) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
"""Gradients of the reduced loss with respect to pi_logits (N, K), mu (N, K, D), log_sigma (N, K, D).
With r the responsibility of each component for the target (the posterior over components):
d/d pi_logits = pi - r, d/d mu = -r * z / sigma, d/d log_sigma = r * (1 - z^2), z = (y - mu) / sigma.
Clipped log_sigma entries get zero gradient. For "none" the per-row gradients are returned unscaled.
"""
pi_logits, mu, log_sigma, target, inside = self._prepare(pi_logits, mu, log_sigma, target)
joint, z = self._joint(pi_logits, mu, log_sigma, target)
resp = np.exp(joint - _logsumexp(joint, axis=1)[:, None])
g_logits = np.exp(_log_softmax(pi_logits, axis=1)) - resp
g_mu = -resp[:, :, None] * z / np.exp(log_sigma)
g_log_sigma = resp[:, :, None] * (1.0 - z**2) * inside
scale = 1.0 / pi_logits.shape[0] if self.config.reduction == "mean" else 1.0
return g_logits * scale, g_mu * scale, g_log_sigma * scale
def mean(self, pi_logits, mu, log_sigma) -> np.ndarray:
"""Mean of the mixture for every row: sum_k pi_k * mu_k. Returns (N, D)."""
pi_logits, mu, _, _, _ = self._prepare(pi_logits, mu, log_sigma)
return (np.exp(_log_softmax(pi_logits, axis=1))[:, :, None] * mu).sum(axis=1)
def sample(self, pi_logits, mu, log_sigma, rng: np.random.Generator) -> np.ndarray:
"""One draw from the mixture for every row: pick a component by pi, then draw from its Gaussian.
rng: a NumPy random generator, e.g. np.random.default_rng(0). Returns (N, D).
"""
pi_logits, mu, log_sigma, _, _ = self._prepare(pi_logits, mu, log_sigma)
cumulative = np.exp(_log_softmax(pi_logits, axis=1)).cumsum(axis=1)
picks = (rng.uniform(size=(len(mu), 1)) > cumulative).sum(axis=1).clip(max=mu.shape[1] - 1)
rows = np.arange(len(mu))
return mu[rows, picks] + np.exp(log_sigma[rows, picks]) * rng.normal(size=(len(mu), mu.shape[2]))
__call__ = forward- Repository
- Not published yet
- Needs
- Python 3.10 and NumPy
- Tests
- 8, run with
python3 -m unittest -v
Practice
Build MDNLoss(MDNLossConfig()) and reproduce the worked example with pi_logits of shape (1, 2), mu and log_sigma of shape (1, 2, 1) and target of shape (1, 1). Check forward and backward against the hand values. Then call mean and draw 1000 values with sample, and compare a histogram with the mean.
Check on learning
- A dataset has two valid outputs for each input, at and . What does a model trained with squared error predict, and what does a two-component mixture predict?
A way to think about it
Squared error is minimised by the average of the valid outputs. Ask whether that average is itself a valid output, then consider what two bumps can represent.
- Without the clip on the log standard deviation, why can the loss go to minus infinity on a finite dataset?
A way to think about it
Place one component's mean exactly on one training target and let its width shrink. Track that example's density, and check that the other examples are still covered by other components.
- The gradient for the mixing scores is . When does a component's weight stop changing?
A way to think about it
The gradient averages to zero when the weight equals the average responsibility over the data. Relate that to the share of the data the component explains.
- For a target exactly one standard deviation from a component's mean, the gradient on that component's width is zero. Why is that the balance point?
A way to think about it
Look at . A Gaussian's expected squared standardised error is 1, so a width is right when targets fall, on average, one standard deviation away.
- A component's weight has fallen to 0.0001. Why is it hard for training to bring it back?
A way to think about it
Its responsibility for any target is tiny, and all its gradients are scaled by that. Think about what would have to happen for it to win a target.