Random Variables

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

Introductory · Undergraduate mathematics · about 14 minutes

Reading map and next steps

Intuition

The idea in plain words, before the symbols.

A tilted die produces one raw outcome, say ω=5\omega=5. What number did you actually measure: the face value 55, the high-roll indicator 11, the parity 11, or the squared miss (6−5)2=1(6-5)^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:

  • XX = number of heads in 10 coin flips
  • YY = pixel intensity at one location
  • LL = 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 XX is a rule: once the raw outcome ω\omega is known, the value X(ω)X(\omega) is determined.

Study prompts for this section: Intuition
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Mathematics

Definitions, assumptions and the derivation.

Let (Ω,F,P)(\Omega,\mathcal F,P) be a probability space. The sample space Ω\Omega contains raw outcomes ω\omega, the event collection F\mathcal F says which subsets can be assigned probabilities, and PP 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)).

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

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

The distribution, or law, of XX is the pushforward of PP through XX. For any Borel set B∈B(R)B\in\mathcal B(\mathbb R),

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

In the finite discrete case, write P(ω)P(\omega) as shorthand for the atomic mass P({ω})P(\{\omega\}). 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).

The support of XX in this finite setting is

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

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

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

The probability mass of that fiber becomes the PMF value pX(x)p_X(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(ω)=∑xx pX(x).\mathbb{E}[X] = \sum_{\omega \in \Omega} X(\omega)P(\omega) = \sum_x x\,p_X(x).

Variance measures squared spread around that expectation:

Var⁡(X)=E[(X−E[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.

When XX has a density fXf_X, probabilities and expectations are computed by integration:

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

A density value is not itself a probability, and not every distribution has an ordinary density. The measure PXP_X 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 ZZ is a random training example and θ\theta are model parameters, then

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

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

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

For independent sampled examples, E[L^m]=E[L]\mathbb E[\hat L_m]=\mathbb E[L] and Var⁡(L^m)=Var⁡(L)/m\operatorname{Var}(\hat L_m)=\operatorname{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.

Study prompts for this section: Mathematics
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Code

The same calculation as runnable code, in the notation of the derivation.

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))
Study prompts for this section: Code
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

Demo

Change an input, predict the result, and see which quantities respond.

ExploreChange one control at a time and name what responds.An optional observation guide follows the demo.

Explore Random Variables

Loading the interactive demo…

Observation guide

Optional and ungraded. Opening a guide saves nothing.

Choose what to inspect in Random Variables, then open its guide.

Change the probability tilt over raw die outcomes, then change what XX 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.

Study prompts for this section: Demo
Study prompts

Each button copies a prompt about this section to your clipboard, for an AI assistant you already use. Nothing is sent by this site.

In focus

Concept: Random Variables

What is the smallest example of Random Variables you can work through by hand, and what does it show?

BeforeProbability BasicsNextDistributions
DetailsProbability

After the first pass

Go deeper

Optional material for a second reading. Sources are always shown; the other panels open from their headings or from these links, and closing one keeps what you wrote or revealed.
What to look for in each sectionChoose a section and what you expect to see in it, then read short advice.

Section by section

Choose what to look for in each section

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

Choose what to look for (no demo yet)01 / Intuition
Illustration of raw outcomes flowing through a measurement map into a discrete value distribution.
What to look for

Start with the picture, metaphor, or geometric mechanism.

Choose first

Choose what you expect to see in this section of Random Variables.

Questions to ask of the pictureChoose a part of the picture and what you expect, then read short advice.

Looking at the picture

Questions to ask of the picture

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

4 of 4 sections writtenNo live demo yet
Question

Which part of the picture should you look at first?

Choose first

Pick the part of the picture you expect to explain Random Variables.

Sources

References for this page

A reference shows where an idea comes from; it does not vouch for every step on this page.
book · 2020Mathematics for Machine LearningDeisenroth, Faisal, and Ong
Why it is cited

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

Open source
book · 1933Grundbegriffe der WahrscheinlichkeitsrechnungKolmogorov
Why it is cited

Springer; in English as Foundations of the Theory of Probability (Chelsea, 1950). Defines a random variable as a measurable function of the outcome and its distribution as the probability it induces on values.

Open source
book · 2019Introduction to Probability (2nd ed.)Blitzstein and Hwang
Why it is cited

Chapman & Hall/CRC. Chapters 3 and 4 cover random variables as functions of outcomes, their distributions, expectation and variance.

Open source
What each claim rests on1 claim, each with its sources, where it appears on this page, and its caveats.

Claims and sources

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

Checked against the cited passages

The checks were made by this site, not by an independent reviewer.

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.
What the sources support

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...

Where to see it on this page
Equation 1
X:(Ω,F)→(R,B(R)).X:(\Omega,\mathcal F)\to(\mathbb R,\mathcal B(\mathbb R)).
Equation 2
X−1(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.

StatusChecked against the cited passages.

MML sections 6.1.2, 6.2 and 6.4.1 define a probability space and target space T, call a function X:Omega->T a random variable, define preimages X^-1(S), give PX(S)=P(X in S)=P(X^-1(S)), and call PX (P composed with X^-1) the law or distribution of X. MML also covers Borel sigma-algebra technicalities and defines expectations by sums or integrals over p(x). The page's equations, code and demo state the measurability condition and show, for a finite example, equal expectations from raw outcomes and the induced PMF.

Explain it without the pageWrite your own explanation before asking for feedback. Your draft and any hints stay while this page is open.

Practice · Random Variables

Try the idea in your own words

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

Concept · Selected for practice

Random Variables

What it rests on: Sources: Mathematics for Machine Learning; Grundbegriffe der Wahrscheinlichkeitsrechnung; Introduction to Probability (2nd ed.)

Context and links
Choose a task

Explain the mechanism

For Random Variables: What is the smallest example of Random Variables you can work through by hand, and what does it show? Explain your answer, including what changes, why, and which assumption matters.

No answer yet

A rough first thought is enough. Your draft stays when you change tasks.

Your draft stays on this page and is cleared when you leave or reload.

A little help · Explain

Open one hint at a time. These are suggestions, not your answer or a grade.

0 of 3 hints shown for this question.

    Clearing your answer keeps this help record. Outside help is your own report; this page cannot check it.

    Where am I stuck? (optional)
    Your own description, not an automatic diagnosis

    Choose one, or leave this unspecified. Select it again to clear it.

    Take your draft to a feedback conversation

    No AI feedback runs here. You can copy a prompt to use elsewhere; nothing is sent automatically. Review the text before sharing, and leave out private information.

    Write an attempt before copying a feedback prompt.

    A draft, or an AI reply to it, is not a test of what you have learned. To check that, try a different case later without help.

    Ask about this pagePick one item on this page and copy a prompt about it into an AI assistant you already use. Notes you write here stay in this browser.
    Ask about this pageClose
    ConceptRandom VariablesSources: Mathematics for Machine Learning; Grundbegriffe der Wahrscheinlichkeitsrechnung; Introduction to Probability (2nd ed.)assert abs(sum(P.values()) - 1.0) < 1e-12

    Your question

    Choose what your question is about

    Pick the idea, equation, source, code, claim, misconception or demo state you want to ask about. The prompt you copy includes it, so the answer can stay on that item.
    Next local actionNo local draft saved yet

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

    conceptProbability

    Random Variables

    Starting question

    What is the smallest example of Random Variables you can work through by hand, and what does it show?

    SourcesCheck the 3 cited sources listed under Sources.Notes can be saved for this item
    Points of view on this item

    Fixed prompts generated from this item. They are not comments from people or independent reviews.

    Learner’s first stepAsk what would make "Random Variables" feel predictable rather than familiar.
    Assumption

    The 3 cited sources must support this exact item, not just the surrounding topic.

    Source-checking summary

    Connect the definition to one equation, piece of code or demo before widening the discussion.

    Proposed experiment

    Change one input, then check that the same relationship holds in the mathematics, the code and the demo.

    Next action

    You can state the mechanism in your own words

    Evidence4 checks
    ObservationChecking for a saved observation
    ActionReady for one action
    PromptLearner prompt ready to copy
    Go to this item
    01ObservationChecking what this browser has saved
    02EvidenceChecking for a saved observation
    03SourcesCheck the 3 cited sources listed under Sources.
    04Next stepSave one next action
    Local action draftNo local draft saved yetOpen when you are ready to write one next action
    Local action draft

    This draft stays in this browser and is attached to this item only.

    No local draft saved.
    Evidence to inspect
    • What the 3 cited sources say about this exact item
    • The definition, its prerequisites, and a contrasting concept
    • The equation or code that makes the concept concrete
    • One demo state that shows what stays the same as the inputs change
    What would resolve this
    • You can state the mechanism in your own words
    • You can name the prerequisite that would clear up the confusion
    • You can predict how the result changes when one input changes
    Reference idconcept/concept-notebook/probability/random-variables concept:probability/random-variables