Concept notebookChecking saved investigationReading browser-local route memory before showing a continuation.

Random Variables

A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.

published · difficulty 2/5 · 14 min read

01

01

Intuition

Build the mental picture first so the rest of the page has something to attach to.

PredictName the object in plain language, then predict what should change.Leave with one reusable mental picture before notation appears.

A tilted die produces one raw outcome, say ω=5\omega=5ω=5. What number did you actually measure: the face value 555, the high-roll indicator 111, the parity 111, or the squared miss (65)2=1(6-5)^2=1(65)2=1?

The phrase "random variable" sounds as if the variable itself is a little random object. It is more useful to think of it as a measurement you decide to take from an uncertain situation.

The world produces raw outcomes:

  • a sequence of coin flips
  • an image sampled from a dataset
  • a user clicking or not clicking
  • a training example with an input and label

A random variable turns each raw outcome into a number:

  • XXX = number of heads in 10 coin flips
  • YYY = pixel intensity at one location
  • LLL = model loss on a sampled training example

Once the raw world has been measured numerically, probability can move from outcomes to values. That moved probability is the distribution of the random variable. From there we can talk about average behavior, spread, likelihood, and the noisy estimates that appear during training.

The distinction is small but load-bearing: the outcome might be a whole image or sentence, while the random variable might be one scalar loss, one token count, or one feature activation.

"Measurement" is a metaphor, not a requirement that there is a physical instrument. The important fact is that XXX is a rule: once the raw outcome ω\omegaω is known, the value X(ω)X(\omega)X(ω) is determined.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

02

02

Math

Translate the story into symbols, assumptions, and a derivation you can inspect.

InspectTrack the same object through the notation and check each symbol.Leave with the invariant the equations preserve.

Let (Ω,F,P)(\Omega,\mathcal F,P)(Ω,F,P) be a probability space. The sample space Ω\OmegaΩ contains raw outcomes ω\omegaω, the event collection F\mathcal FF says which subsets can be assigned probabilities, and PPP assigns probability to those events.

A real-valued random variable is a measurable function

X:(Ω,F)(R,B(R)).X:(\Omega,\mathcal F)\to(\mathbb R,\mathcal B(\mathbb R)).X:(Ω,F)(R,B(R)).

Measurable means that whenever BBB is a Borel set of possible values, the set of raw outcomes that land in BBB is an event:

X1(B)={ωΩ:X(ω)B}F.X^{-1}(B)=\{\omega\in\Omega:X(\omega)\in B\}\in\mathcal F.X1(B)={ωΩ:X(ω)B}F.

The distribution, or law, of XXX is the pushforward of PPP through XXX. For any Borel set BB(R)B\in\mathcal B(\mathbb R)BB(R),

PX(B)=P(XB)=P({ωΩ:X(ω)B}).P_X(B)=P(X \in B)=P(\{\omega \in \Omega : X(\omega) \in B\}).PX(B)=P(XB)=P({ωΩ:X(ω)B}).

In the finite discrete case, write P(ω)P(\omega)P(ω) as shorthand for the atomic mass P({ω})P(\{\omega\})P({ω}). Then all outcomes mapping to the same value get grouped together:

pX(x)=P(X=x)=ω:X(ω)=xP(ω).p_X(x)=P(X=x)=\sum_{\omega : X(\omega)=x} P(\omega).pX(x)=P(X=x)=ω:X(ω)=xP(ω).

The support of XXX in this finite setting is

supp(X)={x:pX(x)>0}.\operatorname{supp}(X)=\{x:p_X(x)>0\}.supp(X)={x:pX(x)>0}.

The group of outcomes mapping to one value is the fiber over xxx:

X1({x})={ω:X(ω)=x}.X^{-1}(\{x\})=\{\omega:X(\omega)=x\}.X1({x})={ω:X(ω)=x}.

The probability mass of that fiber becomes the PMF value pX(x)p_X(x)pX(x).

This is the bridge to the next concept, distributions: the random variable is the map, and the distribution is the probability mass after the map.

The expectation can be computed over raw outcomes or over the induced distribution:

E[X]=ωΩX(ω)P(ω)=xxpX(x).\mathbb{E}[X] = \sum_{\omega \in \Omega} X(\omega)P(\omega) = \sum_x x\,p_X(x).E[X]=ωΩX(ω)P(ω)=xxpX(x).

Variance measures squared spread around that expectation:

Var(X)=E[(XE[X])2]=E[X2](E[X])2.\operatorname{Var}(X) = \mathbb{E}[(X-\mathbb{E}[X])^2] = \mathbb{E}[X^2] - (\mathbb{E}[X])^2.Var(X)=E[(XE[X])2]=E[X2](E[X])2.

When XXX has a density fXf_XfX, probabilities and expectations are computed by integration:

P(aXb)=abfX(x)dx.P(a\le X\le b)=\int_a^b f_X(x)\,dx.P(aXb)=abfX(x)dx.
E[X]=xfX(x)dx.\mathbb{E}[X]=\int x\,f_X(x)\,dx.E[X]=xfX(x)dx.

A density value is not itself a probability, and not every distribution has an ordinary density. The measure PXP_XPX is the general object; PMFs and densities are common representations of it.

In machine learning, a common random variable is the loss on a sampled example. If ZZZ is a random training example and θ\thetaθ are model parameters, then

L=(Z;θ)L=\ell(Z;\theta)L=(Z;θ)

is a random variable because the sampled example ZZZ is uncertain. Training tries to reduce E[L]\mathbb{E}[L]E[L], while a mini-batch computes a noisy estimate:

L^m=1mi=1m(Zi;θ).\hat L_m=\frac{1}{m}\sum_{i=1}^m \ell(Z_i;\theta).L^m=m1i=1m(Zi;θ).

For independent sampled examples, E[L^m]=E[L]\mathbb E[\hat L_m]=\mathbb E[L]E[L^m]=E[L] and Var(L^m)=Var(L)/m\operatorname{Var}(\hat L_m)=\operatorname{Var}(L)/mVar(L^m)=Var(L)/m. That is one reason batch size, learning rate, and optimization stability are connected.

This is also the bridge to likelihood and Bayesian inference. Observed data are values of random variables under a model distribution; likelihood scores those observed values, cross-entropy averages their surprise, and Bayesian inference uses likelihoods to update distributions over unknowns.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

03

03

Code

Keep the implementation aligned with the notation so the algorithm is legible.

TraceMatch variables to symbols before reading the implementation.Leave with a runnable witness for the math.
from collections import defaultdict
from math import exp

# Raw outcome space: a tilted six-sided die.
omega = [1, 2, 3, 4, 5, 6]

def tilted_die(tilt):
    weights = {w: exp(tilt * (w - 3.5)) for w in omega}
    total = sum(weights.values())
    return {w: weight / total for w, weight in weights.items()}

transforms = {
    "face value": lambda w: w,
    "high roll": lambda w: 1 if w >= 5 else 0,
    "odd parity": lambda w: 1 if w % 2 == 1 else 0,
    "squared miss": lambda w: (6 - w) ** 2,
}

def pushforward(P, X):
    pmf = defaultdict(float)
    groups = defaultdict(list)

    for w, prob in P.items():
        x = X(w)
        pmf[x] += prob
        groups[x].append(w)

    pmf = dict(sorted(pmf.items()))
    groups = {x: groups[x] for x in pmf}

    mean_from_outcomes = sum(X(w) * prob for w, prob in P.items())
    mean_from_pmf = sum(x * prob for x, prob in pmf.items())
    variance = sum((x - mean_from_pmf) ** 2 * prob for x, prob in pmf.items())

    assert abs(sum(P.values()) - 1.0) < 1e-12
    assert abs(sum(pmf.values()) - 1.0) < 1e-12
    assert abs(mean_from_outcomes - mean_from_pmf) < 1e-12

    return pmf, groups, mean_from_pmf, variance

P = tilted_die(0.35)

for name, X in transforms.items():
    pmf, groups, mean, variance = pushforward(P, X)
    print(f"\n{name}")
    print("support:", list(pmf))
    print("groups:", groups)
    print("pmf:", {x: round(p, 3) for x, p in pmf.items()})
    print("E[X], Var(X):", round(mean, 3), round(variance, 3))
Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

04

04

Interactive Demo

Use direct manipulation to connect the explanation to a moving system.

ManipulateChange one control and predict the visible response before reveal.Leave with the observed invariant or a repaired model.

Live Concept Demo

Explore Random Variables

The stage is code-native and interactive. Use it to test the explanation against the mechanism.

difficulty 2/5undergraduatecode-aligned
Demo inquiry checkpoint

Manipulate one control and predict the visible change.

01Choose lensTrace a quantity
02ObserveDemo state pending
03GroundName the equation, invariant, or control that explains it.
04CarryNext: Distributions

Choose what to inspect in Random Variables. This shared fallback is an observation guide, not evidence of learning.

Loading interactive demo...

Change the probability tilt over raw die outcomes, then change what XXX measures. Positive tilt favors larger die faces; negative tilt favors smaller die faces.

Before revealing the grouped distribution, use the visible rule and raw probabilities to predict which measured value will collect the most probability mass. The demo hides the support, expectation, variance, and dominant fiber until you commit.

After reveal, compare the winning fiber with the readouts: the same outcome space can produce very different distributions, expectations, and variances depending on the measurement rule.

Section prompt

Copy-only prompts — each action copies a page-grounded prompt to your clipboard. Nothing is sent by this site.

4/4 sections ready

Concept: Random Variables

What is the smallest example that makes Random Variables click without losing the math?

BeforeProbability BasicsNow4/4 sections readyTryManipulate one control and predict the visible change.NextDistributions
Object contextProbability
ConceptLearner lens

Random Variables

What is the smallest example that makes Random Variables click without losing the math?

Mode questionCan I say the mechanism back in one sentence before I reveal anything?

Start with the prediction checkpoint, then compare the reveal to the mental model.

Take this move

Study modes

Keep the object fixed; change the lens.

Route back through the notebook

Carry the same object through intuition, math, code, and demo.

4/4 sections ready
Carry inProbability Basics

Bring the mental model from Probability Basics; this page will reuse it instead of restarting from zero.

Work hereRandom Variables

A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.

Carry outDistributions

The next edge should feel earned: use the demo prediction here before following Distributions.

After The First Pass

Turn the concept into an inspected object.

The lower panels are one second act: keep the object fixed, inspect it visually, check source boundaries, practice transfer, then attach the research question.
ConceptRandom VariablesProbability

Mechanism Storyboard

See the idea move before the page explains it

A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.

Demo notes open01 / Intuition
Editorial probability illustration of raw outcomes flowing through a measurement map into a discrete value distribution.
Prediction lens

Start with the picture, metaphor, or geometric mechanism.

Commit first

Before reading further, choose the kind of change Random Variables should make visible.

Visual Inquiry

Make the image answer a mathematical question

A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.

4/4 stages readyDemo notes connected
Prediction

Which visible object should carry the first intuition?

Commit first

Pick the cue that should make Random Variables easier to reason about before the page gives the answer.

Source Grounding

Canonical references for the mechanism on this page.

Object - ConceptRandom VariablesQuestion

What is the smallest example that makes Random Variables click without losing the math?

concept:probability/random-variables
Boundary

sources: deisenroth-2020-mml

Check

Open the closest source note before trusting the local explanation.

Evidence

1 selected-object source shown first; 1 reference total.

Next move

Audit the claim boundary, then ask from the same selected object.

selected object source · book · 2020Mathematics for Machine LearningDeisenroth, Faisal, and Ong
Located CF editorial boundary

Grounds random variables, expectations, variance, and the bridge from outcomes to numerical features.

Used here as

Mathematics for Machine Learning introduces random variables, distributions, expectations, and variance as the probability vocabulary needed for ML, supporting the page's map-from-outcome...

Caveat

This checks the standard real-valued and finite teaching framing for random variables, induced laws, expectations, and variance, not full measure-theoretic generality or every stochastic-...

Open source

Claim Review

A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.

Object - ConceptRandom VariablesQuestion

What is the smallest example that makes Random Variables click without losing the math?

concept:probability/random-variables
Boundary

sources: deisenroth-2020-mml

Check

Treat every claim as provisional until source support and a local witness agree.

Evidence

1 structured claim check on this concept.

Next move

Run the prediction or practice transfer before asking for a grounded review.

1 CF editorial source-scope review recorded

Publisher-side editorial review is not independent replication. Claims without it still need exact source-support review. 1 reference and 3 local witnesses are available for inspection.

A random variable is a measurable map from raw outcomes to values; pushing probability through that map gives its distribution, and expectations can be computed from either raw outcomes or the induced value distribution.
Used here as

Mathematics for Machine Learning introduces random variables, distributions, expectations, and variance as the probability vocabulary needed for ML, supporting the page's map-from-outcomes and induced-distri...

Local witness
Equation 1
X:(Ω,F)(R,B(R)).X:(\Omega,\mathcal F)\to(\mathbb R,\mathcal B(\mathbb R)).
Equation 2
X1(B)={ωΩ:X(ω)B}F.X^{-1}(B)=\{\omega\in\Omega:X(\omega)\in B\}\in\mathcal F.
Caveat

This checks the standard real-valued and finite teaching framing for random variables, induced laws, expectations, and variance, not full measure-theoretic generality or every stochastic-process setting.

Review stateCF editorial source-scope reviewClaim metadata: source checkedPublisher-side editorial review only; not independent replication. Check caveats and exact source scope.

Checked MML 6.1.2, 6.2, and 6.4.1: MML defines a probability space and target space T, calls a function X:Omega->T a random variable, defines preimages X^-1(S), gives PX(S)=P(X in S)=P(X^-1(S)), and calls PX, equivalently P composed with X^-1, the law/distribution of X. MML also discusses Borel sigma-algebra technicalities and defines expected values by sums/integrals over p(x). The local math/code/demo make the measurable-Borel condition and finite raw-vs-induced-PMF expectation equality explicit.

Reviewer: codex+oracle; reviewed 2026-05-07

Practice notebook

Use the idea, then test it somewhere new

A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.

AttemptNo learning claim inferred
Object - ConceptRandom VariablesQuestion

What is the smallest example that makes Random Variables click without losing the math?

concept:probability/random-variables
Boundary

sources: deisenroth-2020-mml

Check

Use one state from Random Variables to explain what changes, why it changes, and which assumption the explanation needs.

Evidence

No learner move yet; no learning state is inferred.

Next move

Write first, use only the help you need, then try a new case without it.

Explain

Use one state from Random Variables to explain what changes, why it changes, and which assumption the explanation needs.

Hint 1

Reveal when your model needs a nudge.

Hint 2

Reveal when your model needs a nudge.

Hint 3

Reveal when your model needs a nudge.

Grounded object roomClose
Selected object routeAsk from this object; carry one invariant back.sources: deisenroth-2020-mml
  1. ObjectConceptRandom Variables
  2. PredictBefore revealRandom Variables prediction
  3. WitnessCompare codeRandom Variables code witness 1
  4. RoomAsk groundedChecking local snapshot
ConceptRandom VariablesProbability

Research Room

Attach the question to an exact object

Pick the concept, equation, source, code witness, claim, misconception, or demo state before asking for help. The handoff stays grounded to that object.
Next local actionNo local draft saved yet

Open the draft below to save one note and next action in this browser.

conceptProbability

Random Variables

Anchored question

What is the smallest example that makes Random Variables click without losing the math?

Source boundaryInspect source ids: deisenroth-2020-mmlStable content-object key attached
Role lenses for this object

These are fixed, deterministic perspectives derived from the selected object. They do not represent people, community contributions, or independent review.

Learner evidence requestAsk what would make "Random Variables" feel predictable rather than familiar.
Assumption

Source ids deisenroth-2020-mml must support the exact object, not just the surrounding topic.

Source-checking summary

Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion.

Proposed experiment

Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo.

Next action

The learner can state the mechanism in their own words

Evidence4 checks
PredictionChecking carried observation
ActionReady for one action
AILearner handoff ready
Open source object
01PredictionChecking browser-local route memory
02EvidenceChecking for a carried observation
03BoundaryInspect source ids: deisenroth-2020-mml
04Next moveSave one next action
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
Local action draft

This draft stays locally in this browser for concept:probability/random-variables.

No local draft saved.
Evidence to inspect
  • Source ids to inspect: deisenroth-2020-mml
  • Definition, prerequisite, and contrast concept links
  • The equation or code witness that makes the concept operational
  • One demo state that shows the invariant instead of a slogan
What would resolve this
  • The learner can state the mechanism in their own words
  • The learner can name the prerequisite that would repair confusion
  • The learner can predict how the mechanism changes under one perturbation
Object-attached AI handoff

I am working in Continuous Function's research reading room. Object: concept - Random Variables Object key: concept:probability/random-variables Context: Probability Anchor id: concept/concept-notebook/probability/random-variables Open question: What is the smallest example that makes Random Variables click without losing the math? Evidence to inspect: - Source ids to inspect: deisenroth-2020-mml - Definition, prerequisite, and contrast concept links - The equation or code witness that makes the concept operational - One demo state that shows the invariant instead of a slogan Deterministic role lenses for this object: - Boundary: fixed perspectives, not people, community contributions, or independent review - Source-checking summary: Treat this as a mechanism object: connect the definition to one equation, code witness, or demo before broadening the discussion. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Teach/transfer move: Turn the mechanism into one sentence that predicts a neighboring concept. - Assumptions: - Source ids deisenroth-2020-mml must support the exact object, not just the surrounding topic. - The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. - The concept explanation is local atlas prose until checked against its math, code, and source support. - Prerequisite gaps should become a repair route, not a reason to leave the object vague. - Role-lens requests: - Learner: ask for "Ask what would make "Random Variables" feel predictable rather than familiar." | assumption: Source ids deisenroth-2020-mml must support the exact object, not just the surrounding topic. | next action: The learner can state the mechanism in their own words - Researcher: ask for "Source ids to inspect: deisenroth-2020-mml" | assumption: The stable content-object key lets local drafts, prompts, and route memory attach without changing the source page. | next action: The learner can name the prerequisite that would repair confusion - Experimenter: ask for "Choose one variable or condition to perturb before asking for an explanation." | assumption: The concept explanation is local atlas prose until checked against its math, code, and source support. | next action: The learner can predict how the mechanism changes under one perturbation - Professor: ask for "Find the smallest transferable rule a learner could reuse without the AI." | assumption: Prerequisite gaps should become a repair route, not a reason to leave the object vague. | next action: Teach or transfer: Turn the mechanism into one sentence that predicts a neighboring concept. What would resolve this: - The learner can state the mechanism in their own words - The learner can name the prerequisite that would repair confusion - The learner can predict how the mechanism changes under one perturbation Answer as a careful research tutor: stay source-grounded, separate verified evidence from assumptions, name the relevant math objects, and end with one next action. Current deterministic role lens for this object: - Role lens: Learner - Evidence request: Ask what would make "Random Variables" feel predictable rather than familiar. - Assumption to keep visible: Source ids deisenroth-2020-mml must support the exact object, not just the surrounding topic. - Proposed experiment: Ask the learner to perturb one representation, then check whether the same invariant survives in math, code, and demo. - Next action: The learner can state the mechanism in their own words

concept/concept-notebook/probability/random-variables concept:probability/random-variables