Gamma, Beta and Chi-Squared
A few more continuous families appear constantly in probability, statistics and machine learning. Each one has a natural story that explains where it comes from, and knowing the story is more useful than memorising the formula.
Gamma: waiting for several events
The time until the -th event of a Poisson process with rate is the sum of independent exponential gaps. Its density is the gamma (Erlang) density
with mean and variance . It is the continuous analogue of the negative binomial. With non-integer , is replaced by the gamma function .
import random
import math
rng = random.Random(1)
lam, k, n = 2.0, 3, 100_000
T = [sum(rng.expovariate(lam) for _ in range(k)) for _ in range(n)]
print("mean:", round(sum(T) / n, 4), " k/lambda =", k / lam)
def gamma_cdf(t, k, lam): # P(T <= t) = P(at least k events by time t)
return 1 - sum(math.exp(-lam * t) * (lam * t) ** j / math.factorial(j) for j in range(k))
for t in [0.5, 1.5, 3.0]:
print(f"P(T <= {t}): simulated {sum(x <= t for x in T) / n:.4f} formula {gamma_cdf(t, k, lam):.4f}")mean: 1.5009 k/lambda = 1.5
P(T <= 0.5): simulated 0.0804 formula 0.0803
P(T <= 1.5): simulated 0.5755 formula 0.5768
P(T <= 3.0): simulated 0.9376 formula 0.9380
The CDF formula uses a neat duality: the -th event happens by time exactly when at least events occur in , a Poisson count.
Beta: the distribution of a probability
The beta density on with parameters is
where normalises the area to 1. Its mean is . Two stories:
- Order statistics: the -th smallest of independent uniforms has the beta density with , .
- Bayesian updating: with a uniform prior on a coin's bias , after heads and tails the posterior is beta with , (Bayes' Theorem).
import random
rng = random.Random(2)
n, k, runs = 9, 3, 50_000
third = [sorted(rng.random() for _ in range(n))[k - 1] for _ in range(runs)]
print("mean of 3rd smallest of 9 uniforms:", round(sum(third) / runs, 4), " beta mean k/(n+1) =", k / (n + 1))
# Bayesian A/B test: which button has the higher click rate?
a = [rng.betavariate(1 + 45, 1 + 955) for _ in range(runs)] # 45 clicks of 1000
b = [rng.betavariate(1 + 62, 1 + 938) for _ in range(runs)] # 62 clicks of 1000
print("P(B better than A) ~", round(sum(y > x for x, y in zip(a, b)) / runs, 3))mean of 3rd smallest of 9 uniforms: 0.3004 beta mean k/(n+1) = 0.3
P(B better than A) ~ 0.953
The second part is a complete Bayesian A/B test: sample both posteriors and count how often B's click rate beats A's. This "probability to be best" is what many experimentation platforms report.
Chi-squared: sums of squared normals
If are independent standard normals, has the chi-squared distribution with degrees of freedom, mean and variance . It is a gamma density with shape and rate . It measures squared distances: a random point from a -dimensional standard normal is at squared distance about from the origin, so in high dimensions Gaussian samples live near a sphere of radius , not near the centre.
import numpy as np
rng = np.random.default_rng(3)
for k in [1, 2, 10, 100, 1000]:
z = rng.standard_normal((20_000, k))
r = np.sqrt((z ** 2).sum(axis=1))
print(f"k={k:5d} mean |z|^2 = {np.mean(r ** 2):8.2f} |z| between {np.quantile(r, 0.05):6.2f} and {np.quantile(r, 0.95):6.2f} sqrt(k) = {np.sqrt(k):6.2f}")k= 1 mean |z|^2 = 0.99 |z| between 0.06 and 1.94 sqrt(k) = 1.00
k= 2 mean |z|^2 = 1.99 |z| between 0.32 and 2.44 sqrt(k) = 1.41
k= 10 mean |z|^2 = 10.01 |z| between 1.99 and 4.28 sqrt(k) = 3.16
k= 100 mean |z|^2 = 99.95 |z| between 8.80 and 11.14 sqrt(k) = 10.00
k= 1000 mean |z|^2 = 999.57 |z| between 30.43 and 32.78 sqrt(k) = 31.62
The chi-squared distribution is the basis of the chi-squared test for counts, covered in Statistics.
In software
Gamma distributions model service times with several stages and are used in queueing simulations. Beta distributions drive Thompson sampling, the standard algorithm for multi-armed bandits in recommendation and ad systems: sample each arm's beta posterior and play the best sample. The "Gaussian samples lie on a shell" fact matters for embeddings and diffusion models in high dimensions (Math for ML).
Exercises
Exercise 1: Waiting for three
Calls arrive at rate 4 per minute. What are the mean and standard deviation of the time until the third call?
Answer
Mean 0.75 minutes, standard deviation about 0.43 minutes.
Solution
Gamma with , : mean , variance , standard deviation .
Exercise 2: Beta posterior
With a uniform prior, a coin shows 7 heads in 10 tosses. What is the posterior distribution of and its mean?
Answer
Beta(8, 4) with mean .
Solution
, ; mean .
Exercise 3: Thompson sampling (code)
Three ad variants have true click rates 0.04, 0.05 and 0.07, unknown to the algorithm. Run Thompson sampling for 5000 impressions and report how often each variant was shown.
Answer
The best variant (0.07) gets most of the impressions.
Solution
Each round, sample a click rate from each variant's beta posterior, show the variant with the highest sample, and update its counts.
import random
rng = random.Random(6)
true = [0.04, 0.05, 0.07]
wins = [0, 0, 0]
losses = [0, 0, 0]
shown = [0, 0, 0]
for _ in range(5000):
samples = [rng.betavariate(1 + wins[i], 1 + losses[i]) for i in range(3)]
i = samples.index(max(samples))
shown[i] += 1
if rng.random() < true[i]:
wins[i] += 1
else:
losses[i] += 1
print("impressions:", shown)
print("observed rates:", [round(wins[i] / max(shown[i], 1), 3) for i in range(3)])impressions: [473, 346, 4181]
observed rates: [0.042, 0.038, 0.067]
Test yourself
The time until the 5th event of a Poisson process with rate 2 has which distribution?
- Exponential with rate 10
- Gamma with ,
- Poisson with mean 10
- Normal
With a uniform prior, the posterior of a coin's bias after 3 heads and 1 tail is…
- Beta(3, 1)
- Beta(4, 2)
- Beta(1, 3)
- Uniform
The sum of squares of independent standard normals has mean…
- 0
- 1