Sign in

MDN

Mixture Density Network negative log-likelihood

The loss of a mixture density network: the negative log-likelihood of the target under a mixture of Gaussians whose weights, means and widths the network outputs.

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

  1. The network outputs, for each example, KK mixing scores, KK means of dimension DD, and KK log standard deviations of dimension DD.
  2. Turn the scores into mixing weights with softmax, and clip the log standard deviations to the configured range.
  3. For each component compute the log of its weight plus the log-density of the target under its diagonal Gaussian.
  4. Combine the KK values with log-sum-exp and negate. That is the loss for the example.
  5. Reduce over the batch with reduction.
  6. In backward, compute each component's responsibility for the target and use it to scale that component's gradients.
  7. Use mean or sample to 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 sample or the strongest component, not mean, 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

IfUse instead
Each input has one plausible target valueMean squared error or Huber loss
The spread varies but there is only one modeA single Gaussian negative log-likelihood
The target is high dimensional, such as an imageA variational autoencoder trained with the ELBO

Math foundations

  1. The predicted density

    p(y∣x)=∑k=1Kπk(x)  N ⁣(y;  μk(x),  diag⁡(σk2(x)))p(y \mid x) = \sum_{k=1}^{K} \pi_k(x)\;\mathcal{N}\!\big(y;\; \mu_k(x),\; \operatorname{diag}(\sigma_k^{2}(x))\big)

    A weighted sum of KK Gaussians. The weights, means and standard deviations are all outputs of the network, so the shape of the distribution changes with the input.

  2. Keeping the parameters valid

    πk=eak∑jeaj,σkd=e skd\pi_k = \frac{e^{a_k}}{\sum_{j} e^{a_j}}, \qquad \sigma_{kd} = e^{\,s_{kd}}

    Softmax makes the weights positive and sum to 1. The exponential makes every standard deviation positive. The network outputs the unconstrained aa and ss.

  3. One Gaussian component in log form

    ln⁡N(y;μk,σk)=∑d=1D[−12zkd2−skd−12ln⁡2π],zkd=yd−μkdσkd\ln \mathcal{N}(y; \mu_k, \sigma_k) = \sum_{d=1}^{D}\Big[-\tfrac{1}{2} z_{kd}^{2} - s_{kd} - \tfrac{1}{2}\ln 2\pi\Big], \qquad z_{kd} = \frac{y_d - \mu_{kd}}{\sigma_{kd}}

    The standardised error zz says how many standard deviations the target is from the component's centre. A narrow component gains from −s-s only if the target is really close.

  4. The loss

    ℓ=−ln⁡∑k=1Kexp⁡ ⁣(ln⁡πk+ln⁡N(y;μk,σk))\ell = -\ln \sum_{k=1}^{K} \exp\!\big(\ln \pi_k + \ln \mathcal{N}(y; \mu_k, \sigma_k)\big)

    The negative log-likelihood, written as a log-sum-exp so that tiny densities do not underflow.

  5. Responsibilities

    rk=πk N(y;μk,σk)∑j=1Kπj N(y;μj,σj)r_k = \frac{\pi_k\,\mathcal{N}(y; \mu_k, \sigma_k)}{\sum_{j=1}^{K} \pi_j\,\mathcal{N}(y; \mu_j, \sigma_j)}

    The posterior probability that component kk produced the target. The responsibilities sum to 1 and decide how the gradient is shared.

  6. The gradients

    ∂ℓ∂ak=πk−rk,∂ℓ∂μkd=− rk zkdσkd,∂ℓ∂skd=rk (1−zkd2)\frac{\partial \ell}{\partial a_k} = \pi_k - r_k, \qquad \frac{\partial \ell}{\partial \mu_{kd}} = -\,r_k\,\frac{z_{kd}}{\sigma_{kd}}, \qquad \frac{\partial \ell}{\partial s_{kd}} = r_k\,\big(1 - z_{kd}^{2}\big)

    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

x,yx, y
the input and the target; the target has D dimensions
K,DK, D
the number of mixture components and the target dimension
πk\pi_k
mixing weight of component k
aka_k
mixing score of component k, pi_logits
μkd\mu_{kd}
mean of component k in dimension d, mu
σkd\sigma_{kd}
standard deviation of component k in dimension d
skds_{kd}
log standard deviation, log_sigma
zkdz_{kd}
the standardised error of the target under component k
N\mathcal{N}
the Gaussian density
rkr_k
responsibility of component k for the target
ℓ\ell
the loss for one example

Worked by hand

One dimension, two components with equal weights 0.5, means 0 and 4, both with σ=1\sigma = 1. The target is y=1y = 1. The standard normal density gives φ(1)=0.24197\varphi(1) = 0.24197 and φ(3)=0.00443\varphi(3) = 0.00443.

p(y)=0.5×0.24197+0.5×0.00443=0.12320p(y) = 0.5 \times 0.24197 + 0.5 \times 0.00443 = 0.12320
ℓ=−ln⁡0.12320=2.0939\ell = -\ln 0.12320 = 2.0939
r1=0.5×0.241970.12320=0.9820,r2=0.0180r_1 = \frac{0.5 \times 0.24197}{0.12320} = 0.9820, \qquad r_2 = 0.0180
∂ℓ∂μ1=−0.9820×1−01=−0.9820,∂ℓ∂a1=0.5−0.9820=−0.4820\frac{\partial \ell}{\partial \mu_1} = -0.9820 \times \frac{1 - 0}{1} = -0.9820, \qquad \frac{\partial \ell}{\partial a_1} = 0.5 - 0.9820 = -0.4820

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 row
Read 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

  1. A dataset has two valid outputs for each input, at +1+1 and −1-1. 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.

  2. 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.

  3. The gradient for the mixing scores is πk−rk\pi_k - r_k. 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.

  4. 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 1−z21 - z^{2}. A Gaussian's expected squared standardised error is 1, so a width is right when targets fall, on average, one standard deviation away.

  5. 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.