Probability
A continuous random quantity (a waiting time, a measurement error, a neuron's weight at initialisation) is described by a probability density, and every question about it becomes an integral. This lesson defines densities, the cumulative distribution function, expected value and variance, studies the exponential and normal distributions, and shows why the normal distribution sits under so much of machine learning.
Probability density functions
A continuous random variable has a probability density function (pdf) when
Two consequences surprise people. First, for every single value, so and give the same probabilities. Second, is not a probability and can exceed 1: it is probability per unit length, so .
The cumulative distribution function is . By the Fundamental Theorem of Calculus, wherever is continuous, and .
Mean, variance and median
The expected value (mean) weights each value by its density, the continuous analogue of :
is the balance point of the region under , exactly the of a lamina in Applications to Physics and Engineering (with total "area" 1). The median solves . These integrals are improper, and they can diverge: the Cauchy density is a valid pdf with no mean at all (Exercise 3).
import sympy as sp
x, c = sp.symbols("x c", real=True)
f = c * x * (3 - x) # on [0, 3], zero elsewhere
c_val = sp.solve(sp.integrate(f, (x, 0, 3)) - 1, c)[0]
f = f.subs(c, c_val)
mu = sp.integrate(x * f, (x, 0, 3))
var = sp.integrate(x**2 * f, (x, 0, 3)) - mu**2
print("c =", c_val)
print("P(X ≤ 1) =", sp.integrate(f, (x, 0, 1)))
print("mean =", mu, " variance =", var)c = 2/9
P(X ≤ 1) = 7/27
mean = 3/2 variance = 9/20
The exponential distribution
Waiting times between independent random events (requests hitting a server, radioactive decays) are modelled by
The mean follows by parts: . It is the only continuous memoryless distribution: . Having waited 5 minutes tells you nothing about the remaining wait.
Inverse transform sampling. If is uniform on and is a continuous increasing CDF, then has CDF , because . For the exponential, . This is how random-number libraries turn uniform bits into other distributions.
import numpy as np
rng = np.random.default_rng(11)
lam = 0.5 # one event every 2 s on average
U = rng.random(100_000)
T = -np.log(1 - U) / lam # inverse transform
print(f"sample mean {float(T.mean()):.3f} theory 1/λ = {1 / lam:.3f}")
print(f"P(T > 3) {float(np.mean(T > 3)):.4f} theory e^(-1.5) = {np.exp(-1.5):.4f}")
waited = T[T > 2] - 2 # memoryless: remaining wait after 2 s
print(f"mean remaining wait after 2 s: {float(waited.mean()):.3f}")sample mean 2.001 theory 1/λ = 2.000
P(T > 3) 0.2227 theory e^(-1.5) = 0.2231
mean remaining wait after 2 s: 1.995
The normal distribution
The normal (Gaussian) density with mean and standard deviation is
Its antiderivative is not elementary, so the constant comes from the Gaussian integral , proved by squaring it and switching to polar coordinates (Double Integrals in Polar Coordinates). Probabilities are computed with the error function , which libraries implement with series and rational approximations (Applications of Taylor Polynomials). The central limit theorem explains its ubiquity: sums of many small independent effects are approximately normal (Central Limit Theorem).
import numpy as np
import matplotlib.pyplot as plt
from math import erf, sqrt
from scipy.integrate import quad
pdf = lambda x: np.exp(-x**2 / 2) / np.sqrt(2 * np.pi)
total, _ = quad(pdf, -np.inf, np.inf)
print(f"∫ pdf = {total:.10f}")
for k in (1, 2, 3):
print(f"P(|Z| < {k}) = {erf(k / sqrt(2)):.4f}")
xs = np.linspace(-4, 4, 400)
plt.figure(figsize=(6, 3.5))
plt.plot(xs, pdf(xs), color="C0")
band = (xs > -1) & (xs < 1)
plt.fill_between(xs[band], pdf(xs[band]), alpha=0.3, label="P(|Z| < 1) ≈ 0.683")
plt.title("Standard normal density"); plt.legend(); plt.grid(alpha=0.3)
print("plotted the standard normal pdf with the ±1σ area shaded")∫ pdf = 1.0000000000
P(|Z| < 1) = 0.6827
P(|Z| < 2) = 0.9545
P(|Z| < 3) = 0.9973
plotted the standard normal pdf with the ±1σ area shaded
In software: the normal distribution in ML
- Mean squared error is a Gaussian likelihood. If a model predicts and the noise is normal with fixed , the negative log-likelihood of the data is . Minimising it is minimising the squared error, which is why linear regression uses MSE (Linear Regression).
- Weight initialisation. Neural networks draw initial weights from with (He) or (Xavier) so that the variance of activations, an integral like , stays stable from layer to layer.
- Sampling and noise. Diffusion models add and remove Gaussian noise; VAEs sample with ; Gaussian naive Bayes and anomaly detectors evaluate normal densities. See Probability Densities in AI for more, and the survey treatment in Normal Distribution.
Exercises
Exercise 1: Normalise a density
Find so that on is a pdf, then compute and .
Answer
, , .
Solution
Exercise 2: Median of the exponential
Show that the median of the exponential distribution is . For a server with a mean gap of 2 s between requests, what is the median gap?
Answer
; with , .
Solution
Exercise 3: A density without a mean
Show that is a pdf, and that diverges.
Answer
, but , so the mean does not exist.
Solution
import sympy as sp
x, N = sp.symbols("x N", positive=True)
f = 1 / (sp.pi * (1 + x**2))
print(sp.integrate(f, (x, -sp.oo, sp.oo)), "|", sp.integrate(x * f, (x, 0, N)))1 | log(N**2 + 1)/(2*pi)
Exercise 4: Inverse transform sampling
Derive a sampler for on and check its mean () on 100 000 samples.
Answer
, so ; the sample mean is .
Solution
, so . Theory: .
import numpy as np
rng = np.random.default_rng(5)
X = np.sqrt(rng.random(100_000))
print(f"{float(X.mean()):.4f}")0.6671
Test yourself
A pdf has . What does that mean?
- It is impossible: must be
- Near 2,
If is a continuous CDF, how is the pdf obtained?
Why does least-squares regression correspond to a normal noise model?
- Because the normal pdf integrates to 1
- Because of the Gaussian likelihood is a constant plus
- Because the mean equals the median
- It does not; it corresponds to exponential noise