1.3.5Probability & Statistics

Random variables (discrete and continuous)

2,871 words13 min readdifficulty · medium

A random variable is a function that maps outcomes of a random experiment to real numbers. It's the bridge between the mesy real world (coin flips, pixel intensities, user clicks) and the clean mathematical world where we can calculate probabilities and expectations.

Why Random Variables Matter in ML

In machine learning, almost everything is a random variable:

  • Features: pixel values, word counts, sensor readings
  • Labels: class assignments, regression targets
  • Model parameters: weights sampled during training
  • Predictions: outputs with uncertainty

Understanding RVs lets you:

  1. Quantify uncertainty in data and predictions
  2. Design loss functions that match your data distribution
  3. Sample from complex distributions (GANs, VAEs)
  4. Reason about model behavior probabilistically

The Core Intuition

Example: Roll a die. The outcome space is {⚀, ⚁, ⚂, ⚃, ⚄, ⚅}. Define XX = "number of dots". Then XX maps⚂ →3, ⚅ → 6, etc. XX is the random variable, not the outcome "3" itself.


Discrete Random Variables

Probability Mass Function (PMF)

The probability mass function P(X=x)P(X = x) gives the probability that XX takes the exact value xx.

Requirements (these ensure it's a valid probability distribution):

  1. Non-negativity: P(X=x)0P(X = x) \geq 0 for all xx
  2. Normalization: xP(X=x)=1\sum_{x} P(X = x) = 1 (all probabilities sum to 1)

Why these rules? Non-negativity: probabilities can't be negative. Normalization: something must happen, so total probability = 1.

Figure — Random variables (discrete and continuous)

From first principles:

  • Imagine repeating the experiment NN times, getting values x1,x2,...,xNx_1, x_2, ..., x_N
  • The sample average is 1Ni=1Nxi\frac{1}{N}\sum_{i=1}^{N} x_i
  • Group identical values: if xjx_j appears njn_j times, average = 1Njnjxj\frac{1}{N}\sum_{j} n_j x_j
  • As NN \to \infty, njNP(X=xj)\frac{n_j}{N} \to P(X = x_j) (frequency converges to probability)
  • Therefore: E[X]=xxP(X=x)E[X] = \sum_{x} x \cdot P(X = x)

Why does each term get weighted by P(X=x)P(X=x)? More probable values appear more often in the long run, so they contribute more to the average.

PMF: P(X=1)=p,P(X=0)=1pP(X = 1) = p, \quad P(X = 0) = 1 - p

Compact form: P(X=x)=px(1p)1xP(X = x) = p^x (1-p)^{1-x} for x{0,1}x \in \{0, 1\}

Why this form? When x=1x=1: p1(1p)0=pp^1 (1-p)^0 = p. When x=0x=0: p0(1p)1=1pp^0 (1-p)^1 = 1-p. It's a clever way to write both cases in one expression.

Expected value: E[X]=0P(X=0)+1P(X=1)=0(1p)+1p=pE[X] = 0 \cdot P(X=0) + 1 \cdot P(X=1) = 0 \cdot (1-p) + 1 \cdot p = p

Why E[X]=pE[X] = p? If you flip 100 times with p=0.3p=0.3, you expect about 30 heads. Average = 30/100 = 0.3 = pp.

ML Application: Binary classification labels (spam/not spam). Logistic regression outputs pp, which is literally E[X]E[X] for the Bernoulli RV "is this example class 1?".

Derivation of PMF:

  • Probability of any specific sequence with kk heads: pk(1p)nkp^k (1-p)^{n-k} (heads occur kk times at prob pp, tails nkn-k times at prob 1p1-p)
  • Number of such sequences (orderings of kk heads in nn flips): (nk)=n!k!(nk)!\binom{n}{k} = \frac{n!}{k!(n-k)!}
  • Why multiplication? Each specific sequence has prob pk(1p)nkp^k(1-p)^{n-k}, and there are (nk)\binom{n}{k} mutually exclusive sequences

P(X=k)=(nk)pk(1p)nk,k=0,1,...,nP(X = k) = \binom{n}{k} p^k (1-p)^{n-k}, \quad k = 0, 1, ..., n

Expected value: E[X]=npE[X] = np

Why? Each flip contributes expected value pp. With nn independent flips: E[X1+...+Xn]=E[X1]+...+E[Xn]=p+...+p=npE[X_1 + ... + X_n] = E[X_1] + ... + E[X_n] = p + ... + p = np.

ML Application: Dropout in neural networks. Each neuron independently "survives" with probability pp. Number of active neurons in a layer ~ Binomial.


Continuous Random Variables

Key difference from discrete: P(X=x)=0P(X = x) = 0 for any specific xx. Why? Infinitely many points, probability spread infinitely thin. We must ask about intervals: P(aXb)P(a \leq X \leq b).

Probability Density Function (PDF)

The probability density function f(x)f(x) is NOT a probability—it's a density. Think of it as "probability per unit length".

Requirements:

  1. Non-negativity: f(x)0f(x) \geq 0 for all xx
  2. Normalization: f(x)dx=1\int_{-\infty}^{\infty} f(x) \, dx = 1

Why integration? You're summing up infinitesimal probabilities f(x)dxf(x) \, dx over the interval. The "dxdx" converts density to probability: f(x)f(x) has units "probability per unit", dxdx has units "unit", product has units "probability".

Geometric intuition: Probability = area under the curve f(x)f(x) between aa and bb.

E[X]=xf(x)dxE[X] = \int_{-\infty}^{\infty} x \cdot f(x) \, dx

Why xf(x)x \cdot f(x)? Same logic as discrete: weight each value xx by its "probability" (here, density × dxdx).

PDF: f(x)={1baif axb0otherwisef(x) = \begin{cases} \frac{1}{b-a} & \text{if } a \leq x \leq b \\ 0 & \text{otherwise} \end{cases}

Why this form? Constant density in [a,b][a, b] (equally likely). Must integrate to 1: ab1badx=1ba(ba)=1\int_{a}^{b} \frac{1}{b-a} \, dx = \frac{1}{b-a} \cdot (b - a) = 1 \quad \checkmark

Expected value: E[X]=abx1badx=1baabxdx=1bax22ab=1bab2a22E[X] = \int_{a}^{b} x \cdot \frac{1}{b-a} \, dx = \frac{1}{b-a} \int_{a}^{b} x \, dx = \frac{1}{b-a} \cdot \frac{x^2}{2}\Big|_a^b = \frac{1}{b-a} \cdot \frac{b^2 - a^2}{2}

Simplify: b2a2=(ba)(b+a)b^2 - a^2 = (b-a)(b+a), so: E[X]=(ba)(b+a)2(ba)=b+a2E[X] = \frac{(b-a)(b+a)}{2(b-a)} = \frac{b+a}{2}

Why is it the midpoint? Symmetry. Equally likely on both sides, average is the center.

ML Application: Weight initialization in neural networks often uses uniform distributions (e.g., Xavier/Glorot initialization samples from U[6/(nin+nout),6/(nin+nout)]U[-\sqrt{6/(n_{in}+n_{out})}, \sqrt{6/(n_{in}+n_{out})}]).

PDF: f(x)=12πσ2exp((xμ)22σ2)f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right)

Parameters: μ\mu (mean, location), σ2\sigma^2 (variance, spread)

Why this functional form? (Brief derivation from maximum entropy under mean/variance constraints—full proof is complex, but the intuition):

  • We want the "most random" distribution given only knowledge of mean and variance
  • Maximizing entropy subject to E[X]=μE[X] = \mu, E[(Xμ)2]=σ2E[(X-\mu)^2] = \sigma^2 yields this exponential-quadratic form
  • The 1/2πσ21/\sqrt{2\pi\sigma^2} ensures f(x)dx=1\int f(x) dx = 1

Why exp(x2)\exp(-x^2) shape? It concentrates probability near the mean (μ\mu), with tails dying off quickly. The quadratic in the exponent ensures smoothness and the "bell" shape.

Expected value: By symmetry around μ\mu, E[X]=μE[X] = \mu.

ML Applications:

  1. Gaussian noise in data: y=f(x)+ϵy = f(x) + \epsilon, where ϵN(0,σ2)\epsilon \sim \mathcal{N}(0, \sigma^2)
  2. Weight initialization (e.g., He initialization: N(0,2/nin)\mathcal{N}(0, 2/n_{in}))
  3. Gaussian processes, variational autoencoders (VAE latent space)
  4. Linear regression assumes ϵiN(0,σ2)\epsilon_i \sim \mathcal{N}(0, \sigma^2)

Cumulative Distribution Function (CDF)

Both discrete and continuous RVs have CDF F(x)=P(Xx)F(x) = P(X \leq x).

For discrete RV: F(x)=xixP(X=xi)F(x) = \sum_{x_i \leq x} P(X = x_i) (sum up PMF values)

For continuous RV: F(x)=xf(t)dtF(x) = \int_{-\infty}^{x} f(t) \, dt (integrate PDF)

Why useful?

  • CDFs always exist (PMFs/PDFs don't for mixed distributions)
  • Easy to compute probabilities: P(a<Xb)=F(b)F(a)P(a< X \leq b) = F(b) - F(a)
  • Relationship to PDF: f(x)=dF(x)dxf(x) = \frac{dF(x)}{dx} (PDF is the derivative of CDF)

ML Application: Percentile-based metrics, quantile regression, inverse transform sampling (generate samples from any distribution by applying F1F^{-1} to uniform random numbers).


Common Mistakes

Why it feels right: We're used to P(X=x)P(X=x) from discrete RVs.

The fix: f(x)f(x) is density, not probability. Units: f(x)f(x) is "probability per unit". f(x)=2f(x) = 2 means "locally, probability accumulates at 2 units per unit length". Actual probability: P(X[x,x+dx])=f(x)dxP(X \in [x, x+dx]) = f(x) \cdot dx (which is small for small dxdx).

Check: For XU[0,0.3]X \sim U[0, 0.3], f(x)=1/0.33.33>1f(x) = 1/0.3 \approx 3.33 > 1. But P(0X0.3)=3.33×0.3=1P(0 \leq X \leq 0.3) = 3.33 \times 0.3 = 1

Why it feels right: Both use weighted averages.

The fix:

  • Discrete: E_X = sum(x * P(x) for x in values)
  • Continuous: E_X = integrate(x * f(x), x, -inf, inf) or E_X = np.mean(samples) for samples

In NumPy, if you have samples from a continuous RV, use np.mean(samples), not sum(x * count(x)) (which assumes discrete).

Why it feels right: We measure "20°C" on thermometers.

The fix: Real measurements have finite precision. Your thermometer reads "20°C" = "between 19.5and 20.5°C" (an interval). For continuous RVs, always ask about intervals: P(19.5X20.5)P(19.5 \leq X \leq 20.5).


Active Recall

Recall Explain Random Variables to a 12-Year-Old

Imagine you have a magic box that plays games. Sometimes it rolls dice, sometimes it spins a wheel. Every time you use the box, it gives you a number. That number is random (you don't know what it'll be before you use the box), but it follows rules.

A random variable is like a nickname for that number. We call it XX. If we roll a die, XX might be 1, 2, 3, 4, 5, or 6 (only these numbers, nothing in between). That's discrete—like counting candies.

But if we spin a wheel that can land anywhere from 0 to 100, XX could be 23.7145... or 99.001... or any number in between. That's continuous—like measuring how much water is in a cup.

For discrete, we can say "the probability of getting exactly 3 is..." (like P(X=3)=1/6P(X=3)=1/6 for a fair die). For continuous, we can't say "exactly 23.7145" because there are infinite possibilities—it's like asking for one specific grain of sand on a beach. Instead, we ask "What's the probability XX is between 20 and 30?" and add up probabilities in that range (integration).

The cool part: in AI, almost everything is a random variable—what digit is in an image, what word comes next, whether an email is spam. Understanding RVs means understanding how AI handles uncertainty.


Memory Aids

  • Discrete = Distinct, Discrete math (integers)
  • PMF = Probability Mass (mass sits at points)
  • PDF = Probability Density (spread like a fluid)

Alphabet trick:

  • PMF uses Sum (Σ\Sigma)
  • PDF uses Integral (\int)
  • "S comes before I" → use sum for discrete, integral for continuous

Connections


#flashcards/ai-ml

What is a random variable? :: A function that maps outcomes of a random experiment to real numbers. It's the bridge between real-world randomness and mathematical probability.

What is the difference between a discrete and continuous random variable?
Discrete RVs take countable values (can list them); continuous RVs take uncountably infinite values (any real number in an interval).
What is a PMF and what are its two requirements?
Probability Mass Function: P(X=x)P(X=x) for discrete RVs. Requirements: (1) P(X=x)0P(X=x) \geq 0 (non-negative), (2) xP(X=x)=1\sum_x P(X=x) = 1 (sums to 1).
What is a PDF and why is f(x)f(x) not a probability?
Probability Density Function for continuous RVs. f(x)f(x) is a density (probability per unit length), not a probability. Probability = abf(x)dx\int_a^b f(x) dx (area under curve).
Why is P(X=x)=0P(X = x) = 0 for continuous random variables?
Infinitely many possible values mean probability is spread infinitely thin. We must ask about intervals, not exact points.
Expected value formula for discrete RV?
E[X]=xxP(X=x)E[X] = \sum_x x \cdot P(X=x). Each value weighted by its probability.

Expected value formula for continuous RV? :: E[X]=xf(x)dxE[X] = \int_{-\infty}^{\infty} x \cdot f(x) \, dx. Weighted integral over the density.

Bernoulli distribution: PMF and expected value?
P(X=1)=pP(X=1) = p, P(X=0)=1pP(X=0) = 1-p. E[X]=pE[X] = p. Models binary outcomes (success/failure).
Binomial distribution: what does it model and what is E[X]E[X]?
Number of successes in nn independent Bernoulli trials. P(X=k)=(nk)pk(1p)nkP(X=k) = \binom{n}{k} p^k (1-p)^{n-k}. E[X]=npE[X] = np.
Uniform distribution on [a,b][a,b]: PDF and expected value?
f(x)=1baf(x) = \frac{1}{b-a} for x[a,b]x \in [a,b], 0 otherwise. E[X]=a+b2E[X] = \frac{a+b}{2} (midpoint by symmetry).
Gaussian distribution: PDF and parameters?
f(x)=12πσ2exp((xμ)22σ2)f(x) = \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left(-\frac{(x-\mu)^2}{2\sigma^2}\right). Parameters: μ\mu (mean), σ2\sigma^2 (variance).
What is a CDF and how does it relate to PDF/PMF?
Cumulative Distribution Function: F(x)=P(Xx)F(x) = P(X \leq x). For continuous RVs, F(x)=xf(t)dtF(x) = \int_{-\infty}^x f(t) dt and f(x)=F(x)f(x) = F'(x).
Why can a PDF have values greater than 1?
PDF is a density (probability per unit), not a probability. As long as f(x)dx=1\int f(x) dx = 1, f(x)f(x) can exceed 1 locally (e.g., U[0,0.5]U[0, 0.5] has f(x)=2f(x) = 2).
ML application of Bernoulli distribution?
Binary classification labels. Logistic regression outputs p=E[X]p = E[X] for Bernoulli RV "is this class 1?".
ML application of Gaussian distribution?
Noise modeling (y=f(x)+ϵy = f(x) + \epsilon, ϵN(0,σ2)\epsilon \sim \mathcal{N}(0,\sigma^2)), weight initialization, VAE latent space, Gaussian processes.

Concept Map

outcomes

is a

type

type

takes values from

described by

requires

used to compute

derived from

example

enables in ML

Random experiment

Random variable

Function mapping to reals

Discrete RV

Continuous RV

Countable set

Probability mass function

Non-negativity and Normalization

Expected value

Long-run sample average

Bernoulli distribution

Quantify uncertainty

Hinglish (regional understanding)

Intuition Hinglish mein samjho

Random variable samajhne ke liye ek simple idea hai: yeh ek function hai jo real-world randomness ko numbers mein convert karta hai. Jaise agarap ek coin flip karte ho, toh outcome "heads" ya "tails" hai. Lekin random variable X define karo: X=1 agar heads, X=0 agar tails. Ab ap mathematics use kar sakte ho — expectation, variance, probability — kyunki ab sab kuch numbers mein hai.

Do types hain: Discrete (jaise dice roll, class labels in AI — countable values) aur Continuous (jaise temperature, weight — any value in a range). Discrete mein aap directly bol sakte ho "P(X=3) = 1/6" (exact probability). Continuous mein aap exact point ka probability nahi mang sakte (always zero hota hai kyunki infinite points hain), ap sirf interval mang sakte ho: "P(20 ≤ X ≤ 25) kitna hai?" Iska answer PDF (probability density function) ko integrate karke milta hai — basically area under the curve.

Machine learning mein har chez random variable hai. Tumhara data (features, labels), model ke weights during training (randomly initialized), predictions (uncertainty ke sath). Gaussian distribution (bell curve) sabse common hai — noise modeling mein, weight initialization mein, VAEs mein. Bernoulli distribution binary classification ke liye (spam/not spam). Agar tum probability aur randomness handle karna seekh gaye, tum ML models ki behaviour ko deeply samajh paoge — kyunki end mein sab kuch uncertainty quantify karna hai

Go deeper — visual, from zero

Test yourself — Probability & Statistics

Connections