Roll two dice. You rarely care which die showed which face; you care about the total, say 7. A classifier looks at a photo and produces a label. A language model produces the ID of the next token. In each case the outcome of a random process is turned into a number, and then we ask: how likely is each number, and how likely is it to be at most 5?
That turning of outcomes into numbers is a random variable, and the tools for describing how likely each number is are the PMF, the density and the CDF. They are the language in which every later probability lesson, and every model that outputs uncertainty, is written.
A random variable is a function
An experiment has a set of possible outcomes, the sample space (P1.D1), and an event is a set of outcomes. Take two fair dice. The outcomes are the 36 pairs , such as . A random variable is a rule that gives every outcome a number. The rule “add the two faces” is one, written for the outcome and then for :
The name is misleading in two ways. A random variable is not random: the rule is fixed, and the same outcome always gets the same number. It is also not a variable in the sense of algebra: it is a function, from outcomes to numbers (P1.A4). The randomness lives in which outcome happens. Once the dice have landed, has a definite value.
Four pieces of notation, all of them standard:
- A capital letter, , is the rule. A lowercase letter, , is one particular number that the rule can produce. Writing for “ takes the value ” is the usual shorthand, and you will see it in every paper.
- is the event made of all outcomes that turns into . In set-builder notation (P1.A4) it is . For the sum of two dice, is the set of the six outcomes , , , , and , out of 36.
- is short for the probability of that event: .
- is the event of all outcomes with , and is its probability. This one gets its own name below, the CDF.
The probabilities themselves come from the rules of P1.D1: they are at least 0, and the whole sample space has probability 1. A random variable adds nothing new to those rules. It only gives us numbers to ask questions about.
A random variable does not have to be a sum. The number on one die is a random variable (, the identity). A coin turned into 1 for heads and 0 for tails is one. So is the class label of a randomly drawn image, the height of a randomly chosen person, or the output of a model whose input or internal sampling is random: a function of a random variable is again a random variable, as the section on functions below shows.
Discrete or continuous
A random variable is discrete if its possible values can be listed one after another, even if the list never ends: the faces 1 to 6, the class IDs , the token IDs of a vocabulary, the number of emails you get in an hour (). It is continuous if it can take any value in an interval of the real line, so there is no list: a waiting time, a temperature, the noise added to a measurement.
Real data is always recorded with finite precision, so the choice is a modelling decision. A pixel stored as a whole number from 0 to 255 is discrete, but when the numbers are fine-grained it is often convenient to model it as continuous.
Some variables are mixed: part of the probability sits on single values, and the rest is spread out. Take a standard Gaussian variable and apply ReLU (P4.4), . By symmetry , so , a lump of probability on the single value 0, while the positive values of are spread over a continuous range. Neither a pure PMF nor a pure density describes , but the CDF does: for and for , which is the Gaussian CDF value (0.5 at ). So jumps from 0 to at 0 and then rises smoothly. Mixed variables are the exception; the rest of the lesson treats the two pure cases.
The PMF: probability on each value
For a discrete , the probability mass function (PMF) gives the probability of each possible value:
The subscript says which variable the PMF belongs to, and is dropped when it is clear. Two rules make a function a valid PMF: it is never negative, and it adds up to 1 over all possible values,
Probability sits on the points like lumps of clay, with a total mass of 1; hence “mass”. The analogy is a fair picture of a PMF, and it stops working for continuous variables, where no single point carries any mass.
One fair die. for . The six probabilities add up to 1.
The sum of two dice. Count the outcomes of the 36 that give each total. The counts for are , which is outcomes out of 36. So : the single most likely total, 7, has probability , and 2 and 12 have each. The counts add up to 36.
The probability of an event is the sum of the PMF over its values. For the two dice: , and the even totals have .
Models output PMFs. A classifier with three classes turns three scores (logits) into probabilities with the softmax function (P3.A8). For the scores the probabilities are : nonnegative, adding up to 1. This is the model’s predicted PMF over the label. A language model does the same over a vocabulary of token IDs, with numbers adding to 1 (P10.A1).
A PMF value is a probability, so it can never be above 1.
The CDF of a discrete variable: a staircase
Asking “what is ?” for every gives a function with its own name, the cumulative distribution function (CDF):
It is defined for every real number , not only for possible values, and for every kind of random variable. It is the one description that works for discrete, continuous and mixed variables alike.
For one die: (no face is at most 0.5), , (the faces 1 and 2), , and . Plot it and you see a staircase: flat between possible values, with a jump of height at each face. In general:
- The jump at a possible value equals , because , where is the value just to the left of .
- At a jump the CDF takes the upper value. already counts the face 3, since the event is “at most 3”. A function that behaves like this is called right-continuous: approaching from the right, the values settle on . Plots draw a closed dot on the top of the step and an open dot at the bottom.
- Between possible values the CDF is flat: no new probability is added.
For every random variable, discrete or not, the CDF has four properties:
- , since it is a probability.
- It never decreases: if then is inside , so (more outcomes, at least as much probability).
- as and as .
- It is right-continuous.
Intervals. The event splits into the two pieces and that do not overlap (for ). Their probabilities add, so
For a die, (the faces 3, 4 and 5). The ends of the interval matter for a discrete variable: also counts the face 2, so it is , not . For the sum of two dice, and , so .
Continuous variables: probability 0 at every point
Now let be continuous. Say it is equally likely to be anywhere in . There are infinitely many possible values, all equally likely, and the probabilities must add up to 1. If each value had the same positive probability, the total would be infinite, so each value gets probability 0. (A pile of probability on single values is possible for other variables, such as token IDs, counts, or the point mass of the ReLU example above; it is the spreading over a whole interval that forces 0 at each point.) The consequence is surprising but correct:
This does not mean that is impossible: certainly lands somewhere. Think of a dart thrown at a line: any exact point has probability 0 of being hit, yet the dart lands on some point. Probability zero for one point is different from impossible. What can be positive is the probability of an interval.
P1.C9 solved this with a probability density function (PDF) . The probability of an interval is the area under the density over it:
Two examples from P1.C9:
- Uniform on : on and 0 elsewhere. The total area is , and .
- Exponential: for , a model of a waiting time. The areas are , and , which add up to 1.
Because single points carry no probability, the ends of an interval do not matter for a continuous variable: , and the two mixed versions are all equal. For a discrete variable they are not, as the die showed.
A density is not a probability. Its height is probability per unit of , and this has three consequences.
- It can exceed 1. The uniform density on has height : the area is , which is all that is required. Then .
- It has units. If is a time in seconds, is per second. The exponential density at 1 second is per second. Measure the same waiting time in milliseconds and the same point has density per millisecond, because a millisecond is a thousand times shorter. The probabilities do not change: an area is (per second) seconds, with the units cancelling.
- Over a tiny interval, probability is about height times width: for small . For the exponential density, , and the estimate is almost the same.
A density value is therefore never the probability of a point. To get a probability from a density, integrate over an interval.
The CDF of a continuous variable, and the derivative link
The CDF is defined the same way, , which for a density is the area up to :
This is exactly the accumulation function of P1.C9, and its first half of the fundamental theorem gives
The density is the slope of the CDF, and the CDF is the running area under the density. For the exponential: for , and . At the slope is , the same as the height of the density. For the uniform density on : on , a straight ramp of slope from 0 to 1.
A continuous CDF has no jumps, because every single point has probability 0. The same four properties hold: it goes from 0 up to 1 and never decreases. The correspondence between the two pictures is worth memorising:
- Where the CDF is steep, the density is tall: a lot of probability per unit of .
- Where the CDF is flat, the density is 0: no probability is added.
- For a discrete variable, the CDF jumps where the PMF has a bar, and the jump is as tall as the bar.
The standard Gaussian density is (P1.D3). Its CDF has no formula built from the usual elementary functions, as P1.C9 noted for the area under , so it is computed numerically through the error function : . The values to remember are , and . The sigmoid of P1.A5 is also a CDF, that of the standard logistic distribution (P1.C9): and .
The two plots, linked
In the widget, the top plot shows the PMF (bars) or the density (curve), and the bottom plot shows the CDF. They describe the same variable. Drag the point on either plot, or use the keyboard or the sliders: the shaded probability at the top equals the height of the dot at the bottom.
Things to try, with the numbers you should see:
- Fair die, one threshold. Set : three bars turn blue and . The status line says that 3 is a possible value, so the CDF has jumped here and includes the bar at 3, with just to the left. Move to : the readout is and , since 2.75 is not a face; the CDF is flat between 2 and 3.
- Sum of two dice. At the readout is , which includes a jump of from . Switch to “Interval a to b” with and : . The counted values are (not 4).
- Uniform on . The top plot is a tall rectangle with height 2, above the 1 mark on the axis, and the status line says the height is allowed to be above 1. At the area is , and so is . The CDF is a ramp that climbs from 0 to 1 over a width of only 0.5.
- Exponential. The density is tallest at 0, and the CDF is steepest there. Take and : , which is when computed from the unrounded values, the number from P1.C9.
- Gaussian. With and the shaded area is . With and it is . Move to the far tail: the CDF gets close to 1 but never reaches it.
Using the CDF: intervals, tails and quantiles
Because it works for every kind of variable, the CDF is the handiest object for questions about “at most” and “between”:
A quantile turns the question around. Given a probability , find the value with . The -quantile is the median: half of the probability lies below it. The -quantile is the 90th percentile. For a continuous variable whose CDF is strictly increasing, the quantile is the inverse function, : look at height on the CDF and read the value across.
- Exponential: solving gives . The median is and the 90th percentile is .
- Standard Gaussian: the median is (the density is symmetric), and , so 1.96 is the 97.5th percentile.
For a discrete variable the staircase has no exact inverse (it jumps over most heights), so a common convention takes the smallest with . For a die and : is too small and is enough, so the 0.9-quantile is 6. Conventions differ between books and libraries, so check which one a tool uses. Percentiles and the median as summaries of data come back in P1.D12.
Functions of a random variable
If is a random variable and is a function, then is a random variable too: the sum of two dice is a function of the pair of dice, and a model’s output is a function of a random input. Its distribution is not found by applying to the PMF or density; it has to be worked out.
Discrete case: add up the probabilities that land on the same value. Let be one die and . The faces give . So , (the faces 2 and 4), (the faces 1 and 5) and . The four values add up to 1. When sends two different to the same , their probabilities are added.
Continuous case: go through the CDF. Let be uniform on and . For ,
because is uniform, so the CDF of at is . Differentiating gives the density on . This is not a uniform density: , so half of the probability sits in the lowest quarter of the range, and the density is tall near 0 (it grows without bound there, yet its total area is still 1). Squaring squeezes values toward 0.
Stretching also changes the height. If is uniform on and , then is uniform on with density : the same probability is spread over twice the width, so the height halves. A density is probability per unit, and a change of variable changes the unit. The Go-deeper box below gives the rule, which is the one-dimensional case of the Jacobian factor of P1.C7.
Go deeper How a density changes when the variable is transformed
Let where is differentiable with everywhere on the values of , so is strictly increasing and has an inverse. (Strictly increasing alone is not enough: is strictly increasing but has .) Then . Differentiating with the chain rule (P1.C3), with , gives . Rearranged:
This is the formula of P1.C7, , with a Jacobian whose determinant is . The absolute value makes it work for a strictly decreasing as well. The factor says how much stretches a small interval around , and density per unit falls by that factor when the interval is stretched.
Check it for with uniform on : , and , so . Check it for on (increasing there), with : , the density found above from the CDF. If is not one-to-one (for instance on negative and positive ), add the contributions of all with at which : .
Go deeper Inverse-CDF sampling: random numbers with any CDF
Computers produce numbers uniform on , for which . Suppose is a continuous CDF that is strictly increasing, and let . Then , so has exactly the CDF . To sample from a distribution, push uniform numbers through the inverse of its CDF.
For the exponential, . For a discrete variable the same idea works with the staircase: for in the range return . For a die and : , so the sample is 3. Each face is returned for a stretch of values of length , which is its probability. The second code cell below tries it on the exponential. P1.D9 develops sampling and when other methods are needed (when has no formula, as for the Gaussian).
Go deeper What the formal definition requires
Formally, a random variable is a function with one technical requirement: for every real , the set must be an event, one that has a probability. This is what makes defined for every . In practice every function you will meet satisfies it.
Right-continuity of follows from the countable version of the third rule of P1.D1 (countable additivity): the events shrink toward as grows, and probabilities of shrinking events converge to the probability of the limit event. Left limits behave differently: can be smaller than , and the gap is , which is the jump. A standard theorem says the four properties (never decreasing, limits 0 and 1, right-continuous) are all that a function needs to be the CDF of some random variable.
A density is one way to have a continuous CDF, and the usual way in machine learning. A continuous CDF does not always have a density (the Cantor function is the textbook counterexample), but such cases are rare in practice and are not needed in this course.
Several random variables
Everything so far is about one random variable. Two dice give two variables, and , and their sum is a third. A data point with features is random variables at once, a random vector. How they relate, including how knowing one changes what you expect of the other, is the subject of P1.D5 (joint, marginal and conditional probability).
Models as random variables
The same ideas explain how learning systems use probability.
- Classification. The label is a discrete random variable. The model’s softmax output is its predicted PMF for the label (P3.A8). Training pushes the probability of the true label up.
- Language models. The next token ID is a discrete random variable whose PMF has one entry per vocabulary item (P10.A1). Generating text means drawing from that PMF (P1.D9, P10.A5).
- Regression. A common model says , where the noise is a continuous random variable with a Gaussian density (P3.A2, P1.D3). The target is then random too, because it is a function of a random variable.
- Likelihood. Given data, the likelihood multiplies the PMF or density at each observed value. If a die shows , a fair die gives . If waiting times and are modelled by the exponential density, the product is . A product of densities is not a probability (a density value is a height), but it can be compared between models for the same data, and that is how maximum likelihood chooses (P1.D10).
Intuition
A random variable is a measuring device pointed at a random experiment: it reads each outcome as a number. The PMF says how much probability sits at each reading. The CDF is a running total: walk along the number line from the far left and keep adding probability, and the CDF is the total so far. A discrete variable adds it in lumps (a staircase); a continuous one adds it smoothly (a ramp or an S-curve). The density is how fast the running total grows. The analogy of probability as clay or water breaks in one place: the total is always exactly 1, and a point of a continuous variable holds no clay at all, only a rate of piling up.
Math
; .
Discrete: , , .
CDF: ; nondecreasing, right-continuous, , .
Continuous with density: , where is continuous, , , (no upper bound on ).
Quantile: for a strictly increasing continuous ; in general .
Function of a variable :
- Discrete: .
- Continuous: .
- Strictly monotone with : .
Code
import numpy as np
# two dice: x = 2..12
counts = [1, 2, 3, 4, 5, 6,
5, 4, 3, 2, 1]
pmf = np.array(counts) / 36
cdf = np.cumsum(pmf)
print(cdf[5]) # F(7) = 0.5833...
# discrete quantile for q = 0.9:
# the smallest x with F(x) >= q
print(2 + np.searchsorted(cdf, 0.9))
# prints 10np.cumsum turns a PMF into a CDF. For a continuous variable, the CDF of a Gaussian is 0.5 * (1 + math.erf(x / math.sqrt(2))) with the standard library’s math.erf.
Try it: PMFs, CDFs and densities in code
The first cell builds the PMF of the sum of two dice by counting, turns it into a CDF, checks the interval rule, finds the PMF of a function of , and compares with a simulation. Predict before you run it. The second cell checks that the slope of the exponential CDF is the density, computes Gaussian probabilities with math.erf, finds quantiles, and samples by the inverse CDF.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: change the code to three dice (add a third loop variable and use 216 outcomes). What is ? Compare with the number of ways to roll 10 with three dice, which you can count by hand.
Runs real Python in your browser. First run downloads about 6 MB (once; your browser keeps it).
Challenge: use the inverse-CDF idea for the uniform density on () and check that the share of samples at most is about .
Common mistakes
Check your understanding
A fair die is rolled. What is ?
The faces 2, 3, 4 and 5 all count, which is four faces out of six. The value is , which is and leaves out the face 2. The value is and also counts the face 1, while is , the probability of at most 2.
A random variable has the density for and elsewhere. Which statement is correct?
What a density needs is a nonnegative function with total area 1, and this one has area . The height is probability per unit of , so it can exceed 1. The probability of the exact value 0.1 is 0, not 4, because a height is not a probability. Dividing by 4 would make the total area , which breaks the rule.
Which of these functions cannot be the CDF of any random variable?
A CDF never decreases and goes from 0 up to 1, but this function starts at 1 and falls to 0. The step from 0 to 1 at is the CDF of a variable that always equals 1. The ramp from 0 to 1 is the uniform CDF, and is the exponential CDF from this lesson.
For a standard Gaussian variable the density at 1 is . What is ?
For a continuous variable every exact value has probability 0. The height is probability per unit of : a small interval of width around 1 has probability about , and that goes to 0 as shrinks. The probability is exactly 0, not a small positive number, and the variance does not change the fact that single points have probability 0.
Let be uniform on and . What is ?
The event is the event , which has probability for a uniform . The value would be right only if itself were uniform, which it is not, because squaring squeezes values toward 0. The value squares the probability instead of the threshold, and has no basis in this problem.
Exercises
- Two fair dice are summed. Find and .
Show answer
There are 4 ways to get 9, so . The ways to get 9, 10, 11 and 12 are , so . - For one fair die, find , and .
Show answer
, (the faces 1 and 2), . - For one fair die, find and , and say which of them equals .
Show answer
and . The first one equals , because the possible values below 5 are the ones up to 4. - Is , , a valid PMF? If not, fix it by changing one number.
Show answer
No: the numbers add up to , not 1. Changing to gives a valid PMF. - is uniform on . Give its density, its CDF on , and its median.
Show answer
The density is on (area ), and . . The median solves , so it is 2. - For the exponential density (), find .
Show answer
. - Show that on (and 0 elsewhere) is a valid density. Find its CDF on and . Where is the density above 1?
Show answer
It is nonnegative and . The CDF is on , and confirms it. . The density is above 1 for , up to 3 at . - For the standard Gaussian, . Find , and .
Show answer
. By symmetry as well. So . - is uniform on and . Find the CDF and the density of .
Show answer
for . The density is the derivative, on : is uniform on . - Find the 75th percentile of the uniform density on and of the exponential density.
Show answer
Uniform: gives . Exponential: . - Code: in the first cell, find the PMF of the largest of two dice, . What is ?
Show answer
Count pairs whose maximum is : of the 36, so and .
Next: P1.D3 gathers the common named distributions, with their PMFs or densities and CDFs. P1.D4 summarises a distribution with its expected value and variance, which are sums over the PMF or integrals against the density. P1.D5 puts several random variables together, and P1.D9 shows how to draw samples from a distribution.