Probability distributions
| Problem | Work with a probability distribution as one object: evaluate its density or mass, distribution, survival and quantile functions; compute its moments; draw samples; and estimate its parameters from data by maximum likelihood |
| Devised by | Maximum likelihood: Ronald Fisher (1912, 1922). Extreme-value distributions: Fisher and Leonard Tippett (1928), Emil Gumbel (1958), Richard von Mises (1936) and Arthur Jenkinson (1955, GEV); skew-normal: Adelchi Azzalini (1985); Owen’s T: Donald Owen (1956); gamma MLE starting value: Thomas Minka (2002) |
| Accuracy | Densities, distribution functions, quantiles and moments agree with scipy.stats to or better for every distribution; maximum-likelihood fits to (exactly, where closed forms exist) |
| Cost | Closed forms: . Quantiles by inversion: 10–40 evaluations of the distribution function. Fits: for closed forms and score equations, a few thousand likelihood evaluations by Nelder-Mead |
| Read first | Descriptive statistics, Incomplete gamma and beta functions |
| API | ContinuousDistribution, DiscreteDistribution, Fit, and 25 distribution types such as Gamma, GeneralizedExtremeValue and NegativeBinomial |
Overview
Most statistical work involves a few named distributions and the same handful of questions about each: how likely is a value,
what is the probability below a threshold, which value has 95% of the probability below it, what are the mean and the spread,
and which parameters best describe a sample. scipy.stats answers them with one object per distribution and the same methods on
every object. This entry gives the library the same design:
- a trait
ContinuousDistributionwithpdf,logpdf,cdf,sf,ppf,isf,mean,variance,skewness,excess_kurtosis,median,interval,log_likelihoodandsample; and its counterpartDiscreteDistributionwithpmf; - 20 continuous distributions: normal, uniform, exponential, gamma, beta, chi-squared, Student’s t, F, log-normal, Weibull, Cauchy, Laplace, logistic, Pareto, Rayleigh, Gumbel, generalised extreme value, truncated normal, von Mises and skew-normal;
- 5 discrete ones: binomial, Poisson, geometric, negative binomial and hypergeometric;
- maximum-likelihood fitting for all of them except the truncated normal and the hypergeometric.
Where it is used
A probability distribution describes uncertainty in a quantity.
- Reliability and quality. Failure times modelled with Weibull or exponential distributions; defect counts with Poisson.
- Communications and noise. Gaussian noise, Rayleigh fading and Rician amplitudes.
- Risk analysis and simulation. Choosing input distributions for a Monte Carlo analysis, and reading off probabilities and quantiles.
- Fitting. Estimating a distribution’s parameters from data by maximum likelihood.
History
Most of these distributions arose in the eighteenth and nineteenth centuries: the binomial and normal with Jacob Bernoulli and Abraham de Moivre, the Poisson as a limit of the binomial (1837), and Student’s t with William Gosset (1908). Ronald Fisher introduced maximum likelihood between 1912 and 1922 and showed that, under regularity conditions, it is consistent, efficient and asymptotically normal with variance given by the inverse Fisher information. Distributions of extremes came from Fisher and Leonard Tippett (1928), who found the three possible limits of the maximum of many samples. Richard von Mises (1936) and Arthur Jenkinson (1955) united them as the generalised extreme value distribution, and Emil Gumbel’s Statistics of Extremes (1958) brought them into engineering use for floods and loads. Richard von Mises (1918) also gave the circular normal distribution. Adelchi Azzalini (1985) introduced the skew-normal, whose distribution function needs Donald Owen’s T function (1956).
The idea
Four views of one distribution
A continuous distribution is described equally by its density , its distribution function , its survival function , or its quantile function . Each is best for something:
- for likelihoods;
- and for probabilities of intervals and tails. Computing directly instead of as keeps its accuracy when , so every distribution here
evaluates the tail it is asked for, with
exp_m1,ln_1por the complementary special function; - for critical values and for sampling: if is uniform on , then has distribution (inversion).
Many distributions reduce to two special functions, the regularised incomplete gamma and beta . The gamma and chi-squared distribution functions are , and the Poisson’s is . The beta, Student’s t, F, binomial and negative binomial are all incomplete beta functions. Where the quantile has a closed form (normal, exponential, Weibull, Pareto, Gumbel, GEV, Laplace, logistic, Cauchy, Rayleigh, log-normal), it is used. Otherwise the distribution function is inverted by expanding a bracket from the mean and applying Brent’s method, which converges to machine precision in a few tens of evaluations.
Two less common distribution functions
The skew-normal density tilts the normal by a factor that rises from 0 to 2. Its distribution function is , where Owen’s T function
is computed by 40-point Gauss-Legendre quadrature for , and through the identity (for ) beyond.
The von Mises distribution lives on a circle. Its distribution function is a Fourier series,
whose Bessel-function ratios come from Miller’s backward recurrence . The series loses accuracy in the far tails for large , where SciPy switches to a normal approximation. Its relative error is about there.
Maximum likelihood
Given independent observations , the maximum-likelihood estimate maximises . For many distributions the maximum has a closed form or reduces to one equation:
| distribution | maximum-likelihood estimate |
|---|---|
| normal | , |
| exponential, Poisson, geometric | , , |
| log-normal | the normal estimates of |
| Laplace | median, mean absolute deviation from it |
| Pareto, Rayleigh | , ; |
| gamma | , then |
| beta | , |
| Weibull | , then |
| Gumbel | , then in closed form |
| von Mises | = mean direction; , the mean resultant length |
| negative binomial | for each , ; then from the profile score |
The one-dimensional equations are solved by Brent’s method or Newton’s method (the gamma shape from Minka’s starting value converges in 3–4 Newton steps), and the beta equations by Newton’s method in two dimensions with trigamma derivatives. The remaining distributions are fitted by Nelder-Mead on , with positive parameters on a log scale: Student’s t, F, Cauchy, logistic, GEV and skew-normal.
Maximum likelihood also chooses between models: of several fitted distributions, the one with the smallest Akaike information criterion (with parameters) is expected to predict new data best:
Figure 10.2. Fitted distributions.
Table 10.2. Log-likelihood and AIC of the four fits.
| model | parameters | log-likelihood | AIC |
|---|---|---|---|
| gamma | 2 | -686.5 | 1376.9 |
| Weibull | 2 | -687.6 | 1379.1 |
| log-normal | 2 | -703.8 | 1411.6 |
| exponential | 1 | -719.1 | 1440.1 |
The gamma model, which generated the data, has the lowest AIC. The Weibull is close behind, as it often is for skewed positive data. The log-normal, whose density vanishes too fast at zero, and the exponential, which has one parameter fewer, are clearly worse.
Algorithm
ppf(p) (when no closed form): start from the mean (or a point in the support) and double a step of one standard deviation outward
until brackets , then solve by Brent’s method to a relative tolerance of .
Discrete ppf(p): the smallest with , by doubling an upper bracket from and bisecting.
fit: the closed form or score equation from the table, or Nelder-Mead from moment estimates with tolerances of in the objective
and in the parameters.
sample: inversion, ppf(U) with uniform on .
Implementation
/// A generator by fast numerical inversion of a distribution (SciPy's `FastGeneratorInversion`):
/// polynomial inversion of the density of `dist` on its support (order 5, resolution 1e-12), with
/// `ppf`, `cdf`, `rvs` and `qrvs_sobol`. The centre, where the density is positive, is the median.
pub fn fast_generator_inversion<'a>(dist: &'a dyn ContinuousDistribution) -> Result<lib_jsl_random::sampling::FastGeneratorInversion<'a>, ErrorsJSL> {
let median = dist.ppf(0.5);
let (lo, hi) = dist.support();
let center = if median.is_finite() { median } else if lo.is_finite() && hi.is_finite() { 0.5 * (lo + hi) } else { dist.mean() };
lib_jsl_random::sampling::FastGeneratorInversion::new(move |x| dist.pdf(x), (lo, hi), center, 0.0, 1.0)
}
/// A continuous probability distribution on the real line.
pub trait ContinuousDistribution {
/// The probability density.
fn pdf(&self, x: f64) -> f64;
/// The log density (more accurate than `pdf(x).ln()` in the tails where overridden).
fn logpdf(&self, x: f64) -> f64 {
self.pdf(x).ln()
}
/// The distribution function `P(X ≤ x)`.
fn cdf(&self, x: f64) -> f64;
/// The survival function `P(X > x)`.
fn sf(&self, x: f64) -> f64 {
1.0 - self.cdf(x)
}
/// The quantile (percent-point) function, the inverse of the distribution function.
fn ppf(&self, p: f64) -> f64 {
let (lo, hi) = self.support();
let m = self.mean();
let guess = if m.is_finite() { m } else if lo.is_finite() { lo + 1.0 } else if hi.is_finite() { hi - 1.0 } else { 0.0 };
let s = self.std();
invert_cdf(|x| self.cdf(x), p, (lo, hi), guess, if s.is_finite() { s } else { 1.0 })
}
/// The inverse survival function.
fn isf(&self, q: f64) -> f64 {
self.ppf(1.0 - q)
}
/// The interval `[a, b]` outside which the density is zero.
fn support(&self) -> (f64, f64);
fn mean(&self) -> f64;
fn variance(&self) -> f64;
fn std(&self) -> f64 {
self.variance().sqrt()
}
fn skewness(&self) -> f64;
/// The excess kurtosis (zero for the normal distribution), as SciPy's `stats(moments='k')`.
fn excess_kurtosis(&self) -> f64;
fn median(&self) -> f64 {
self.ppf(0.5)
}
/// The central interval containing a fraction `confidence` of the probability.
fn interval(&self, confidence: f64) -> (f64, f64) {
let a = 0.5 * (1.0 - confidence);
(self.ppf(a), self.isf(a))
}
/// `Σ log f(xᵢ)`.
fn log_likelihood(&self, data: &[f64]) -> f64 {
data.iter().map(|&x| self.logpdf(x)).sum()
}
/// A sample by inversion, `ppf(U)`.
fn sample<U: UniformGenerator>(&self, rng: &mut U) -> f64
where
Self: Sized,
{
let mut u = rng.next_f64();
while u <= 0.0 || u >= 1.0 {
u = rng.next_f64();
}
self.ppf(u)
}
}
/// Maximum-likelihood estimation of a distribution's parameters (SciPy's `fit`, with the
/// location fixed where the distribution has no location parameter here).
pub trait Fit: Sized {
fn fit(data: &[f64]) -> Result<Self, ErrorsJSL>;
}
/// A discrete distribution on the integers.
pub trait DiscreteDistribution {
fn pmf(&self, k: i64) -> f64;
fn logpmf(&self, k: i64) -> f64 {
self.pmf(k).ln()
}
fn cdf(&self, k: i64) -> f64;
fn sf(&self, k: i64) -> f64 {
1.0 - self.cdf(k)
}
/// The smallest `k` with `cdf(k) ≥ p`.
fn ppf(&self, p: f64) -> i64 {
let (lo, hi) = self.support();
if p <= 0.0 {
return lo - 1;
}
// Find an upper bracket, then bisect.
let mut b = lo.max((self.mean() + 3.0 * self.variance().sqrt()).ceil() as i64);
let mut step = 1i64.max(self.variance().sqrt().ceil() as i64);
while b < hi && self.cdf(b) < p * (1.0 - 1e-15) {
b = b.saturating_add(step).min(hi);
step = step.saturating_mul(2);
}
let mut a = lo - 1;
while b - a > 1 {
let mid = a + (b - a) / 2;
if self.cdf(mid) >= p * (1.0 - 1e-15) { b = mid } else { a = mid }
}
b
}
fn support(&self) -> (i64, i64);
fn mean(&self) -> f64;
fn variance(&self) -> f64;
fn skewness(&self) -> f64;
fn excess_kurtosis(&self) -> f64;
fn log_likelihood(&self, data: &[i64]) -> f64 {
data.iter().map(|&k| self.logpmf(k)).sum()
}
fn sample<U: UniformGenerator>(&self, rng: &mut U) -> i64
where
Self: Sized,
{
self.ppf(rng.next_f64())
}
}
impl Fit for Gamma {
/// The shape solves `ln k − ψ(k) = ln x̄ − mean(ln x)` (Newton's method from Minka's
/// starting value), and `θ = x̄ / k`.
fn fit(data: &[f64]) -> Result<Self, ErrorsJSL> {
check_data(data, 2)?;
if data.iter().any(|&v| v <= 0.0) {
return Err(ErrorsJSL::InvalidInputRange("gamma data must be positive"));
}
let m = mean(data);
let s = m.ln() - data.iter().map(|v| v.ln()).sum::<f64>() / data.len() as f64;
let mut k = (3.0 - s + ((s - 3.0).powi(2) + 24.0 * s).sqrt()) / (12.0 * s);
for _ in 0..50 {
let f = k.ln() - digamma(k) - s;
let step = f / (1.0 / k - trigamma(k));
let next = (k - step).max(k / 10.0);
if (next - k).abs() <= 1e-15 * k {
k = next;
break;
}
k = next;
}
Gamma::new(k, m / k)
}
}
- Parameters are each distribution’s natural ones:
Gamma { shape, scale },Exponential { lambda }(a rate), andGeneralizedExtremeValue { xi, … }in the statistics convention, where SciPy’sgenextremeshape is . Each type’s documentation gives the SciPy equivalent. - Fits estimate the parameters each type has. Distributions without a location parameter here (gamma, Weibull, log-normal, Pareto,
Rayleigh, exponential) correspond to SciPy’s fits with
floc=0. sampleuses inversion for every distribution: simple and exact, though slower than the specialised samplers inlib_jsl_randomfor the gamma, beta and Poisson distributions.
In practice
Every distribution is compared with scipy.stats from SciPy 1.17.1 (references from
book/generator/data/make_distributions_refs.py). The density, distribution and survival functions are evaluated at four or five points
including the tails, the quantiles at , and the four moments. Each fit is to 400 samples, against SciPy’s maximum-likelihood
estimate polished by a tight Nelder-Mead search. All entries are relative differences:
Table 10.3. Distributions against SciPy.
| distribution | pdf / pmf | cdf and sf | ppf | mean, variance, skewness, kurtosis | maximum-likelihood fit |
|---|---|---|---|---|---|
Normal | 2e-16 | 5e-15 | 3e-15 | 0 | 2e-16 |
Uniform | 0 | 0 | 0 | 0 | |
Exponential | 2e-15 | 2e-15 | 2e-16 | 2e-16 | 0 |
Gamma | 2e-15 | 2e-15 | 2e-15 | 0 | 4e-9 |
Beta | 6e-16 | 1e-15 | 1e-15 | 0 | 1e-8 |
ChiSquared | 5e-16 | 8e-16 | 2e-16 | 0 | 7e-9 |
StudentT | 2e-15 | 3e-15 | 2e-15 | 0 | 7e-8 |
FDist | 3e-15 | 2e-15 | 8e-15 | 7e-16 | 2e-7 |
LogNormal | 7e-16 | 3e-15 | 5e-15 | 3e-16 | 2e-16 |
Weibull | 2e-16 | 0 | 0 | 1e-13 | 5e-9 |
Cauchy | 2e-16 | 6e-16 | 3e-14 | 0 | 5e-8 |
Laplace | 0 | 0 | 0 | 0 | 4e-16 |
Logistic | 2e-16 | 1e-16 | 0 | 0 | 3e-8 |
Pareto | 3e-16 | 2e-16 | 0 | 2e-16 | 3e-16 |
Rayleigh | 2e-16 | 2e-16 | 0 | 6e-16 | 5e-16 |
Gumbel | 1e-15 | 1e-16 | 0 | 2e-16 | 8e-9 |
GeneralizedExtremeValue, ξ > 0 | 3e-15 | 2e-16 | 2e-15 | 3e-14 | 6e-8 |
GeneralizedExtremeValue, ξ < 0 | 4e-16 | 1e-16 | 5e-16 | 3e-14 | |
TruncatedNormal | 5e-16 | 6e-15 | 2e-15 | 2e-15 | |
VonMises | 1e-15 | 7e-12 | 7e-13 | 6e-13 | 3e-9 |
SkewNormal | 4e-15 | 7e-8 | 3e-15 | 3e-16 | 7e-8 |
Binomial | 9e-15 | 7e-15 | 0 | 2e-16 | |
Poisson | 6e-15 | 5e-15 | 0 | 6e-17 | |
Geometric | 2e-16 | 1e-16 | 0 | 0 | |
NegativeBinomial | 1e-14 | 3e-15 | 0 | 1e-16 | 9e-8 |
Hypergeometric | 3e-14 | 3e-14 | 0 | 1e-16 |
The functions agree to rounding except in two places. The skew-normal distribution function at is , and the difference there is in absolute terms. The von Mises series agrees to in the tails. The fits agree to the tolerance of the optimisation, or exactly where closed forms exist.
Strengths
- One interface for 25 distributions, with accurate tails through direct survival functions and complementary special functions.
- Maximum-likelihood fits that are exact where possible, with score equations solved to machine precision.
- Every distribution’s quantile function, closed form or numerical, so inversion sampling and critical values work everywhere.
Weaknesses
- No multivariate distributions beyond the existing multivariate normal sampler: no Wishart, multivariate t or Dirichlet density.
- No fits with free location for distributions that do not have one here (SciPy’s three-parameter gamma or Weibull), and no fits for the truncated normal or the hypergeometric distribution. The binomial is fitted for a known .
- Fits return point estimates only. Standard errors need the observed information or the bootstrap.
Exercises
- Show that if is uniform on , then has distribution function . Use it to sample from the Weibull distribution in closed form.
- Derive the maximum-likelihood equations for the gamma distribution, and show that is decreasing, so the shape equation has exactly one solution.
- Show that the Student t distribution function is for .
- For the negative binomial, show that for fixed the likelihood is maximised at , and why the data must be over-dispersed () for a finite .
- Fit both the Gumbel and the GEV distribution to annual maxima of your choice, and use the likelihood-ratio statistic , approximately , to test .
Hints and answers
- . For the Weibull, .
- . Setting gives , and substituting into gives the equation. Its left side is decreasing because .
- Substitute in of the density: the tail beyond is .
- gives . As the negative binomial tends to the Poisson. If , the profile likelihood increases without bound in .
- The GEV contains the Gumbel as , so twice the gain in log-likelihood is asymptotically under the null hypothesis. Reject at 5% if it exceeds 3.84.
Further reading
- N. L. Johnson, S. Kotz and N. Balakrishnan, Continuous Univariate Distributions, vols. 1 and 2, 2nd ed., Wiley, 1994–95.
- N. L. Johnson, A. W. Kemp and S. Kotz, Univariate Discrete Distributions, 3rd ed., Wiley, 2005.
- S. Coles, An Introduction to Statistical Modeling of Extreme Values, Springer, 2001.
- A. Azzalini, “A class of distributions which includes the normal ones”, Scandinavian Journal of Statistics 12 (1985) 171–178.
- T. P. Minka, “Estimating a gamma distribution”, Microsoft Research technical note, 2002.
- Y. Pawitan, In All Likelihood: Statistical Modelling and Inference Using Likelihood, Oxford University Press, 2001.