AnyLearn
All lessons
Mathintermediate

Random Variables and Distributions

Build the vocabulary that underlies all of ML: sample spaces, discrete and continuous random variables, PMFs, PDFs, and CDFs. Then tour the key distributions — Bernoulli, Binomial, Categorical, Gaussian, Poisson, Exponential, Uniform — with their parameters, mean, variance, and exactly when each appears in practice.

Updated · AI-authored, review-gated · how lessons are made

Not signed in: your progress and quiz score won't be saved.
Progress1 / 10

Sample spaces and events

Every probability model starts with a sample space Ω\Omega — the set of all outcomes. An event is a subset A⊆ΩA \subseteq \Omega. A probability measure PP assigns a number in [0,1][0,1] to each event, with P(Ω)=1P(\Omega) = 1 and countable additivity: for disjoint A1,A2,…A_1, A_2, \ldots,

P ⁣(⋃i=1∞Ai)=∑i=1∞P(Ai).P\!\left(\bigcup_{i=1}^{\infty} A_i\right) = \sum_{i=1}^{\infty} P(A_i).

From these three axioms (due to Kolmogorov) everything else follows. Most people's intuition breaks because Ω\Omega can be uncountably infinite — e.g., Ω=R\Omega = \mathbb{R} when modelling a real-valued measurement. That's where random variables come in: they give us a tractable handle on Ω\Omega.

Full lesson text

All 10 steps on one page, for reading, reference, and search.

Show

1. Sample spaces and events

Every probability model starts with a sample space Ω\Omega — the set of all outcomes. An event is a subset A⊆ΩA \subseteq \Omega. A probability measure PP assigns a number in [0,1][0,1] to each event, with P(Ω)=1P(\Omega) = 1 and countable additivity: for disjoint A1,A2,…A_1, A_2, \ldots,

P ⁣(⋃i=1∞Ai)=∑i=1∞P(Ai).P\!\left(\bigcup_{i=1}^{\infty} A_i\right) = \sum_{i=1}^{\infty} P(A_i).

From these three axioms (due to Kolmogorov) everything else follows. Most people's intuition breaks because Ω\Omega can be uncountably infinite — e.g., Ω=R\Omega = \mathbb{R} when modelling a real-valued measurement. That's where random variables come in: they give us a tractable handle on Ω\Omega.

2. Random variables: discrete vs continuous

A random variable X:Ω→RX: \Omega \to \mathbb{R} maps outcomes to numbers. The distribution of XX is the induced probability law over R\mathbb{R}.

  • Discrete: XX takes values in a countable set (often {0,1,2,…}\{0, 1, 2, \ldots\}). Its distribution is captured by the probability mass function p(x)=P(X=x)p(x) = P(X = x), which must satisfy p(x)≥0p(x) \ge 0 and ∑xp(x)=1\sum_x p(x) = 1.
  • Continuous: XX takes values in an interval or R\mathbb{R}. P(X=x)=0P(X = x) = 0 for every single xx; instead the distribution is characterised by a probability density function f(x)≥0f(x) \ge 0 with ∫−∞∞f(x) dx=1\int_{-\infty}^{\infty} f(x)\,dx = 1, and P(a≤X≤b)=∫abf(x) dxP(a \le X \le b) = \int_a^b f(x)\,dx.

The key rule: PMF gives the probability of a point; PDF gives the probability of an interval.

3. The CDF: one function to rule them all

The cumulative distribution function (CDF) unifies both cases:

F(x)=P(X≤x).F(x) = P(X \le x).

Properties (true for any XX):

  • FF is non-decreasing.
  • lim⁡x→−∞F(x)=0\lim_{x \to -\infty} F(x) = 0, lim⁡x→+∞F(x)=1\lim_{x \to +\infty} F(x) = 1.
  • FF is right-continuous.

For discrete XX: F(x)=∑k≤xp(k)F(x) = \sum_{k \le x} p(k) (a staircase). For continuous XX: F(x)=∫−∞xf(t) dtF(x) = \int_{-\infty}^{x} f(t)\,dt, so f(x)=F′(x)f(x) = F'(x).

The CDF is exactly what numpy and scipy.stats return via .cdf(). Knowing it lets you compute any probability as P(a<X≤b)=F(b)−F(a)P(a < X \le b) = F(b) - F(a) — no integration required.

from scipy import stats
X = stats.norm(loc=0, scale=1)  # standard Gaussian
print(X.cdf(1.96))   # 0.975  (classic 95% CI endpoint)
print(X.ppf(0.025))  # -1.960 (inverse CDF = quantile)

4. Discrete distributions: Bernoulli, Binomial, Categorical

Bernoulli(p)(p) — a single binary trial. P(X=1)=pP(X=1)=p, P(X=0)=1−pP(X=0)=1-p. Mean pp, variance p(1−p)p(1-p). Every classifier output, coin flip, or clicked/not-clicked event is Bernoulli.

Binomial(n,p)(n,p) — count of successes in nn i.i.d. Bernoulli(p)(p) trials: P(X=k)=(nk)pk(1−p)n−k,k=0,…,n.P(X=k) = \binom{n}{k}p^k(1-p)^{n-k}, \quad k=0,\ldots,n. Mean npnp, variance np(1−p)np(1-p). Use when summing independent binary outcomes.

Categorical(π)(\boldsymbol{\pi}) — generalises Bernoulli to KK classes: P(X=k)=πkP(X=k)=\pi_k with ∑kπk=1\sum_k \pi_k=1. This is the output distribution of a softmax classifier. Its multivariate cousin is Multinomial(n,π)(n,\boldsymbol{\pi}), which counts occurrences of each class in nn draws.

5. Continuous distributions: Gaussian, Uniform, Exponential

Gaussian (Normal) N(μ,σ2)\mathcal{N}(\mu, \sigma^2) — the workhorse. PDF: f(x)=1σ2πexp⁡ ⁣(−(x−μ)22σ2).f(x) = \frac{1}{\sigma\sqrt{2\pi}}\exp\!\left(-\frac{(x-\mu)^2}{2\sigma^2}\right). Mean μ\mu, variance σ2\sigma^2. Appears everywhere via the CLT; conjugate to itself.

Uniform Unif(a,b)\mathrm{Unif}(a,b) — constant density 1b−a\frac{1}{b-a} on [a,b][a,b]. Mean a+b2\frac{a+b}{2}, variance (b−a)212\frac{(b-a)^2}{12}. The default "I know nothing" prior on a bounded interval; used in random initialization.

Exponential(λ)(\lambda) — models the waiting time between events in a Poisson process: f(x)=λe−λxf(x) = \lambda e^{-\lambda x}, x≥0x \ge 0. Mean 1/λ1/\lambda, variance 1/λ21/\lambda^2. Memoryless: P(X>s+t∣X>s)=P(X>t)P(X > s+t \mid X > s) = P(X > t). Models inter-arrival times, dropout survival, and hardware failure rates.

6. The Poisson distribution

Poisson(λ)(\lambda) counts events in a fixed interval when they occur independently at rate λ\lambda:

P(X=k)=λke−λk!,k=0,1,2,…P(X=k) = \frac{\lambda^k e^{-\lambda}}{k!}, \quad k = 0, 1, 2, \ldots

Mean λ\lambda, variance λ\lambda (they're equal — a signature). As n→∞n \to \infty, p→0p \to 0 with np=λnp = \lambda fixed, Binomial(n,p)→(n,p) \to Poisson(λ)(\lambda). Classic applications: number of word occurrences in a document (bag-of-words models), events per time bucket in streaming data, rare disease counts.

import numpy as np
from scipy import stats

lam = 3.5
x = np.arange(0, 15)
pmf = stats.poisson.pmf(x, mu=lam)
print(f"P(X=0) = {pmf[0]:.4f}")   # 0.0302
print(f"P(X=3) = {pmf[3]:.4f}")   # 0.2158
print(f"mean={stats.poisson.mean(mu=lam)}, var={stats.poisson.var(mu=lam)}")
# mean=3.5, var=3.5

7. Choosing a distribution

Decision tree for picking the right distribution given the nature of the random variable:

flowchart TD
  A["What kind of RV?"]
  B["Discrete"]
  C["Continuous"]
  D["Binary outcome (0/1)?"]
  E["Count of successes in n trials?"]
  F["Count of events in interval?"]
  G["One of K classes?"]
  H["Bernoulli(p)"]
  I["Binomial(n, p)"]
  J["Poisson(lambda)"]
  K["Categorical(pi)"]
  L["Bounded interval?"]
  M["Waiting time / positive reals?"]
  N["Bell-shaped / CLT?"]
  O["Uniform(a, b)"]
  P["Exponential(lambda)"]
  Q["Gaussian N(mu, sigma^2)"]
  A --> B
  A --> C
  B --> D
  B --> E
  B --> F
  B --> G
  D --> H
  E --> I
  F --> J
  G --> K
  C --> L
  C --> M
  C --> N
  L --> O
  M --> P
  N --> Q

8. Distribution reference table

A quick-reference table of the distributions above. B(a,b)B(a,b) is the beta function; all others are standard notation.

DistributionParametersMeanVariance
Bernoullip∈[0,1]p \in [0,1]ppp(1−p)p(1-p)
Binomialn∈N, p∈[0,1]n \in \mathbb{N},\, p \in [0,1]npnpnp(1−p)np(1-p)
Categoricalπ∈ΔK−1\boldsymbol{\pi} \in \Delta^{K-1}——
Poissonλ>0\lambda > 0λ\lambdaλ\lambda
Gaussianμ∈R, σ2>0\mu \in \mathbb{R},\, \sigma^2 > 0μ\muσ2\sigma^2
Uniforma<ba < ba+b2\frac{a+b}{2}(b−a)212\frac{(b-a)^2}{12}
Exponentialλ>0\lambda > 01λ\frac{1}{\lambda}1λ2\frac{1}{\lambda^2}

Notice that Poisson has mean == variance — if empirical variance ≫\gg mean, the data is overdispersed and you need a Negative Binomial instead.

9. Independence and joint distributions

Two random variables X,YX, Y are independent if their joint distribution factors:

p(x,y)=pX(x) pY(y)(discrete)p(x, y) = p_X(x)\, p_Y(y) \quad (\text{discrete}) f(x,y)=fX(x) fY(y)(continuous)f(x, y) = f_X(x)\, f_Y(y) \quad (\text{continuous})

Independence implies Cov(X,Y)=0\text{Cov}(X,Y)=0 but not vice versa (uncorrelated ≠\neq independent, except for Gaussians). The marginal of XX is obtained by summing/integrating out YY: pX(x)=∑yp(x,y)p_X(x) = \sum_y p(x,y).

When X1,…,XnX_1, \ldots, X_n are i.i.d. (independent, identically distributed), many results become tractable — the CLT, the law of large numbers, maximum likelihood factorization. "i.i.d." is the backbone assumption in most supervised learning setups.

10. Working with distributions in NumPy / SciPy

Every scipy.stats distribution follows the same API: construct with parameters, then call .pmf/.pdf, .cdf, .ppf (quantile), .rvs (random samples).

import numpy as np
from scipy import stats

# Gaussian
g = stats.norm(loc=2.0, scale=1.5)
print(g.pdf(2.0))         # peak: 0.2659
print(g.cdf(3.5))         # P(X <= 3.5): 0.8413
print(g.ppf(0.95))        # 95th percentile: 4.468
samples = g.rvs(size=10_000, random_state=0)

# Binomial
b = stats.binom(n=20, p=0.3)
print(b.pmf(6))            # P(X=6): 0.1916
print(b.mean(), b.var())   # 6.0  4.2

# Exponential (scipy uses scale=1/lambda)
e = stats.expon(scale=1/2.0)
print(e.mean())            # 0.5 = 1/lambda

Always double-check parameter conventions — scipy uses scale = 1/lambda for the Exponential, not λ\lambda directly.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. A coin is flipped 100 times. The number of heads follows which distribution, and what is its variance?
    • Poisson(50); variance = 50
    • Binomial(100, 0.5); variance = 25
    • Gaussian(50, 50); variance = 50
    • Bernoulli(0.5); variance = 0.25
  2. For a Poisson($\lambda$) random variable, which statement is always true?
    • The mean equals $\lambda$ and the variance equals $\lambda^2$.
    • The mean equals $\lambda$ and the variance equals $\lambda$.
    • The mean equals $1/\lambda$ and the variance equals $1/\lambda^2$.
    • The distribution is symmetric around $\lambda$ for all $\lambda > 0$.
  3. You observe $P(X = x) > 0$ for a specific real value $x$. What can you conclude?
    • Nothing; this holds for all random variables.
    • $X$ must be a continuous random variable with a well-defined PDF.
    • $X$ must be a discrete random variable; continuous RVs assign zero probability to any single point.
    • $X$ follows a Gaussian distribution.
  4. An Exponential$(\lambda)$ distribution is a good model for which of the following?
    • The number of customer arrivals in one hour.
    • The waiting time between successive customer arrivals in a Poisson process.
    • The proportion of defective items in a batch of 200.
    • A measurement that is equally likely to fall anywhere in $[0, 1]$.
  5. Which pair of distributions has the same mean and variance when their parameters are matched correctly?
    • Bernoulli$(p)$ and Binomial$(1, p)$
    • Gaussian$(\lambda, \lambda)$ and Poisson$(\lambda)$
    • Exponential$(\lambda)$ and Poisson$(\lambda)$
    • Uniform$(0,1)$ and Bernoulli$(0.5)$

Related lessons