The scipy.stats package contains probability distributions, summary statistics, parameter fitting, statistical tests, and kernel density estimation. Check out scipy.stats tutorial for more examples.
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats
from scipy.optimize import minimize
rng = np.random.default_rng(37830)Distributions¶
SciPy provides over 100 continuous distributions and about 20 discrete ones (see the lists of continuous and discrete distributions). They are all objects with the same methods:
| method | returns |
|---|---|
pdf(x), pmf(x) | the probability density function (continuous) or probability mass function (discrete) |
logpdf(x), logpmf(x) | its logarithm |
cdf(x) | the cumulative distribution function (CDF) |
sf(x) | the survival function |
ppf(q) | the inverse of the CDF, or quantile function: the with |
isf(q) | the inverse of the survival function |
rvs(size, random_state) | random samples (“random variates”) |
mean(), var(), std(), median() | summary values |
interval(c) | an interval that contains with probability |
expect(f) | |
fit(data) | parameters fitted to data |
The normal distribution is stats.norm. To avoid confusion with a norm in linear algebra, we’ll import it as normal.
from scipy.stats import norm as normalThe normal distribution¶
The standard normal distribution with mean variance has probability density function (PDF)
The default is and .
print("support:", *normal.support())
print("mean and variance:", normal.mean(), normal.var())
x = np.linspace(-5, 5, 200)
fig, ax = plt.subplots(1, 2, figsize=(10, 3.5))
ax[0].plot(x, normal.pdf(x))
ax[0].set_title('normal PDF')
ax[1].plot(x, normal.cdf(x))
ax[1].set_title('normal CDF')
plt.show()The quantile function ppf answers questions such as “where is the 97.5th percentile?”. interval gives the same answer directly.
print(normal.ppf(0.975))
low, high = normal.interval(0.95)
print(low, high)Tail probabilities and logarithms¶
Use sf rather than 1 - cdf for probabilities far in the tail. The CDF rounds to 1 long before the tail probability gets too small to represent (see Bits, Bytes, and Numbers), so subtracting it from 1 gives 0:
for x0 in [3, 6, 10]:
print(f"P(X > {x0:2d}): 1 - cdf = {1 - normal.cdf(x0):.3e}, sf = {normal.sf(x0):.3e}")For the same reason, use logpdf when you need the logarithm of a density. The density at is about , which underflows to 0, while its logarithm is an ordinary number. This matters when we fit distributions below, which adds up the log-densities of many data points.
print(normal.pdf(40), normal.logpdf(40))Sampling¶
rvs draws samples. Pass a Generator as random_state to make the results reproducible. A histogram with density=True is scaled to have area 1, so it can be compared with the PDF.
X = normal.rvs(size=1000, random_state=rng)
x = np.linspace(-4, 4, 200)
plt.hist(X, bins=40, density=True, alpha=0.5, label='1000 samples')
plt.plot(x, normal.pdf(x), 'k', label='PDF')
plt.legend()
plt.show()Location and scale¶
Every continuous distribution takes loc and scale keyword arguments, which shift and stretch it. If has the standard distribution, then , with density
For the normal distribution, loc is the mean and scale is the standard deviation, not the variance.
X = normal.rvs(size=1000, loc=1.0, scale=0.5, random_state=rng)
x = np.linspace(-1, 3, 200)
plt.hist(X, bins=40, density=True, alpha=0.5, label='samples')
plt.plot(x, normal.pdf(x, loc=1.0, scale=0.5), 'k', label='PDF, loc = 1, scale = 0.5')
plt.legend()
plt.show()Frozen distributions¶
Instead of passing the parameters to every method, you can “freeze” a distribution by calling it with its parameters. The frozen distribution has the same methods.
dist = normal(loc=1.0, scale=0.5)
print(dist.mean(), dist.std())
print(dist.rvs(size=5, random_state=rng))Shape parameters¶
Many distributions have shape parameters in addition to loc and scale. The gamma distribution, for example, has a shape and density
where is scale. Its mean is and its variance is . Shape parameters come first, before loc and scale.
x = np.linspace(0, 6, 300)
for a in [1, 2, 5]:
plt.plot(x, stats.gamma.pdf(x, a, scale=0.5), label=f'$a = {a}$')
plt.legend()
plt.title('gamma PDFs with scale 0.5')
plt.show()
dist = stats.gamma(2.0, scale=0.5)
print(f"mean {dist.mean()}, variance {dist.var()}")Textbooks, NumPy, and SciPy often parameterize the same distribution differently, so check the definition in the documentation (help(stats.gamma)) before using a distribution. Three common cases:
stats.expon(scale=1/lam)is the exponential distribution with rate .stats.gamma(a, scale=1/b)is the gamma distribution with rate .stats.lognorm(s=sigma, scale=np.exp(mu))is the distribution of for , which NumPy samples withrng.lognormal(mu, sigma).
Example: the Laplace distribution¶
The Laplace distribution has density
and variance 2. Compared with the normal distribution with the same variance, it has a sharper peak and much heavier tails. The difference is clearest on a logarithmic scale.
from scipy.stats import laplace
print("Laplace mean and variance:", laplace.mean(), laplace.var())
x = np.linspace(-8, 8, 400)
fig, ax = plt.subplots(1, 2, figsize=(10, 3.5))
for a in ax:
a.plot(x, laplace.pdf(x), label='Laplace')
a.plot(x, normal.pdf(x, scale=np.sqrt(2)), label='normal, variance 2')
a.legend()
ax[0].set_title('PDFs')
ax[1].set_yscale('log')
ax[1].set_ylim(1e-8, 1)
ax[1].set_title('PDFs, logarithmic scale')
plt.show()Discrete distributions¶
Discrete distributions have the same methods, except that they have a probability mass function pmf instead of a PDF, and no scale argument. The Poisson distribution with mean describes the number of events in a fixed time when events happen independently at a constant rate, such as the number of radioactive decays in a second. It has
and its variance equals its mean.
from scipy.stats import poisson
dist = poisson(3.0)
print("support:", *dist.support())
print("mean and variance:", dist.mean(), dist.var())
k = np.arange(12)
X = dist.rvs(size=10_000, random_state=rng)
frequencies = np.bincount(X, minlength=k.size)[:k.size] / X.size
fig, ax = plt.subplots(1, 2, figsize=(10, 3.5))
ax[0].bar(k, frequencies, alpha=0.5, label='sample frequencies')
ax[0].plot(k, dist.pmf(k), 'ko', label='PMF')
ax[0].legend()
ax[0].set_title('Poisson PMF, mean 3')
xx = np.linspace(0, 11, 500)
ax[1].plot(xx, dist.cdf(xx))
ax[1].set_title('Poisson CDF')
plt.show()Expectations¶
expect computes for a function , by numerical integration with quad for continuous distributions and by summation for discrete ones.
print(normal.expect(lambda x: x**4)) # 3
print(laplace.expect(np.abs)) # E|X| = 1
print(poisson(3.0).expect(lambda k: k**2)) # variance + mean^2 = 12Monte Carlo Methods estimates the same kind of expectation from random samples instead, which is the better choice in high dimensions.
Summary statistics¶
NumPy computes the basic statistics of a sample, and scipy.stats adds a few more. Note that np.var and np.std divide by , unless you pass ddof=1 to divide by , which gives an unbiased estimate of the variance. stats.sem uses ddof=1.
X = stats.gamma.rvs(2.0, scale=0.5, size=1000, random_state=rng)
print(f"mean {np.mean(X):.4f}, median {np.median(X):.4f}")
print(f"variance with ddof=0: {np.var(X):.4f}, with ddof=1: {np.var(X, ddof=1):.4f}")
print(f"5th and 95th percentiles: {np.percentile(X, [5, 95])}")
print(f"skewness {stats.skew(X):.3f}, excess kurtosis {stats.kurtosis(X):.3f}")
print(f"standard error of the mean: {stats.sem(X):.4f}")The standard error of the mean, where is the sample standard deviation, estimates the typical distance between the sample mean and the true mean. It is the error bar of a Monte Carlo estimate.
Fitting distributions¶
Given data and a family of distributions with parameters , the maximum likelihood estimate of maximizes the log-likelihood
The fit method computes it. By default fit fits every parameter, including loc, which for the gamma distribution would shift the support away from . Fix a parameter by passing its value with an f in front of the name, such as floc=0.
a_fit, loc_fit, scale_fit = stats.gamma.fit(X, floc=0)
print(f"fitted a = {a_fit:.3f}, scale = {scale_fit:.3f} (true values 2 and 0.5)")
x = np.linspace(0, 5, 300)
plt.hist(X, bins=40, density=True, alpha=0.5, label='data')
plt.plot(x, stats.gamma.pdf(x, a_fit, scale=scale_fit), 'k', label='fitted gamma PDF')
plt.legend()
plt.show()For most distributions, fit maximizes the likelihood numerically. We can do the same by minimizing the negative log-likelihood with minimize. Note the use of logpdf: the product of 1000 densities could easily underflow.
def neg_log_likelihood(theta):
a, scale = theta
return -np.sum(stats.gamma.logpdf(X, a, scale=scale))
res = minimize(neg_log_likelihood, x0=[1.0, 1.0], bounds=[(1e-6, None), (1e-6, None)])
print(f"minimize: a = {res.x[0]:.3f}, scale = {res.x[1]:.3f}")For the normal distribution, the maximum likelihood estimates are the sample mean and the standard deviation with ddof=0:
Y = normal.rvs(loc=1.0, scale=0.5, size=100, random_state=rng)
loc_fit, scale_fit = normal.fit(Y)
print(f"fit: loc = {loc_fit:.4f}, scale = {scale_fit:.4f}")
print(f"mean = {np.mean(Y):.4f}, std = {np.std(Y):.4f}")Confidence intervals¶
A number computed from data is random, and should come with an error bar. For the mean of independent samples, the interval
contains the true mean with probability about 95%, where is the 97.5th percentile of Student’s distribution with degrees of freedom. For large it is close to the normal value 1.96.
n = len(X)
low, high = stats.t.interval(0.95, df=n - 1, loc=np.mean(X), scale=stats.sem(X))
print(f"mean {np.mean(X):.4f}, 95% confidence interval ({low:.4f}, {high:.4f}), true mean 1")For other statistics, such as the median, there is often no formula. The bootstrap estimates the uncertainty by recomputing the statistic on many data sets drawn with replacement from the data itself. stats.bootstrap does this; its first argument is a tuple of data arrays.
res = stats.bootstrap((X,), np.median, rng=rng)
ci = res.confidence_interval
print(f"median {np.median(X):.4f}, 95% confidence interval ({ci.low:.4f}, {ci.high:.4f})")
print(f"true median {stats.gamma.median(2.0, scale=0.5):.4f}")Hypothesis tests¶
A statistical test asks whether data are consistent with a null hypothesis, such as “the mean is 0” or “these samples come from a normal distribution”. It computes a test statistic and a p-value: the probability, if the null hypothesis is true, of a statistic at least as extreme as the one observed. A small p-value (0.05 is a common threshold) is evidence against the null hypothesis. A large one means only that the data are consistent with it, not that it is true.
The t-test¶
ttest_1samp tests whether the mean of a normally distributed sample equals a given value.
X0 = normal.rvs(size=50, random_state=rng) # true mean 0
X1 = normal.rvs(loc=0.5, size=50, random_state=rng) # true mean 0.5
print(f"true mean 0: p = {stats.ttest_1samp(X0, 0).pvalue:.4f}")
print(f"true mean 0.5: p = {stats.ttest_1samp(X1, 0).pvalue:.2e}")What does a p-value mean? If the null hypothesis is true, the p-value is uniformly distributed on , so a test at the 0.05 level wrongly rejects it 5% of the time. We check this by running 10,000 tests at once, since most tests take an axis argument, on samples whose mean really is 0, and 10,000 more on samples with mean 0.5.
null = stats.ttest_1samp(normal.rvs(size=(10_000, 50), random_state=rng), 0, axis=1).pvalue
alt = stats.ttest_1samp(normal.rvs(loc=0.5, size=(10_000, 50), random_state=rng), 0, axis=1).pvalue
fig, ax = plt.subplots(1, 2, figsize=(10, 3.5))
ax[0].hist(null, bins=20, range=(0, 1))
ax[0].set_title(f'true mean 0: {np.mean(null < 0.05):.1%} have $p < 0.05$')
ax[1].hist(alt, bins=20, range=(0, 1))
ax[1].set_title(f'true mean 0.5: {np.mean(alt < 0.05):.1%} have $p < 0.05$')
for a in ax:
a.set_xlabel('p-value')
plt.show()If you run many tests, some will have small p-values by chance alone. The fraction of tests that detect a real difference (the right panel) is the power of the test. It grows with the sample size and with the size of the difference, and with enough data even a difference too small to matter in practice gives a small p-value.
The Kolmogorov-Smirnov test¶
The Kolmogorov-Smirnov 2 sample test (ks_2samp) tests whether two samples come from the same distribution. Here the normal and Laplace samples have the same mean and variance, so a t-test can’t tell them apart, but the KS test sees the different shapes:
X0 = normal.rvs(size=2000, random_state=rng)
X1 = normal.rvs(size=2000, random_state=rng)
X2 = laplace.rvs(scale=1 / np.sqrt(2), size=2000, random_state=rng) # mean 0, variance 1
print(f"normal vs normal: p = {stats.ks_2samp(X0, X1).pvalue:.3f}")
print(f"normal vs Laplace: p = {stats.ks_2samp(X0, X2).pvalue:.2e}")Kernel density estimation¶
A histogram is a rough estimate of a density, and a kernel density estimate (KDE) is a smooth estimate. It places a narrow Gaussian at each data point and averages them:
where is the standard normal density and the width is the bandwidth. gaussian_kde returns an object that can be called like a function.
We try it on a mixture: half the samples come from the Laplace distribution centered at 0, and half from a normal distribution centered at 5.
X = np.concatenate([laplace.rvs(size=200, random_state=rng),
normal.rvs(loc=5, size=200, random_state=rng)])
true_pdf = lambda x: 0.5 * laplace.pdf(x) + 0.5 * normal.pdf(x, loc=5)
kde = stats.gaussian_kde(X)
x = np.linspace(-5,10,500)
y = kde(x)
plt.plot(x, y)
plt.title("KDE")
plt.figure(figsize=(8, 6))
plt.hist(X, bins=40, density=True, color='lightgray', label='histogram')
plt.plot(x, true_pdf(x), 'k--', label='true density')
for bw in [None, 0.2, 0.1]:
kde = stats.gaussian_kde(X, bw_method=bw)
h = kde.factor * np.std(X, ddof=1)
name = "default" if bw is None else f"bw_method = {bw}"
plt.plot(x, kde(x), label=f"KDE, {name}, $h = {h:.2f}$")
plt.legend()
plt.show()The bandwidth controls a trade-off. A large bandwidth smooths away real features, such as the sharp peak of the Laplace distribution, and a small one follows the noise in this particular sample. By default gaussian_kde uses , where is the standard deviation of the data, and a number passed as bw_method replaces the factor .