Statistical modeling with Python · Lesson 3 of 16

Probability distributions with scipy.stats

Use the normal, binomial and Poisson distributions in scipy.stats: pdf and pmf, cdf for 'at most', sf for 'more than', and ppf for cut-offs.

About 15 minutes · code runs in your browser, nothing to install

A probability distribution says how likely each value is. Statistical models are built on them: linear regression usually assumes normally distributed errors, logistic regression a binomial one, count models a Poisson one. scipy.stats has them all, and every distribution has the same few methods.

  • pmf(k): probability of exactly k (for counts: probability mass function).
  • pdf(x): height of the curve at x (for measurements: probability density function). It is not a probability by itself.
  • cdf(x): probability of a value at most x (cumulative distribution function).
  • sf(x): probability of a value more than x (survival function, 1 − cdf).
  • ppf(q): the value with a share q below it, the inverse of cdf. ppf(0.95) is the 95th percentile.

The normal distribution

Heights, measurement errors and averages of many things follow the bell-shaped normal curve. It has two settings: the mean (loc) and the standard deviation (scale). Say adult heights in a town have mean 170 cm and standard deviation 8 cm.

Pythoneditable
from scipy import stats

height = stats.norm(loc=170, scale=8)
print(f"P(shorter than 180): {height.cdf(180):.4f}")
print(f"P(taller than 185):  {height.sf(185):.4f}")
print(f"P(between 160 and 180): {height.cdf(180) - height.cdf(160):.4f}")
print(f"95th percentile: {height.ppf(0.95):.1f} cm")
Output
P(shorter than 180): 0.8944
P(taller than 185):  0.0304
P(between 160 and 180): 0.7887
95th percentile: 183.2 cm

stats.norm(loc, scale) makes a 'frozen' distribution you can ask many questions.

How to read it: about 89% of people are shorter than 180 cm, and only 3% are taller than 185 cm. The 95th percentile, 183.2 cm, is the height that 95% of people stay below.

The famous rule of thumb: about 68% of values lie within 1 standard deviation of the mean, 95% within 1.96, and 99.7% within 3. You can check it with the standard normal (mean 0, sd 1), the one behind the z-scores of the next lessons.

Pythoneditable
from scipy import stats

z = stats.norm()  # mean 0, standard deviation 1
for k in [1, 1.96, 3]:
    inside = z.cdf(k) - z.cdf(-k)
    print(f"within {k} sd: {inside:.3f}")
print(f"z for 97.5%: {z.ppf(0.975):.3f}")
Output
within 1 sd: 0.683
within 1.96 sd: 0.950
within 3 sd: 0.997
z for 97.5%: 1.960
Pythoneditable
import numpy as np
import matplotlib.pyplot as plt
from scipy import stats

x = np.linspace(140, 200, 300)
y = stats.norm.pdf(x, loc=170, scale=8)
print(f"Share between 160 and 180: {stats.norm.cdf(180, 170, 8) - stats.norm.cdf(160, 170, 8):.3f}")

plt.plot(x, y, color="navy")
band = (x >= 160) & (x <= 180)
plt.fill_between(x[band], y[band], color="skyblue")
plt.title("Heights: normal curve, mean 170, sd 8")
plt.xlabel("Height (cm)")
plt.show()
Output
Share between 160 and 180: 0.789
Chart drawn by this code

The shaded area is the probability: the area under a pdf curve, not its height.

The binomial distribution: counting successes

Each of 20 visitors to a shop buys something with probability 0.3, independently. The number of buyers follows a binomial distribution with n=20 tries and success chance p=0.3. It is the distribution behind logistic regression.

Pythoneditable
from scipy import stats

buyers = stats.binom(n=20, p=0.3)
print(f"P(exactly 6 buy): {buyers.pmf(6):.4f}")
print(f"P(at most 3 buy): {buyers.cdf(3):.4f}")
print(f"P(more than 9):   {buyers.sf(9):.4f}")
print("expected buyers:", buyers.mean())
Output
P(exactly 6 buy): 0.1916
P(at most 3 buy): 0.1071
P(more than 9):   0.0480
expected buyers: 6.0

The Poisson distribution: counts per period

A help desk gets on average 4 calls an hour, arriving independently. The number of calls in an hour follows a Poisson distribution with mean mu=4. Counts of events (visits, accidents, emails) are the job of Poisson regression in Poisson regression for count data in Python.

Pythoneditable
from scipy import stats

calls = stats.poisson(mu=4)
for k in range(9):
    print(k, f"{calls.pmf(k):.3f}", "#" * round(calls.pmf(k) * 100))
print(f"P(more than 6 calls): {calls.sf(6):.4f}")
Output
0 0.018 ##
1 0.073 #######
2 0.147 ###############
3 0.195 ####################
4 0.195 ####################
5 0.156 ################
6 0.104 ##########
7 0.060 ######
8 0.030 ###
P(more than 6 calls): 0.1107

A tiny text histogram: each # is 1% probability.

For a Poisson distribution the variance equals the mean. Real count data often varies more than that (overdispersion), and you will learn to check for it.

✎ Exercise

Emails arrive at a rate of 2.5 an hour (Poisson). Print the probability of no email in an hour and the probability of at least 3 emails, both with 4 decimals. Tip: 'at least 3' is 'more than 2'.

Hint: pmf(0) for exactly zero; sf(2) is P(X > 2), which for counts is the same as P(X >= 3).

Your codewrite your answer, then Run
from scipy import stats

# your code here

Expected output:

P(no email): 0.0821
P(at least 3): 0.4562
Show a solution
Solutioneditable
from scipy import stats

emails = stats.poisson(mu=2.5)
print(f"P(no email): {emails.pmf(0):.4f}")
print(f"P(at least 3): {emails.sf(2):.4f}")
Output
P(no email): 0.0821
P(at least 3): 0.4562

Check yourself

1. Which method gives the probability of a value at most x?

2. stats.norm(170, 8).ppf(0.95) returns 183.2. What is it?

3. For a Poisson count, P(at least 5) is…

Spotted a mistake on this page? Tell us