Sign in

Probability distributions

Probability distributions and the exponential family

Six standard distributions (Gaussian, Bernoulli, Poisson, exponential, Beta, Dirichlet) and the single exponential-family form they all share.

Overview

A probability distribution is a rule for how probability is spread over the values a quantity can take. A handful of rules cover most modelling needs, and each answers a different kind of question. Bernoulli: did it happen? Poisson: how many times? Exponential: how long until the next one? Gaussian: where does a sum of many small effects land? Beta and Dirichlet: what is the unknown proportion, or set of proportions? They look unrelated, but all six can be written in one template, the exponential family, which is why the same algorithms work for all of them.

A short history

The standard distributions were found one problem at a time. Abraham de Moivre derived the normal curve in 1733 and Carl Friedrich Gauss used it for measurement errors in 1809. Jacob Bernoulli studied yes or no trials, and Simeon Denis Poisson published his law for rare events in 1837. In the 1930s Georges Darmois, Bernard Koopman and E. J. G. Pitman showed that these share one form, the exponential family.

How it works

  1. Decide what kind of quantity you have: a yes or no, a count, a waiting time, a real number, a proportion, or a vector of proportions.
  2. Pick the matching distribution and set its parameters. Each parameter has a direct meaning, such as a mean, a rate or a pseudo-count.
  3. Evaluate the log density (or log mass for discrete values) to score how plausible an observation is. Outside the support it is minus infinity.
  4. Read the mean and variance from the parameters, or draw samples.
  5. Rewrite the distribution in exponential-family form: natural parameters η\eta, sufficient statistics T(x)T(x), a log partition function A(η)A(\eta) and a base measure h(x)h(x).
  6. Use the derivative of AA to get the mean of the sufficient statistics without doing any integral.

Watch out for

  • A density is not a probability and can exceed 1. A Gaussian with standard deviation 0.1 has density about 4 at its mean. Only areas under the curve are probabilities.
  • The exponential and Gamma families are written with either a rate or a scale (one over the rate). Mixing the two conventions between libraries gives silently wrong results.
  • The Poisson forces the variance to equal the mean. Real count data are often more spread out than that, and a Poisson fit then understates uncertainty.
  • The split into base measure and sufficient statistics is not unique. This template writes the Beta with natural parameters (a,b)(a, b) and base measure 1/(x(1−x))1/(x(1-x)), while other texts use (a−1,b−1)(a-1, b-1).
  • Beta and Dirichlet densities are undefined at exactly 0 and 1. Data containing those values need clipping or a different model.

Use cases

When to use it

Choosing a noise model or an output layer for a problem, writing a likelihood, picking a prior, and understanding why generalized linear models and conjugate updates have the form they do.

In industry

Telecommunications and operations
Arrivals of calls or requests per interval are modelled as Poisson, and the gaps between them as exponential, to size capacity.
Insurance
Generalised linear models with Poisson claim counts are a standard way to set motor and home insurance rates.
Online experimentation
Click and conversion rates are modelled as Bernoulli outcomes with a Beta distribution over the unknown rate.
Text analysis
Topic models such as latent Dirichlet allocation place Dirichlet priors on the mix of topics per document.

Choosing it: what must hold

  • Knowledge of the data type: binary, a count, a positive duration, a proportion, or an unbounded real number.
  • A family whose support matches the data, for example Poisson for counts and Beta for values between 0 and 1.
  • A check of the fit against the data, for example with a histogram or a quantile plot.

When to choose something else

IfUse instead
No standard family fits, for example the data have several peaksA mixture model, or a nonparametric estimate such as a histogram or kernel density
Counts vary more than a Poisson allowsA negative binomial distribution
The data have heavier tails than a GaussianA Student t distribution, or transform the data first

Math foundations

  1. Gaussian

    p(x)=1σ2πexp⁡ ⁣(−(x−μ)22σ2)p(x) = \frac{1}{\sigma\sqrt{2\pi}} \exp\!\left(-\frac{(x - \mu)^{2}}{2\sigma^{2}}\right)

    A bell curve for real numbers with mean μ\mu and variance σ2\sigma^{2}. The log density is a negative squared distance from the mean, which is where squared-error losses come from.

  2. Bernoulli and Poisson

    P(x)=px(1−p)1−x,  x∈{0,1};P(k)=λke−λk!,  k=0,1,2,…P(x) = p^{x}(1 - p)^{1 - x},\ \ x \in \{0, 1\}; \qquad P(k) = \frac{\lambda^{k} e^{-\lambda}}{k!},\ \ k = 0, 1, 2, \dots

    Bernoulli is one trial with success probability pp, mean pp and variance p(1−p)p(1-p). Poisson counts events that occur independently at average rate λ\lambda, and its mean and variance are both λ\lambda.

  3. Exponential

    p(x)=λe−λx,x≥0p(x) = \lambda e^{-\lambda x}, \qquad x \ge 0

    The waiting time until the next event when events arrive at rate λ\lambda. The mean is 1/λ1/\lambda and the variance is 1/λ21/\lambda^{2}.

  4. Beta

    p(x)=Γ(a+b)Γ(a) Γ(b) xa−1(1−x)b−1,0<x<1p(x) = \frac{\Gamma(a + b)}{\Gamma(a)\,\Gamma(b)}\, x^{a - 1}(1 - x)^{b - 1}, \qquad 0 < x < 1

    A distribution over a proportion. Its mean is a/(a+b)a/(a+b), and larger a+ba + b means a narrower peak. It is the conjugate prior for the Bernoulli probability.

  5. Dirichlet

    p(x1,…,xK)=Γ ⁣(∑iαi)∏iΓ(αi)∏i=1Kxiαi−1,xi>0,  ∑ixi=1p(x_1, \dots, x_K) = \frac{\Gamma\!\left(\sum_{i} \alpha_i\right)}{\prod_{i} \Gamma(\alpha_i)} \prod_{i=1}^{K} x_i^{\alpha_i - 1}, \qquad x_i > 0,\ \ \sum_{i} x_i = 1

    The Beta extended to KK proportions that sum to 1. The mean of xix_i is αi/∑jαj\alpha_i / \sum_j \alpha_j. It is the usual prior over the probabilities of a categorical variable.

  6. The exponential family

    p(x∣η)=h(x) exp⁡ ⁣(η⊤T(x)−A(η))p(x \mid \eta) = h(x)\,\exp\!\big(\eta^{\top} T(x) - A(\eta)\big)

    All six distributions fit this form. T(x)T(x) is everything the data contribute, η\eta is the parameter in its most convenient coordinates, and A(η)A(\eta) makes the total probability 1. The template computes every log density this way.

  7. What the log partition function gives

    ∇ηA(η)=E[T(x)]\nabla_{\eta} A(\eta) = \mathbb{E}\big[T(x)\big]

    Differentiating AA gives the mean of the sufficient statistics, and the second derivative gives their variance. For the Bernoulli, A(η)=log⁡(1+eη)A(\eta) = \log(1 + e^{\eta}) and its derivative is the sigmoid function.

Symbols

xx
a value of the random quantity
μ, σ\mu,\ \sigma
the Gaussian mean and standard deviation
pp
the Bernoulli success probability
λ\lambda
the rate of the Poisson or exponential distribution
kk
a count: a non-negative whole number
a, ba,\ b
the Beta shape parameters
αi\alpha_i
the Dirichlet concentration for component ii
KK
the number of components of a Dirichlet vector
Γ\Gamma
the gamma function, which extends the factorial: Γ(n)=(n−1)!\Gamma(n) = (n-1)!
η\eta
the natural parameters
T(x)T(x)
the sufficient statistics
A(η)A(\eta)
the log partition function
h(x)h(x)
the base measure

Worked by hand

Write a Bernoulli with p=0.8p = 0.8 in exponential-family form. Its sufficient statistic is T(x)=xT(x) = x, its base measure is 1, and its natural parameter is the log odds.

η=ln⁡0.80.2=ln⁡4≈1.386\eta = \ln\frac{0.8}{0.2} = \ln 4 \approx 1.386
A(η)=ln⁡ ⁣(1+eη)=ln⁡5≈1.609A(\eta) = \ln\!\big(1 + e^{\eta}\big) = \ln 5 \approx 1.609
ln⁡P(1)=η×1−A(η)=1.386−1.609=−0.223=ln⁡0.8\ln P(1) = \eta \times 1 - A(\eta) = 1.386 - 1.609 = -0.223 = \ln 0.8
ln⁡P(0)=η×0−A(η)=−1.609=ln⁡0.2\ln P(0) = \eta \times 0 - A(\eta) = -1.609 = \ln 0.2
dAdη=eη1+eη=45=0.8\frac{dA}{d\eta} = \frac{e^{\eta}}{1 + e^{\eta}} = \frac{4}{5} = 0.8

The exponential-family pieces reproduce both probabilities, and the derivative of the log partition function returns the mean 0.8. That derivative is the sigmoid, which is why logistic regression models the log odds.

Visual example

Loading the example.

Try this

  • Choose Bernoulli with p = 0.8: η is ln 4, A is ln 5 and the slope of A is 0.8, as in the worked example.
  • Choose Poisson and raise λ. The mean and the variance stay equal.
  • Choose Beta and set both shapes below 1, then both above 1.

Code sample

import numpy as np
from impl import Gaussian, Poisson, Dirichlet, make_distribution
from config import ProbabilityDistributionsConfig

Gaussian(0.0, 1.0).prob(0.0)                 # 0.3989
Poisson(3.0).prob(2)                         # 0.2240
Dirichlet([1.0, 1.0, 1.0]).prob([0.2, 0.3, 0.5])   # 2.0, uniform over the simplex

beta = make_distribution(ProbabilityDistributionsConfig(distribution="beta", params=(2.0, 5.0)))
draws = beta.sample(1000)                    # (1000,), mean near 2/7
Read the implementation (301 lines)
"""Common probability distributions and their exponential-family form.

Gaussian, Bernoulli, Poisson, Exponential, Beta and Dirichlet. Each class gives the log density (or log mass),
mean, variance and sampling, and also its exponential-family pieces, so that

    log p(x) = eta . T(x) - A(eta) + log h(x)

with natural parameters eta, sufficient statistics T(x), log partition A and base measure h.
"""
from __future__ import annotations

import math

import numpy as np

try:
    from .config import ProbabilityDistributionsConfig
except ImportError:  # run from the template's own folder
    from config import ProbabilityDistributionsConfig

_lgamma = np.vectorize(math.lgamma, otypes=[float])


class _Distribution:
    """Shared behaviour. Subclasses define the exponential-family pieces and the moments."""

    seed = 0

    def log_prob(self, x) -> np.ndarray:
        """Log density or log mass at x, computed as eta . T(x) - A(eta) + log h(x). -inf outside the support."""
        x = np.asarray(x, dtype=float)
        inside = self.in_support(x)
        safe = np.where(self._expand(inside, x), x, self.safe_point())
        value = self.sufficient_statistics(safe) @ self.natural_parameters() - self.log_partition() + self.log_base_measure(safe)
        return np.where(inside, value, -np.inf)

    def prob(self, x) -> np.ndarray:
        """Density or mass at x."""
        return np.exp(self.log_prob(x))

    def log_partition(self, eta=None) -> float:
        """A(eta). Uses this distribution's own natural parameters when eta is None."""
        return float(self._log_partition(self.natural_parameters() if eta is None else np.asarray(eta, dtype=float)))

    def sample(self, n: int, rng: np.random.Generator | None = None) -> np.ndarray:
        """n independent draws, array (n,) (or (n, k) for the Dirichlet)."""
        return self._sample(n, rng or np.random.default_rng(self.seed))

    @staticmethod
    def _expand(inside, x):
        return inside

    def log_base_measure(self, x) -> np.ndarray:
        return np.zeros(np.shape(x))


class Gaussian(_Distribution):
    """Normal distribution with mean `mean` and standard deviation `std`. Support: all reals."""

    def __init__(self, mean: float = 0.0, std: float = 1.0) -> None:
        if std <= 0:
            raise ValueError("std must be positive")
        self.mean_, self.std = float(mean), float(std)

    def natural_parameters(self) -> np.ndarray:
        return np.array([self.mean_ / self.std**2, -0.5 / self.std**2])

    def sufficient_statistics(self, x) -> np.ndarray:
        x = np.asarray(x, dtype=float)
        return np.stack([x, x**2], axis=-1)

    @staticmethod
    def _log_partition(eta) -> float:
        return -eta[0] ** 2 / (4 * eta[1]) - 0.5 * math.log(-2 * eta[1])

    def log_base_measure(self, x) -> np.ndarray:
        return np.full(np.shape(x), -0.5 * math.log(2 * math.pi))

    def in_support(self, x) -> np.ndarray:
        return np.isfinite(x)

    def safe_point(self) -> float:
        return self.mean_

    def mean(self) -> float:
        return self.mean_

    def variance(self) -> float:
        return self.std**2

    def cdf(self, x) -> np.ndarray:
        z = (np.asarray(x, dtype=float) - self.mean_) / (self.std * math.sqrt(2.0))
        return 0.5 * (1.0 + np.vectorize(math.erf, otypes=[float])(z))

    def _sample(self, n, rng):
        return rng.normal(self.mean_, self.std, size=n)


class Bernoulli(_Distribution):
    """One trial that is 1 with probability p and 0 otherwise, 0 < p < 1."""

    def __init__(self, p: float = 0.5) -> None:
        if not 0 < p < 1:
            raise ValueError("p must lie strictly between 0 and 1")
        self.p = float(p)

    def natural_parameters(self) -> np.ndarray:
        return np.array([math.log(self.p / (1 - self.p))])  # the logit

    def sufficient_statistics(self, x) -> np.ndarray:
        return np.asarray(x, dtype=float)[..., None]

    @staticmethod
    def _log_partition(eta) -> float:
        return float(np.logaddexp(0.0, eta[0]))

    def in_support(self, x) -> np.ndarray:
        return (x == 0) | (x == 1)

    def safe_point(self) -> float:
        return 0.0

    def mean(self) -> float:
        return self.p

    def variance(self) -> float:
        return self.p * (1 - self.p)

    def _sample(self, n, rng):
        return (rng.random(n) < self.p).astype(float)


class Poisson(_Distribution):
    """Count of events at average rate `rate` > 0. Support: 0, 1, 2, ..."""

    def __init__(self, rate: float = 1.0) -> None:
        if rate <= 0:
            raise ValueError("rate must be positive")
        self.rate = float(rate)

    def natural_parameters(self) -> np.ndarray:
        return np.array([math.log(self.rate)])

    def sufficient_statistics(self, x) -> np.ndarray:
        return np.asarray(x, dtype=float)[..., None]

    @staticmethod
    def _log_partition(eta) -> float:
        return math.exp(eta[0])

    def log_base_measure(self, x) -> np.ndarray:
        return -_lgamma(np.asarray(x, dtype=float) + 1.0)

    def in_support(self, x) -> np.ndarray:
        return (x >= 0) & (x == np.round(x))

    def safe_point(self) -> float:
        return 0.0

    def mean(self) -> float:
        return self.rate

    def variance(self) -> float:
        return self.rate

    def _sample(self, n, rng):
        return rng.poisson(self.rate, size=n).astype(float)


class Exponential(_Distribution):
    """Waiting time with rate `rate` > 0 (mean 1 / rate). Support: x >= 0."""

    def __init__(self, rate: float = 1.0) -> None:
        if rate <= 0:
            raise ValueError("rate must be positive")
        self.rate = float(rate)

    def natural_parameters(self) -> np.ndarray:
        return np.array([-self.rate])

    def sufficient_statistics(self, x) -> np.ndarray:
        return np.asarray(x, dtype=float)[..., None]

    @staticmethod
    def _log_partition(eta) -> float:
        return -math.log(-eta[0])

    def in_support(self, x) -> np.ndarray:
        return x >= 0

    def safe_point(self) -> float:
        return 0.0

    def mean(self) -> float:
        return 1.0 / self.rate

    def variance(self) -> float:
        return 1.0 / self.rate**2

    def cdf(self, x) -> np.ndarray:
        return 1.0 - np.exp(-self.rate * np.clip(np.asarray(x, dtype=float), 0.0, None))

    def _sample(self, n, rng):
        return rng.exponential(1.0 / self.rate, size=n)


class Beta(_Distribution):
    """Distribution of a proportion with shape parameters a, b > 0. Support: 0 < x < 1."""

    def __init__(self, a: float = 1.0, b: float = 1.0) -> None:
        if a <= 0 or b <= 0:
            raise ValueError("a and b must be positive")
        self.a, self.b = float(a), float(b)

    def natural_parameters(self) -> np.ndarray:
        return np.array([self.a, self.b])

    def sufficient_statistics(self, x) -> np.ndarray:
        x = np.asarray(x, dtype=float)
        return np.stack([np.log(x), np.log1p(-x)], axis=-1)

    @staticmethod
    def _log_partition(eta) -> float:
        return math.lgamma(eta[0]) + math.lgamma(eta[1]) - math.lgamma(eta[0] + eta[1])

    def log_base_measure(self, x) -> np.ndarray:
        x = np.asarray(x, dtype=float)
        return -np.log(x) - np.log1p(-x)

    def in_support(self, x) -> np.ndarray:
        return (x > 0) & (x < 1)

    def safe_point(self) -> float:
        return 0.5

    def mean(self) -> float:
        return self.a / (self.a + self.b)

    def variance(self) -> float:
        s = self.a + self.b
        return self.a * self.b / (s * s * (s + 1))

    def _sample(self, n, rng):
        return rng.beta(self.a, self.b, size=n)


class Dirichlet(_Distribution):
    """Distribution over probability vectors of length k, with concentrations alpha_i > 0.

    Points x have shape (..., k), positive entries summing to 1. `mean` and `variance` return arrays (k,).
    """

    def __init__(self, alpha) -> None:
        alpha = np.asarray(alpha, dtype=float)
        if alpha.ndim != 1 or alpha.size < 2 or np.any(alpha <= 0):
            raise ValueError("alpha must be a 1-D array of at least two positive numbers")
        self.alpha = alpha

    def natural_parameters(self) -> np.ndarray:
        return self.alpha.copy()

    def sufficient_statistics(self, x) -> np.ndarray:
        return np.log(np.asarray(x, dtype=float))

    @staticmethod
    def _log_partition(eta) -> float:
        return float(sum(math.lgamma(a) for a in eta) - math.lgamma(float(np.sum(eta))))

    def log_base_measure(self, x) -> np.ndarray:
        return -np.log(np.asarray(x, dtype=float)).sum(axis=-1)

    def in_support(self, x) -> np.ndarray:
        return np.all(x > 0, axis=-1) & (np.abs(x.sum(axis=-1) - 1.0) < 1e-9)

    @staticmethod
    def _expand(inside, x):
        return inside[..., None]

    def safe_point(self) -> np.ndarray:
        return np.full(self.alpha.size, 1.0 / self.alpha.size)

    def mean(self) -> np.ndarray:
        return self.alpha / self.alpha.sum()

    def variance(self) -> np.ndarray:
        s = self.alpha.sum()
        m = self.alpha / s
        return m * (1 - m) / (s + 1)

    def _sample(self, n, rng):
        return rng.dirichlet(self.alpha, size=n)


def make_distribution(config: ProbabilityDistributionsConfig | None = None):
    """Build the distribution named by the config, with `config.params` as its parameters."""
    config = config or ProbabilityDistributionsConfig()
    classes = {"gaussian": Gaussian, "bernoulli": Bernoulli, "poisson": Poisson,
               "exponential": Exponential, "beta": Beta}
    dist = Dirichlet(config.params) if config.distribution == "dirichlet" else classes[config.distribution](*config.params)
    dist.seed = config.seed
    return dist
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
8, run with python3 -m unittest -v

Practice

Build Poisson(3.0), or use make_distribution with ProbabilityDistributionsConfig(distribution="poisson", params=(3.0,)). Print natural_parameters, sufficient_statistics(2), log_partition and log_prob(2), and check log_prob against the Poisson formula by hand. Then estimate the derivative of log_partition(eta) with a small finite difference around the natural parameter and compare it with mean().

Check on learning

  1. Counts of support tickets per hour have mean 4 and variance 15. Why is a Poisson model a poor fit, and what would it get wrong?
    A way to think about it

    Compare the variance the Poisson implies with the one observed. Then think about how often the model would call a busy hour nearly impossible.

  2. Beta(1, 1), Beta(10, 10) and Beta(0.5, 0.5) all have mean 0.5. How do their shapes differ, and what belief does each express?
    A way to think about it

    Look at the exponents a−1a - 1 and b−1b - 1: zero, positive or negative. Sketch what xa−1(1−x)b−1x^{a-1}(1-x)^{b-1} does near 0 and 1 in each case.

  3. The Gaussian has sufficient statistics xx and x2x^{2}. What does that say about what you need to keep from a data set to fit it?
    A way to think about it

    Sum the log density over the data and see which sums of the observations appear. Everything else about the data drops out.

  4. Why is it possible for a density to be 4 while probabilities never exceed 1?
    A way to think about it

    A probability is density times width. Check the area of a tall, narrow rectangle that is 4 high and 0.25 wide.

  5. For the Poisson, A(η)=eηA(\eta) = e^{\eta} with η=ln⁡λ\eta = \ln \lambda. Use the derivative rule to find the mean and the variance without summing a series.
    A way to think about it

    Differentiate once for the mean and twice for the variance, then substitute η=ln⁡λ\eta = \ln \lambda. Compare with the known answers.