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
- 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.
- Pick the matching distribution and set its parameters. Each parameter has a direct meaning, such as a mean, a rate or a pseudo-count.
- Evaluate the log density (or log mass for discrete values) to score how plausible an observation is. Outside the support it is minus infinity.
- Read the mean and variance from the parameters, or draw samples.
- Rewrite the distribution in exponential-family form: natural parameters , sufficient statistics , a log partition function and a base measure .
- Use the derivative of 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 and base measure , while other texts use .
- 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
| If | Use instead |
|---|---|
| No standard family fits, for example the data have several peaks | A mixture model, or a nonparametric estimate such as a histogram or kernel density |
| Counts vary more than a Poisson allows | A negative binomial distribution |
| The data have heavier tails than a Gaussian | A Student t distribution, or transform the data first |
Math foundations
Gaussian
A bell curve for real numbers with mean and variance . The log density is a negative squared distance from the mean, which is where squared-error losses come from.
Bernoulli and Poisson
Bernoulli is one trial with success probability , mean and variance . Poisson counts events that occur independently at average rate , and its mean and variance are both .
Exponential
The waiting time until the next event when events arrive at rate . The mean is and the variance is .
Beta
A distribution over a proportion. Its mean is , and larger means a narrower peak. It is the conjugate prior for the Bernoulli probability.
Dirichlet
The Beta extended to proportions that sum to 1. The mean of is . It is the usual prior over the probabilities of a categorical variable.
The exponential family
All six distributions fit this form. is everything the data contribute, is the parameter in its most convenient coordinates, and makes the total probability 1. The template computes every log density this way.
What the log partition function gives
Differentiating gives the mean of the sufficient statistics, and the second derivative gives their variance. For the Bernoulli, and its derivative is the sigmoid function.
Symbols
- a value of the random quantity
- the Gaussian mean and standard deviation
- the Bernoulli success probability
- the rate of the Poisson or exponential distribution
- a count: a non-negative whole number
- the Beta shape parameters
- the Dirichlet concentration for component
- the number of components of a Dirichlet vector
- the gamma function, which extends the factorial:
- the natural parameters
- the sufficient statistics
- the log partition function
- the base measure
Worked by hand
Write a Bernoulli with in exponential-family form. Its sufficient statistic is , its base measure is 1, and its natural parameter is the log odds.
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/7Read 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
- 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.
- 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 and : zero, positive or negative. Sketch what does near 0 and 1 in each case.
- The Gaussian has sufficient statistics and . 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.
- 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.
- For the Poisson, with . 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 . Compare with the known answers.