Bring the mental model from Probability Basics; this page will reuse it instead of restarting from zero.
Probability
Random Variables
A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.

Concept Structure
Random Variables
Start with the picture, metaphor, or geometric mechanism.
Make the objects explicit and connect them with notation.
Mirror the equations with runnable implementation details.
Manipulate the mechanism and watch the idea respond.
Learning map
Random VariablesConceptual Bridge
What should feel connected as you move through this page.
A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.
The next edge should feel earned: use the demo prediction here before following Distributions.
01
Intuition
Build the mental picture first so the rest of the page has something to attach to.
A tilted die produces one raw outcome, say . What number did you actually measure: the face value , the high-roll indicator , the parity , or the squared miss ?
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:
- = number of heads in 10 coin flips
- = pixel intensity at one location
- = 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 is a rule: once the raw outcome is known, the value is determined.
02
Math
Translate the story into symbols, assumptions, and a derivation you can inspect.
Let be a probability space. The sample space contains raw outcomes , the event collection says which subsets can be assigned probabilities, and assigns probability to those events.
A real-valued random variable is a measurable function
Measurable means that whenever is a Borel set of possible values, the set of raw outcomes that land in is an event:
The distribution, or law, of is the pushforward of through . For any Borel set ,
In the finite discrete case, write as shorthand for the atomic mass . Then all outcomes mapping to the same value get grouped together:
The support of in this finite setting is
The group of outcomes mapping to one value is the fiber over :
The probability mass of that fiber becomes the PMF value .
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:
Variance measures squared spread around that expectation:
When has a density , probabilities and expectations are computed by integration:
A density value is not itself a probability, and not every distribution has an ordinary density. The measure 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 is a random training example and are model parameters, then
is a random variable because the sampled example is uncertain. Training tries to reduce , while a mini-batch computes a noisy estimate:
For independent sampled examples, and . 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.
03
Code
Keep the implementation aligned with the notation so the algorithm is legible.
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))
04
Interactive Demo
Use direct manipulation to connect the explanation to a moving system.
Change the probability tilt over raw die outcomes, then change what 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.
Live Concept Demo
Explore Random Variables
The stage is code-native and interactive. Use it to test the explanation against the mechanism.
Manipulate one control and predict the visible change.
Commit to what Random Variables should make visible before reading the result.
After The First Pass
Turn the concept into an inspected object.
Once the invariant is visible in the intuition, math, code, and demo, use these panels to inspect the mechanism visually, check source support, practice the idea, and attach a grounded research question.
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.

Start with the picture, metaphor, or geometric mechanism.
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.
Which visible object should carry the first intuition?
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.
Grounds random variables, expectations, variance, and the bridge from outcomes to numerical features.
Open sourceClaim Review
A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.
Claims without a substantive review badge still need exact source-support review.
deisenroth-2020-mml
Use equation, code, and demo objects to check whether the source support is operational.
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-distribution framing.
Sources: Mathematics for Machine LearningThis 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.A bounded review summary is present; still 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-07Practice Loop
Try the idea before it explains itself
A random variable is a function from outcomes to numbers; its distribution lets you compute expectations, variances, and likelihoods.
Before touching the demo, predict one visible change that should happen in Random Variables.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
Reveal when your model needs a nudge.
A concrete answer is on the canvas.
The answer names why the claim should hold.
It touches the page context or a neighboring idea.
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.Open the draft below to save one note and next action in this browser.
Random Variables
What is the smallest example that makes Random Variables click without losing the math?
Local action draftNo local draft saved yetExpand only when ready to capture one local next action
This draft stays locally in this browser for concept:probability/random-variables.
- 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
- 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
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 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.
concept/concept-notebook/probability/random-variables
concept:probability/random-variables