Probability and Statistics · Chapter 3

Chapter 3
Probability

Lectures 5–8 · the language of uncertainty, how to reason with it, and how it goes wrong

Cartoon: a positive testA worried person holds a test result and says: The test is 99% accurate and I tested positive, so I am 99% likely to have it! A second person, hand on chin, replies: 99% of what, though? 99% accurate, I testedpositive... so I'm 99%likely to have it!99% of what,though?
Pr(positive | ill) is not Pr(ill | positive)

You use probability every day without calling it that. "70% chance of rain." "One in a billion chance of a random DNA match." "This email is probably spam." "If I take the express I'll probably make it." Each is a statement about something uncertain, and each guides a decision: take an umbrella, convict or acquit, delete the email, run for the train.

Chapter 1 drew the map of the course: probability reasons forwards, from a mechanism to the data it produces. Before we can reason backwards from data to mechanisms (inference), we need a precise language for uncertainty. This chapter builds it. The rules turn out to be few and simple. The trouble is that human intuition about probability is famously bad, and some of the mistakes it leads to have sent innocent people to prison. So alongside the rules, we'll keep meeting situations where your gut says one thing and the mathematics says another, and you'll learn to trust the mathematics.

Probability serves both of the course's goals, in opposite directions. Reasoning forwards, from a known mechanism to the data it will produce, is prediction: if a test is 90% sensitive, gives false alarms for 9% of healthy people, and the disease affects 1% of people, how many positive tests should a clinic expect? Reasoning backwards, from observed data to the mechanism that produced them, is inference: given that this patient tested positive, how likely is it that she has the disease? Most of this chapter builds the forward machinery; Section 3.6 then shows how Bayes' theorem runs it in reverse, and that reversal is the seed from which all of statistical inference grows.

Here is the route through the chapter.

Think About It: Test Your Intuition First

Before reading on, write down quick answers to these three questions. Don't calculate; just guess. You'll meet each one properly later in the chapter, and it's worth knowing how good your intuition is before you start.

  1. How many people do you need in a room for it to be more likely than not that two of them share a birthday?
  2. A disease affects 1 in 100 people. A test for it is 90% accurate for people who have it, and gives false alarms for only 9% of people who don't. You test positive. Roughly how likely is it that you have the disease?
  3. On a game show you pick one of three doors; the host, who knows where the prize is, opens another door to show it's empty, and offers you a switch. Does switching help?

The answers are 23 people (Example 3.9), about 9% (Example 3.18), and yes: switching doubles your chance (Example 3.21). If you got all three right without having seen them before, you're very unusual. Most people, including most doctors for question 2, get them badly wrong. That's not a failing of intelligence; it's a sign that probability needs to be calculated, not felt.

Lecture 5 — What probability means and its rules

3.1 What does probability mean?

Three ways to read a probability

What does it mean to say a coin lands heads with probability 12? People have given three different answers.

  1. Equally likely outcomes (classical). There are two faces and nothing to favour either, so each gets half. This works for coins, dice and lotteries, where symmetry tells us the outcomes are equally likely. It doesn't tell us the probability that a drug works or that it rains.
  2. Long-run frequency (frequentist). Flip the coin many, many times: the fraction of heads settles down to 12. A probability is the fraction of the time something happens in a long run of repetitions. This is how a casino, an insurer, or a lab estimating a test's error rate thinks.
  3. Degree of belief (Bayesian). A probability measures how strongly a reasonable person should believe something, given what they know. This makes sense even for one-off events: "the probability that this suspect left this fingerprint", "the probability that this vaccine works".

The three interpretations disagree about what probability is, but they agree on the rules probability must follow. That's what makes probability so useful: the same rules serve the casino, the scientist and the juror.

Here is the long-run idea in action. Toss a coin over and over, and track the fraction of heads.

Watch the Law of Large Numbers happen

Set the true probability of heads, then toss. The line tracks the running proportion of heads after each toss; the dashed line is the true probability. Early on the line jumps around. With many tosses it settles down. Press new run a few times and compare how different the early paths are.

Running proportion of heads plotted against the number of tosses on a logarithmic axis…Running proportion of heads plotted against the number of tosses on a logarithmic axis, with a dashed line at the true probability.

Early on the fraction swings wildly; after hundreds of tosses it barely moves. This settling-down is called the Law of Large Numbers. We'll state it precisely and prove it in Chapter 7; for now, it justifies estimating a probability by a long-run fraction.

Definition: Probability as Long-Run Frequency (Informal)

If an experiment can be repeated independently under the same conditions, the probability of an event is the value that the fraction of repetitions in which the event occurs settles down to as the number of repetitions grows.

Example 3.1: Rolling a Die by Computer ★ lecture example

A fair die has six equally likely faces, so the classical probability of rolling a six is 16≈0.167. Use R to roll a die 10, 100, 1,000 and 100,000 times, and compare the fraction of sixes with 16.

sample(1:6, n, replace = TRUE) rolls a fair die n times: it draws from the numbers 1 to 6, putting each one back before the next draw. Comparing with == 6 gives TRUE for each six, and mean() of a TRUE/FALSE vector is the fraction of TRUEs.

R
set.seed(3)
for (n in c(10, 100, 1000, 100000)) {
  rolls <- sample(1:6, n, replace = TRUE)
  cat(format(n, big.mark = ",", scientific = FALSE), "rolls: fraction of sixes =", mean(rolls == 6), "\n")
}
output
10 rolls: fraction of sixes = 0 
100 rolls: fraction of sixes = 0.15 
1,000 rolls: fraction of sixes = 0.174 
100,000 rolls: fraction of sixes = 0.16699 

With 10 rolls the fraction can be far from 16. With 100,000 rolls it's within a fraction of a percentage point. Notice that the error shrinks as n grows, but not in proportion: 100 times as many rolls doesn't make the error 100 times smaller. Chapter 7 shows that it shrinks roughly like 1/n, so 100 times the data buys about 10 times the precision.

A plot of the running fraction of sixes in one long sequence of rolls shows the settling-down directly. The horizontal axis is on a log scale, so that early and late rolls both show up:

R
set.seed(6)
rolls <- sample(1:6, 10000, replace = TRUE)
running <- cumsum(rolls == 6) / seq_along(rolls)
ggplot(data.frame(n = seq_along(rolls), running), aes(n, running)) +
  geom_line() +
  geom_hline(yintercept = 1/6, linetype = "dashed") +
  scale_x_log10() +
  labs(x = "number of rolls (log scale)", y = "fraction of sixes")
Line plot of the fraction of sixes after each roll, for 10,000 simulated rolls, with the…Line plot of the fraction of sixes after each roll, for 10,000 simulated rolls, with the number of rolls on a logarithmic axis from 1 to 10,000. The line swings between 0 and 0.25 in the first few dozen rolls, then settles close to a dashed horizontal line at one sixth. 0.00 0.05 0.10 0.15 0.20 0.25 1 10 100 1000 10000 number of rolls (log scale) fraction of sixes

Empirical probability: probabilities from data

For a die we know the probability in advance. Most of the time we don't. What is the probability that a randomly chosen eruption of Old Faithful lasts more than 3 minutes? That a hospital patient with these symptoms needs intensive care? That a new email is spam? Nobody can work these out from symmetry. Instead, we look at what happened in the past and count.

Definition: Empirical Probability

Suppose an experiment has been observed n times, and event A happened in nA of them. The empirical probability (or relative frequency) of A is Pr̂(A)=nAn=number of times A happenednumber of observations. The "hat" on Pr̂ is a reminder that this is an estimate of the true probability Pr(A), computed from data.

The Law of Large Numbers is what makes empirical probabilities worth computing: if the observations are independent repetitions of the same experiment, then as n grows, Pr̂(A) settles down to the true Pr(A). The empirical probability is the statistic; the true probability is the parameter (Section 1.3).

Example 3.2: Estimating a Probability from Old Faithful ★ lecture example

Using the 272 eruptions in faithful, estimate the probability that an eruption lasts more than 3 minutes. How much would your estimate have differed if you had only seen the first 20 eruptions? Plot the estimate as the eruptions accumulate.

Reading the problem. The "experiment" is one eruption. The event is A = "lasts more than 3 minutes". We count how many of the 272 eruptions are in A.

R
e <- faithful$eruptions
sum(e > 3)              # n_A: eruptions longer than 3 minutes
length(e)               # n
mean(e > 3)             # empirical probability n_A / n
mean(e[1:20] > 3)       # using only the first 20 eruptions
output
[1] 175
[1] 272
[1] 0.6433824
[1] 0.55

So Pr̂(longer than 3 minutes)=175272≈0.643. From the first 20 eruptions alone, the estimate would have been 11/20=0.55, quite a bit lower. To see how the estimate settles down, compute it after each new eruption: the running fraction after k eruptions is the number of long eruptions among the first k, divided by k. R's cumsum() gives running totals:

R
running <- cumsum(e > 3) / seq_along(e)
ggplot(data.frame(k = seq_along(e), running), aes(k, running)) +
  geom_line() +
  geom_hline(yintercept = mean(e > 3), linetype = "dashed") +
  labs(x = "number of eruptions observed", y = "fraction over 3 min")
Line plot of the running fraction of Old Faithful eruptions longer than 3 minutes…Line plot of the running fraction of Old Faithful eruptions longer than 3 minutes, against the number of eruptions observed, from 1 to 272. The line jumps around between about 0.5 and 1 for the first 20 or so eruptions, then settles, staying between about 0.6 and 0.67 after 100 eruptions and ending at 0.643, marked by a dashed horizontal line. 0.5 0.6 0.7 0.8 0.9 1.0 0 100 200 number of eruptions observed fraction over 3 min

This is the Law of Large Numbers on real data: early estimates jump about, later ones barely move.

A critical caveat. The Law of Large Numbers needs independent repetitions of the same experiment. Eruptions are not quite independent (a long eruption tends to follow a short one, as you can check with table(head(e > 3, -1), tail(e > 3, -1))), and the geyser's behaviour changes slowly over the years. So 0.643 estimates the probability for Old Faithful during the period these data were collected. An empirical probability is only as good as the assumption that the future works like the past (Chapter 1's chicken).

Example 3.3: What Does "70% Chance of Rain" Mean?

A weather forecast says there is a 70% chance of rain in Manhattan tomorrow. Explain what this means in long-run terms, and how you could check whether a forecaster's probabilities can be trusted.

Tomorrow happens only once, so we can't repeat it. But we can look at all the days on which this forecaster said "70%", and compute the empirical probability of rain on those days. If the forecasts are good, it should have rained on about 70% of them, on about 30% of the days they said "30%", and so on. A forecaster whose probabilities pass this test is called well calibrated.

US National Weather Service forecasts are well calibrated in this sense, and checking calibration is exactly how forecasting services (and, these days, machine learning models) are evaluated. Note what a 70% forecast does not mean: it doesn't mean it will rain for 70% of the day, or over 70% of the city.

Bayesian Inference: Probability as a Betting Price

How can a belief be a number? The Bayesian answer: your probability for an event is the price you would consider fair for a ticket that pays $1 if the event happens. If you'd pay 70¢ for a "rain tomorrow" ticket, your probability is 0.7.

This simple idea forces beliefs to obey the rules of probability. Suppose you price "rain" at 70¢ and "no rain" at 50¢. Someone sells you both tickets for $1.20. Whatever the weather, exactly one ticket pays out, so you get back $1 and lose 20¢ for certain. A set of prices that lets someone make a guaranteed profit off you is called a Dutch book, and the only way to avoid one is to make your prices follow the rules in Section 3.3. Rational beliefs, it turns out, must be probabilities.

History: A Gambler's Question

Probability theory was born in 1654 from a gambling problem. A French writer and gambler, the Chevalier de Méré, asked the mathematician Blaise Pascal a question about dice (we'll answer it in Example 3.15), and a second one, the problem of points: how should the pot be divided fairly if a game is stopped before anyone has won? Pascal wrote to Pierre de Fermat, and in a famous exchange of letters the two solved it, laying the foundations of the subject. Earlier, the Italian physician and gambler Gerolamo Cardano had written a book on games of chance in the 1560s, though it wasn't published until 1663.

Check Yourself

A lab re-tests 400 samples that were originally reported positive and finds that 100 of them were false positives. What is the empirical probability that a reported positive is false?

You flip a fair coin 10 times and get 7 heads. Which statement is correct?

Think About It: Can the Future Be Estimated from the Past?

An insurance company has 50 years of data showing that 0.3% of homes in a county flood each year, and prices its policies on that empirical probability. List two reasons the next 50 years might not behave like the last 50. What does this say about using empirical probabilities to predict?

The mechanism may change: a warming climate brings heavier rainfall and rising seas, and new building in the floodplain changes how water drains. The data may also be unrepresentative: 50 years is short for rare events, so a single unusually wet or dry decade can distort the estimate. An empirical probability is a good prediction only if the process that generated the past data keeps working the same way (Chapter 1's chicken). Insurers increasingly combine past data with models of the mechanism (climate and hydrology) for exactly this reason: inference about the mechanism makes for better prediction.

Key Takeaways

  • Probability can be read as symmetry, as a long-run frequency, or as a degree of belief. All three follow the same rules.
  • The empirical probability Pr̂(A)=nA/n estimates Pr(A) from data.
  • The Law of Large Numbers: in many independent repetitions, the fraction of times an event happens settles down to its probability. The error shrinks roughly like 1/n.
  • Empirical probabilities assume the future works like the past.

3.2 Experiments, outcomes and events

To reason precisely we need a vocabulary. Any process with an uncertain result, from rolling a die to running a DNA test, is called an experiment.

Definition: Sample Space and Events

  • The sample space S of an experiment is the set of all its possible outcomes.
  • An event is a set of outcomes, that is, a subset of S. An event occurs if the outcome of the experiment is one of its members.

Some examples:

Why bother with sets? Because it turns vague questions into precise ones. "What's the chance the test isn't negative?" becomes "what's the probability of the set {inc,pos}?", and sets can be combined, compared and counted.

Combining events

Events are sets, so we combine them with set operations. In words and in symbols:

Definition: Combining Events

For events A and B in a sample space S:

  • A or B (the union) A∪B: the outcomes in A, in B, or in both.
  • A and B (the intersection) A∩B: the outcomes in both A and B.
  • not A (the complement) Ac: the outcomes in S that are not in A.
  • A and B are disjoint (or mutually exclusive) if they can't both happen: A∩B=⌀, where ⌀ is the empty set, the event containing no outcomes.
  • A is a subset of B, written A⊆B, if every outcome in A is also in B: whenever A happens, B happens.

In mathematics, "or" always means "one or the other or both." Venn diagrams make these operations visible: draw S as a rectangle and events as regions inside it. The shaded outcomes belong to the event.

Six Venn diagrams, each a rectangle containing circles A and B with one region shadedSix Venn diagrams, each a rectangle containing circles A and B with one region shaded. Union, A or B: both circles shaded. Intersection, A and B: only the overlap shaded. Complement of A: everything outside circle A shaded. A but not B: the part of A outside B shaded. Neither A nor B: everything outside both circles shaded. Disjoint events: two separate circles that do not overlap.ABA ∪ BA or B (or both)ABA ∩ BA and BABAᶜnot AABA ∩ BᶜA but not BAB(A ∪ B)ᶜneither A nor BABA ∩ B = ∅disjoint: no overlap
The six set operations you will use most. The rectangle is the sample space S; shaded outcomes belong to the event.

Some combinations are built from these: "A but not B" is A∩Bc, and "exactly one of A and B" is (A∩Bc)∪(Ac∩B). The best way to get fluent is to practise in both directions: from a picture to symbols, and from symbols to a picture.

Click the regions, read the set

The rectangle is the sample space S and the circles are events. Click any region (or use the buttons below the picture) to shade it, and the readout gives the event you have shaded in set notation and in words. Then try a challenge: choose an event from the list and shade exactly that event.

Venn diagram whose regions can be clicked to shade themVenn diagram whose regions can be clicked to shade them. The same regions can be toggled with the buttons below.

Theorem: De Morgan's Laws

For any events A and B, (A∪B)c=Ac∩Bcand(A∩B)c=Ac∪Bc. In words: "not (A or B)" is "neither A nor B"; "not (A and B)" is "not A, or not B (or both)".

First law. We show the two sets contain exactly the same outcomes. An outcome is in (A∪B)c exactly when it is not in A∪B. That means it is in neither A nor B: it is not in A (so it's in Ac) and not in B (so it's in Bc). So it is in Ac∩Bc. Every step can be read backwards, so the two sets are equal.

Second law. Apply the first law to the events Ac and Bc (whose complements are A and B): (Ac∪Bc)c=A∩B. Taking the complement of both sides gives Ac∪Bc=(A∩B)c. ◼∎

You can check De Morgan's laws in the widget: shade "neither" in the two-event diagram, and the readout offers both ways of writing it.

Example 3.4: Describing Events at a Login Server

A server records, for each login attempt, whether the password was correct (P) and whether the attempt came from a new device (N). Write each event in symbols:

  1. The password was wrong.
  2. The password was correct and the device was new.
  3. At least one warning sign: a wrong password or a new device.
  4. No warning signs.

Strategy. Translate each phrase piece by piece: "wrong password" is "not P"; "and" is ∩; "or" (and "at least one") is ∪; "no ... at all" is the complement of "at least one".

  1. Pc.
  2. P∩N.
  3. The two warning signs are Pc and N, so "at least one" is Pc∪N.
  4. Neither warning sign: the password was correct and the device was not new, P∩Nc. By De Morgan this is (Pc∪N)c, the complement of part 3, as it should be: "no warning signs" is the opposite of "at least one warning sign".

Check Yourself

A forensic lab tests a fingerprint (F = "a usable print was recovered") and a DNA swab (D = "a usable DNA profile was recovered").

Think About It: Defining the Event Is Half the Battle

A news report says "the chance of a major earthquake in the region is 70%". Before you can judge or use that number, what must you know about the event? List at least three things the sentence leaves out.

What counts as "major" (magnitude 6.7? 7?); over what time period (next year? next 30 years?); and what region exactly (a city? a whole state?). The probability of an event depends entirely on how the event is defined: "at least one magnitude-6.7 earthquake in the San Francisco Bay Area in the next 30 years" is a precise set of outcomes; "a major earthquake in the region" is not. (The US Geological Survey's widely quoted estimate is of the precise form.) Precise events are the first step to useful predictions.

Key Takeaways

  • The sample space lists every possible outcome; an event is a set of outcomes.
  • Union = or (inclusive), intersection = and, complement = not. Disjoint events can't happen together.
  • De Morgan: not(A or B) = (not A) and (not B); not(A and B) = (not A) or (not B).

3.3 The rules of probability

What rules should any sensible assignment of probabilities follow? Think about long-run fractions, or empirical probabilities. A fraction of the time is never negative and never more than 1. Something certain to happen happens 100% of the time. And if two events can't happen together, the fraction of times that one or the other happens is the sum of their fractions. Remarkably, these three properties are all we need.

Definition: The Axioms of Probability (Kolmogorov)

A probability on a sample space S assigns to each event A a number Pr(A) such that:

  1. Pr(A)≥0 for every event A;
  2. Pr(S)=1;
  3. if A1,A2,A3,… are events no two of which can happen together (pairwise disjoint), then Pr(A1∪A2∪A3∪⋯)=Pr(A1)+Pr(A2)+Pr(A3)+⋯.

Everything else follows from these. Here are the consequences you'll use constantly.

Theorem: Consequences of the Axioms

For any events A and B:

  1. Complement rule. Pr(Ac)=1−Pr(A).
  2. The impossible event. Pr(⌀)=0.
  3. Bounds. 0≤Pr(A)≤1, and if A⊆B (whenever A happens, so does B) then Pr(A)≤Pr(B).
  4. Addition rule. Pr(A∪B)=Pr(A)+Pr(B)−Pr(A∩B).
  5. Union bound. Pr(A∪B)≤Pr(A)+Pr(B).

We prove 2 first. S=S∪⌀∪⌀∪⋯, and these sets are pairwise disjoint, so axiom 3 gives Pr(S)=Pr(S)+Pr(⌀)+Pr(⌀)+⋯. This is only possible if Pr(⌀)=0. As a bonus, axiom 3 now works for finitely many disjoint events too: pad the list with copies of ⌀, which add nothing.

  1. A and Ac are disjoint and together make up S. By axiom 3 (for two events) and axiom 2, Pr(A)+Pr(Ac)=Pr(S)=1. Subtract Pr(A).

  2. Shown above.

  3. If A⊆B, split B into the disjoint pieces A and B∩Ac. Then Pr(B)=Pr(A)+Pr(B∩Ac)≥Pr(A), by axiom 1. Taking B=S gives Pr(A)≤1.

  4. Split A∪B into three disjoint pieces: only A (A∩Bc), both (A∩B), and only B (Ac∩B). Then Pr(A∪B)=Pr(A∩Bc)+Pr(A∩B)+Pr(Ac∩B),Pr(A)=Pr(A∩Bc)+Pr(A∩B),Pr(B)=Pr(Ac∩B)+Pr(A∩B).Pr(A∪B)=Pr(A∩Bc)+Pr(A∩B)+Pr(Ac∩B),Pr(A)=Pr(A∩Bc)+Pr(A∩B),Pr(B)=Pr(Ac∩B)+Pr(A∩B). Adding the last two lines counts the middle piece Pr(A∩B) twice, so Pr(A)+Pr(B)=Pr(A∪B)+Pr(A∩B). Rearrange.

  5. From 4, because Pr(A∩B)≥0. ◼∎

The addition rule is easiest to see in a picture. Move the sliders, and watch which areas get counted twice.

Two events, one picture

Set the probabilities of two events A and B and of their overlap. The areas in the diagram are drawn to scale inside a square of total area 1. The readout applies the rules of this chapter: complements, the addition rule, conditional probability, and a check for independence. Try making the overlap equal to Pr(A) × Pr(B), and try making it zero.

A unit square representing the sample spaceA unit square representing the sample space. Event A is a rectangle spanning a fraction of the width; event B is a rectangle spanning a fraction of the height inside and outside A, drawn so that each area equals its probability.

Example 3.5: Women or Children on the Titanic ★ lecture example

When the RMS Titanic sank in April 1912, about 2,200 people were aboard. A British inquiry recorded each person's class, sex, age group and whether they survived; R's Titanic dataset contains those counts (as compiled by R. Dawson, Journal of Statistics Education, 1995). Pick one person aboard at random. What is the probability that the person was female or a child?

Reading the problem. "Pick at random" makes every person equally likely, so a probability is a count divided by the 2,201 people aboard. Name the events: F = female, C = child. The question asks for Pr(F∪C) ("or").

First the counts of sex by age group:

R
tt <- as.data.frame(Titanic)                 # one row per combination, with a count
xtabs(Freq ~ Sex + Age, data = tt)           # cross-tabulate sex by age
output
        Age
Sex      Child Adult
  Male      64  1667
  Female    45   425

There were 45+425=470 females, 64+45=109 children, and 45 girls, who are both. The addition rule gives Pr(F∪C)=Pr(F)+Pr(C)−Pr(F∩C)=4702201+1092201−452201=5342201≈0.243.Pr(F∪C)=Pr(F)+Pr(C)−Pr(F∩C)=4702201+1092201−452201=5342201≈0.243. Simply adding 470 and 109 would count the 45 girls twice. The answer is 534 people: about 24% of everyone aboard, the group a "women and children first" policy was meant to protect.

Example 3.6: At Least One Alarm

A company's network has two intrusion detectors. Over the past year, detector A raised a false alarm on 3% of days, detector B on 4% of days, and both on 1% of days.

  1. On what fraction of days did at least one detector raise a false alarm?
  2. On what fraction of days did neither?
  3. Without knowing the 1% figure, what can you say for certain about part 1?

Reading the problem. Let A and B be the events that detectors A and B falsely alarm on a given day. Then Pr(A)=0.03, Pr(B)=0.04, Pr(A∩B)=0.01 ("both"). "At least one" is A∪B; "neither" is its complement.

  1. Addition rule: Pr(A∪B)=0.03+0.04−0.01=0.06.
  2. Complement rule: Pr((A∪B)c)=1−0.06=0.94.
  3. The union bound gives Pr(A∪B)≤0.03+0.04=0.07, whatever the overlap.

Notice the detectors are far from independent (Section 3.5): if they were, both would alarm on only 0.03×0.04=0.12% of days, not 1%. They probably react to the same unusual traffic. Security teams use the union bound constantly: with 50 detectors each falsely alarming on 1% of days, the chance of at least one false alarm on a given day could be as large as 50%. More alarms means more false alarms.

Check Yourself

In a city, 30% of burglaries involve forced entry, 20% happen at night, and 10% involve forced entry at night.

What is the probability that a randomly chosen burglary involves forced entry or happens at night (or both)?

What is the probability that it involves neither?

What is the probability that it involves forced entry but did not happen at night?

Interlude (Optional): Probability as Measurement

The axioms look abstract, but they are the same rules obeyed by every way we measure the size of things. Length, area, volume, mass and probability all assign a non-negative number to a region, and all are additive: the size of two non-overlapping pieces is the sum of their sizes. Mathematicians call any such rule a measure, and probability is simply a measure whose total is 1.

Picture throwing a dart at a square board, landing uniformly at random. The probability it lands in a region is that region's share of the area. This also explains something puzzling. The chance the dart hits one exact point, say the dead centre, is zero, because a point has no area. Yet the dart lands somewhere, on a point that had probability zero. So probability zero doesn't mean impossible. This happens whenever outcomes are measurements (times, weights, concentrations), and it's why Chapter 5 works with areas under curves instead of probabilities of single values.

There is a deeper surprise. In 1905 Giuseppe Vitali showed that it is impossible to assign a sensible "length" to every subset of a line; and in 1924 Stefan Banach and Alfred Tarski showed that a solid ball can be cut into finitely many pieces (five turn out to be enough) and reassembled into two balls the same size as the first. The pieces are so strange they have no volume at all. The fix is to measure only well-behaved sets, called measurable sets. When Andrey Kolmogorov wrote down the axioms of probability in 1933, he built them on exactly this theory of measure, and every probability course since stands on his foundation. You will never meet an unmeasurable event in practice, but it's worth knowing that even "how big is this set?" turned out to have a subtle answer.

Why it matters: every rule in this chapter is a rule about measuring sizes, which is why Venn-diagram areas are such a faithful picture of probability.

Think About It: Do the Probabilities Add Up?

A sports commentator says: "Team A has a 60% chance of winning the league, Team B has 30%, and Team C has 25%." What's wrong? If you trusted the commentator's numbers, how could someone take advantage of you?

The three teams can't all win, so the events are disjoint, and their probabilities should add to at most 1; here they add to 1.15. By the Dutch book argument (Section 3.1), someone could sell you a $1 ticket on each team at those prices: you'd pay $1.15 and collect exactly $1 whichever team wins (or less, if a fourth team wins), losing at least 15 cents for certain. Probabilities that break the axioms are not just untidy; they lead to bad decisions.

Key Takeaways

  • Three axioms: probabilities are non-negative, the whole sample space has probability 1, and probabilities of disjoint events add.
  • Complement rule Pr(Ac)=1−Pr(A). Addition rule Pr(A∪B)=Pr(A)+Pr(B)−Pr(A∩B).
  • "At least one" problems are often easiest through the complement: 1−Pr(none).

Lecture 6 — Counting and equally likely outcomes

3.4 Equally likely outcomes and counting

When all outcomes in a finite sample space are equally likely (fair dice, shuffled cards, random samples, random passwords), the axioms give a simple formula.

Theorem: Equally Likely Outcomes

If S has N outcomes, all equally likely, then for any event A containing nA outcomes, Pr(A)=nAN. In words: the number of outcomes in A divided by the number of outcomes in S.

The N single outcomes are disjoint and together make up S, so by axioms 2 and 3 their equal probabilities add to 1: each has probability 1/N. The event A is the disjoint union of its nA outcomes, so Pr(A)=nA×1N. ◼∎

So probability becomes counting. The trouble is that the counts are often astronomically large: nobody can list all the possible poker hands, let alone all the possible 8-character passwords. We need shortcuts, and they all grow from one idea.

The multiplication rule

Theorem: Multiplication Rule for Counting

If a task is done in k stages, with n1 ways to do stage 1, then n2 ways to do stage 2 (whatever happened in stage 1), and so on, the whole task can be done in n1×n2×⋯×nk ways.

Picture a tree: n1 branches for stage 1, each splitting into n2 branches for stage 2, and so on. Each complete path from the root to a leaf is one way of doing the whole task. After stage 1 there are n1 partial paths; each splits into n2, giving n1n2 after stage 2; and so on. After k stages there are n1n2⋯nk paths. ◼∎

For example, a meal deal with 3 mains, 4 sides and 2 drinks gives 3×4×2=24 different meals.

The four ways to choose

Most counting problems ask: in how many ways can we choose k items from n distinct items? The answer depends on two questions, which you should ask every time:

  1. Does order matter? Is "Alice then Bob" different from "Bob then Alice"? For a race (gold, silver), yes; for a committee, no.
  2. Is replacement allowed? Can the same item be chosen more than once? For the digits of a PIN, yes; for people on a committee, no.

Two yes/no questions give four cases. We take them one at a time, each with a motivating example, a formula and a proof.

with replacement (repeats allowed) without replacement (no repeats)
order matters nk n!(n−k)!
order doesn't matter (n+k−1k) (nk)=n!k!(n−k)!

Here n!=n×(n−1)×⋯×2×1 ("n factorial"), with the convention 0!=1. In R: factorial(n) and choose(n, k).

Case 1: order matters, with replacement

A PIN has 4 digits, each from 0 to 9, and digits can repeat. There are 10 choices for the first digit, 10 for the second, and so on: 104=10,000 PINs.

Theorem: Ordered Selections with Replacement

The number of ordered sequences of length k whose entries are each chosen from n distinct items, repeats allowed, is nk.

Each of the k positions is a stage with n choices, whatever was chosen before. By the multiplication rule, there are n×n×⋯×n=nk sequences. ◼∎

Example 3.7: How Long to Crack a Password? ★ lecture example

An attacker who has stolen a database of hashed passwords can test guesses offline. Assume a powerful attacker can test 10 billion (1010) guesses per second. How long does it take to try every possible password of length 8 if passwords use:

  1. lowercase letters only (26 symbols)?
  2. upper- and lowercase letters and digits (62 symbols)?
  3. all 94 printable keyboard characters?

Which case? A password is a sequence (order matters: "abc" and "cba" are different passwords) and characters can repeat ("aaa" is allowed). So with m symbols in each of 8 positions there are m8 passwords. Dividing by 1010 guesses per second gives the time in seconds.

R
m <- c(26, 62, 94)
n_passwords <- m^8
seconds <- n_passwords / 1e10
data.frame(symbols = m, passwords = signif(n_passwords, 3),
           hours = round(seconds / 3600, 3), days = round(seconds / 86400, 2))
output
  symbols passwords   hours days
1      26  2.09e+11   0.006 0.00
2      62  2.18e+14   6.065 0.25
3      94  6.10e+15 169.325 7.06
  1. 268≈2.1×1011 passwords: about 21 seconds.
  2. 628≈2.2×1014: about 6 hours.
  3. 948≈6.1×1015: about 7 days.

The numbers grow so fast that a picture needs a logarithmic axis, on which each gridline is 10 times the one below:

R
len <- 4:14
grid <- expand.grid(length = len, symbols = factor(c(26, 62, 94)))
grid$seconds <- as.numeric(as.character(grid$symbols))^grid$length / 1e10
ggplot(grid, aes(length, seconds, linetype = symbols)) +
  geom_line() +
  scale_y_log10(breaks = 10^c(-6, 0, 6, 12, 18), labels = scales::math_format(10^.x)(c(-6, 0, 6, 12, 18))) +
  scale_linetype_manual(values = c("solid", "dashed", "dotted")) +
  geom_hline(yintercept = c(86400, 3.15e9), colour = "grey60") +
  annotate("text", x = 4, y = c(86400, 3.15e9) * 6, label = c("1 day", "1 century"), hjust = 0, vjust = -0.4, size = 3.8, colour = "grey40") +
  labs(x = "password length", y = "seconds (log scale)",
       linetype = "symbols")
Line plot, on a logarithmic vertical axis, of the time in seconds needed to try every…Line plot, on a logarithmic vertical axis, of the time in seconds needed to try every password against password length from 4 to 14 characters, for 26, 62 and 94 symbols. All three lines are straight and rise steeply; the 94-symbol line reaches about 4 times 10 to the power 17 seconds at 14 characters. Solid grey horizontal lines mark one day and one century. 1 day 1 century 10 0 10 6 10 12 10 18 6 9 12 password length seconds (log scale) symbols 26 62 94

(The grey lines mark one day and one century.) Each extra character multiplies the work by m, which is why the lines are straight on a log scale. A 12-character password from 94 symbols would take about 1.5 million years. Length matters more than cleverness.

One caveat to think about: these counts assume every password is equally likely. Real people choose Password1! far more often than q7#Lr2!x, so attackers try common passwords first. "Equally likely" is a model, and here it flatters the defender.

Case 2: order matters, without replacement

Eight runners compete for gold, silver and bronze. Any of the 8 can win gold; once gold is decided, any of the remaining 7 can win silver; then any of the remaining 6, bronze: 8×7×6=336 possible podiums. Each choice uses up one runner, so the number of options falls by one at each stage.

Theorem: Ordered Selections Without Replacement (Permutations)

The number of ordered sequences of k different items chosen from n distinct items is n×(n−1)×⋯×(n−k+1)=n!(n−k)!. In particular, all n items can be arranged in n! orders.

Use the multiplication rule: n choices for the first position, then n−1 for the second (one item is used up), down to n−(k−1)=n−k+1 for the kth. For the second form, multiply and divide by (n−k)!=(n−k)(n−k−1)⋯1. The numerator becomes n(n−1)⋯(n−k+1)×(n−k)⋯1=n!, so the product equals n!(n−k)!. With k=n, this is n!/0!=n!. ◼∎

Factorials grow astonishingly fast. A deck of 52 cards can be shuffled into 52!≈8×1067 orders, more than the number of atoms in the Earth, so every thorough shuffle you make has almost certainly never happened before.

Example 3.8: A Line-Up

A witness is shown a line-up of 6 people, one of whom is the suspect. If the 6 are arranged in a random order, what is the probability that the suspect stands in position 1? In positions 1, 2 or 3?

Which case? An arrangement is an ordering of all 6 people, without repeats: 6!=720 equally likely line-ups.

Position 1. Count the line-ups with the suspect first: the other 5 people can be arranged in the remaining 5 positions in 5!=120 ways. So Pr(suspect in position 1)=120720=16. That makes sense: by symmetry, the suspect is equally likely to be in any of the 6 positions.

Positions 1 to 3. The events "in position 1", "in position 2" and "in position 3" are disjoint, each with probability 16, so by axiom 3 the probability is 36=12.

R
factorial(6)
factorial(5) / factorial(6)
output
[1] 720
[1] 0.1666667

Random ordering matters in practice: witnesses tend to pick people in some positions more than others, and a fair procedure must not let the suspect's position give anything away.

Example 3.9: The Birthday Problem ★ lecture example

There are 23 people in a room. Assuming each is equally likely to have been born on any of 365 days (ignore 29 February), independently of the others, what is the probability that at least two share a birthday? Try the widget below first, after writing down your guess.

Strategy. "At least two share" is complicated: one pair, two pairs, three people with the same birthday... Its complement, "all 23 birthdays are different", is much simpler. So we find that and subtract from 1.

Count with cases 1 and 2. Write down the birthdays as a list in order (person 1's birthday, person 2's, and so on).

  • All possible lists: each of the 23 people has 365 possible birthdays, repeats allowed (case 1): 36523 equally likely lists.
  • Lists with no repeats: 365 choices for person 1, 364 for person 2, ..., down to 365−22=343 for person 23 (case 2): 365×364×⋯×343.

So Pr(all different)=365×364×⋯×34336523≈0.493, and Pr(at least one shared birthday)=1−0.493=0.507. With just 23 people, a match is more likely than not.

R
1 - prod(365:343) / 365^23      # by the formula
pbirthday(23)                   # R has a built-in function
output
[1] 0.5072972
[1] 0.5072972
R
people <- 1:80
p_match <- sapply(people, pbirthday)
ggplot(data.frame(people, p_match), aes(people, p_match)) +
  geom_line() +
  geom_hline(yintercept = 0.5, linetype = "dashed") +
  geom_vline(xintercept = 23, linetype = "dotted") +
  labs(x = "number of people", y = "Pr(shared birthday)")
Line plot of the probability that at least two people share a birthday, against the…Line plot of the probability that at least two people share a birthday, against the number of people from 1 to 80. The curve rises in an S shape, crossing 0.5 at 23 people, reaching about 0.97 at 50 and nearly 1 by 70. 0.00 0.25 0.50 0.75 1.00 0 20 40 60 80 number of people Pr(shared birthday)

Why does intuition fail so badly? We think about our own birthday, and the chance someone else shares it is small: 1−(364/365)22≈0.06 with 22 others. But the question is about any pair, and 23 people make (232)=253 pairs (case 3, below). Coincidences are much more common than they feel, which matters whenever someone says "what are the odds?" about a match in a large database.

The birthday problem

How many people must be in a room before it's more likely than not that two share a birthday? Before you touch anything, write down your guess. Then choose a room size and gather rooms of random people (365 equally likely birthdays, ignoring 29 February). The calendar shows the latest room: a red square is a birthday shared by two or more people. The curve below is the exact probability, which you'll be able to compute by the end of Section 3.4.

TopTop: a calendar of 365 days with the birthdays in the latest room marked and shared birthdays highlighted. Bottom: the probability of at least one shared birthday against the number of people, with the chosen room size marked.

Case 3: order doesn't matter, without replacement

A lab must choose 2 of its 5 analysts to review a case. Ordered pairs (first reviewer, second reviewer) number 5×4=20 by case 2. But a review panel of Ana and Ben is the same panel as Ben and Ana: each panel was counted twice, once in each order. So there are 20/2=10 panels. The same idea, dividing out the orderings, works in general.

Theorem: Unordered Selections Without Replacement (Combinations)

The number of ways to choose k items from n distinct items, without repeats and when order doesn't matter, is (nk)=n!k!(n−k)!, read "n choose k". It is also the number of subsets of size k of a set of size n.

Count the ordered selections of k items in two ways.

  • Directly, by case 2: there are n!(n−k)! of them.
  • In two stages: first choose which k items (an unordered selection: (nk) ways, the number we want), then put those k items in order (k! ways, by case 2 with k=n). By the multiplication rule there are (nk)×k! ordered selections.

Both count the same thing, so (nk)×k!=n!(n−k)!⇒(nk)=n!k!(n−k)!.◼∎

Two quick checks: (n0)=(nn)=1 (one way to choose nothing, one way to choose everything), and (nk)=(nn−k) (choosing which k to take is the same as choosing which n−k to leave). Combinations are the most important counting tool in the course: Chapter 4's binomial distribution is built on them.

Example 3.10: The Powerball Jackpot

To win the US Powerball jackpot you must match 5 white balls drawn from 69 (order doesn't matter) and 1 red Powerball drawn from 26. What is the probability that one ticket wins?

Which cases? The white balls are drawn without replacement, and the order they come out doesn't matter: case 3, (695) ways. The red ball can be any of 26. By the multiplication rule there are (695)×26 equally likely outcomes, and one ticket matches exactly one of them.

R
choose(69, 5)
choose(69, 5) * 26
output
[1] 11238513
[1] 292201338

The probability is 1 in 292,201,338. If you bought one ticket every second, day and night, you'd expect to wait over nine years for a jackpot.

Putting it in perspective. With a probability of about 3.4×10−9 per ticket, buying 100 tickets a week for 50 years (260,000 tickets) gives a chance of roughly 260,000/292,201,338≈0.0009 of ever winning the jackpot: less than 1 in 1,000. Chapter 4 (Example 4.5) works out what a ticket is worth on average, including the smaller prizes.

Example 3.11: Auditing a Drug Seizure ★ lecture example

Police seize 2,000 small bags of powder. Unknown to anyone, 100 of them are fakes (no controlled substance). The lab tests a random sample of 20 bags. What is the probability that the sample contains no fakes at all, so that the lab never discovers them?

Which case? The lab tests 20 different bags (no replacement), and the order of testing doesn't matter: case 3. A random sample makes every set of 20 bags equally likely, so count sets.

  • All possible samples: (200020).
  • Samples with no fakes: all 20 come from the 1,900 genuine bags, (190020).

Pr(no fakes in sample)=(190020)(200020)≈0.357.

R
choose(1900, 20) / choose(2000, 20)
output
[1] 0.356686

So about one time in three, a sample of 20 contains no fakes at all, even though 5% of the bags are fake. A clean sample does not prove the whole seizure is clean. A plot shows how the chance of missing every fake falls as the lab tests more bags:

R
k <- 1:100
p_miss <- choose(1900, k) / choose(2000, k)
ggplot(data.frame(k, p_miss), aes(k, p_miss)) +
  geom_line() +
  geom_hline(yintercept = 0.05, linetype = "dashed") +
  labs(x = "number of bags tested", y = "Pr(no fakes found)")
Line plot of the probability that a random sample contains no fake bags, against the…Line plot of the probability that a random sample contains no fake bags, against the number of bags tested from 1 to 100, when 100 of 2,000 bags are fake. The curve falls from about 0.95 at 1 bag to 0.36 at 20, 0.13 at 40 and below 0.05 at 58, marked by a dashed line. 0.00 0.25 0.50 0.75 0 25 50 75 100 number of bags tested Pr(no fakes found)

This calculation is the basis of the sampling plans forensic labs use to decide how many items to test (Exercise 5 asks how many are needed), and Chapter 4 turns it into the hypergeometric distribution.

Case 4: order doesn't matter, with replacement

The last case is the least obvious. A lab orders 10 reagent kits, and each kit can be one of 4 types (A, B, C, D). How many different orders are possible? Order doesn't matter (an order is just "how many of each type"), and types can repeat. An order might be 3 of A, 0 of B, 5 of C and 2 of D.

The trick, called stars and bars, is to draw each order as a row of 10 stars (the kits) separated by 4−1=3 bars into 4 compartments (the types). The order above is ⋆⋆⋆||⋆⋆⋆⋆⋆|⋆⋆ Three stars before the first bar (type A), none between the first and second bars (B), five between the second and third (C), and two after the third (D). Every order gives exactly one such row, and every row of 10 stars and 3 bars gives exactly one order. So we just count rows: 13 positions, of which we choose 3 for the bars, giving (133)=286 orders.

Theorem: Unordered Selections with Replacement (Stars and Bars)

The number of ways to choose k items from n distinct types, when order doesn't matter and types can repeat (equivalently, the number of ways to write k=x1+⋯+xn with each xi a whole number ≥0), is (n+k−1k)=(n+k−1n−1).

A selection is described completely by the counts (x1,…,xn) of each type, with x1+⋯+xn=k. Represent it as a row of k stars and n−1 bars: x1 stars, then a bar, then x2 stars, then a bar, and so on, ending with xn stars.

  • Every selection gives a row with exactly k stars and n−1 bars.
  • Every such row gives a selection: read off the numbers of stars between consecutive bars.

So selections and rows are in one-to-one correspondence, and we can count rows instead. A row has n+k−1 positions, and choosing which k of them hold stars (the rest hold bars) determines it completely. By case 3 there are (n+k−1k) ways; choosing the n−1 bar positions instead gives the same number. ◼∎

Watch Out: Counting Is Not the Same as Probability

Case 4 counts the possible unordered results, but those results are usually not equally likely, so you can't divide counts to get probabilities. Roll two dice and record the unordered result: by case 4 there are (6+2−12)=21 possible results ({1,1},{1,2},…). But {1,2} can happen two ways (1 then 2, or 2 then 1) while {1,1} can happen only one way, so Pr({1,2})=236 but Pr({1,1})=136. The equally likely outcomes are the 36 ordered pairs. When in doubt, count ordered outcomes. (In 1754 the great mathematician Jean d'Alembert made a closely related mistake, arguing that the chance of at least one head in two coin tosses is 2/3, because he treated three possible results as equally likely when they are not.)

The widget lists every selection for small cases, so you can see where all four formulas come from.

List every selection

Choose how many letters to pick from (n), how many to select (k), whether order matters, and whether letters can be reused. Every possible selection is listed, and the count is compared with the formula. Notice how each "order does not matter" list is a shorter version of the matching "order matters" list.

Check Yourself

In how many different orders can 5 suspects be arranged in a line-up?

A lab must choose 2 of its 5 analysts to review a case (order doesn't matter). How many different review panels are possible?

A 4-digit PIN uses digits 0–9, and repeats are allowed. What is the probability that a random guess is right?

A café sells 6 flavours of doughnut. How many different boxes of 2 doughnuts are possible, if a box can contain two of the same flavour and the order in the box doesn't matter?

Think About It: Is It Really Equally Likely?

Counting only gives probabilities when the outcomes really are equally likely. For each claim, decide whether "equally likely" is a reasonable model: (a) each of the 10 digits is equally likely to be the last digit of a randomly chosen phone number; (b) each of the 104 PINs is equally likely to be someone's bank PIN; (c) a randomly chosen person is equally likely to be born on any day of the year.

(a) Reasonable: last digits are assigned with no preference. (b) Not at all: people choose 1234, 0000, birth years and dates far more than random strings; studies of leaked PINs find 1234 alone is used by around 1 in 10 people. An attacker predicts using that skewed distribution, not the uniform one. (c) Roughly, but not exactly: births vary by season and are less common on weekends and holidays (because of scheduled deliveries). The birthday problem's probability of 0.507 for 23 people is a slight underestimate for real people, because unequal birthdays make matches more likely.

Key Takeaways
  • With equally likely outcomes, Pr(A) is the number of outcomes in A divided by the total number of outcomes.
  • Ask two questions: does order matter? are repeats allowed? Then: nk; n!/(n−k)!; (nk); (n+k−1k).
  • Every formula comes from the multiplication rule, plus dividing out orderings that were counted more than once.
  • For "at least one" problems, count the complement. Coincidences are common: there are many more pairs than people.

Lecture 7 — Conditional probability and independence

3.5 Conditional probability and independence

Zooming in

Of the 2,201 people aboard the Titanic, 711 survived: Pr(survived)=711/2201≈0.32. But that number hides enormous differences. Suppose you learn that the person you picked was a woman. Your probability should change, because women were far more likely to be given places in the lifeboats. Learning something narrows the sample space to the outcomes consistent with what you learned. Try it.

Conditioning is zooming in: the Titanic

Each dot is one of the 2,201 people aboard the Titanic (R's Titanic data): filled dots survived, hollow dots did not. Pick a random person from the whole ship and the chance they survived is the fraction of filled dots. Now condition: choose a class, sex or age. Everyone outside your choice fades away, and the probability is recomputed among the people who remain. That is all a conditional probability is.

A grid of 2,201 dots, one per person aboard the Titanic, grouped by class, sex and ageA grid of 2,201 dots, one per person aboard the Titanic, grouped by class, sex and age. Filled dots survived. People outside the chosen condition are faded.

Among the 470 women, 344 survived, so the probability of survival given that the person was female is 344/470≈0.73. Notice how this was computed: restrict attention to the women, then take the fraction who survived. In a Venn diagram, the new information shrinks the sample space from the whole rectangle to the circle "female", and we ask what share of that circle lies inside "survived". Dividing both counts by 2,201 turns this into probabilities, and gives the general definition.

Definition: Conditional Probability

For events A and B with Pr(B)>0, the conditional probability of A given B is Pr(A∣B)=Pr(A∩B)Pr(B). It is the probability of A in a world where we know B has happened. The vertical bar is read "given".

FigureFigurebefore: the whole sample space SABPr(A) = area of A / area of Slearn Bafter: only B is possibleA ∩ BBPr(A | B) = Pr(A ∩ B) / Pr(B)
Conditioning on B throws away every outcome outside B, then rescales so that B has probability 1.

Check it on the Titanic: Pr(survived∣female)=Pr(survived∩female)Pr(female)=344/2201470/2201=344470≈0.73. The 2,201s cancel: conditioning is just counting within the smaller group.

Rearranging the definition gives a rule for "and" that we'll use all the time.

Theorem: Multiplication Rule

For events A and B with Pr(B)>0, Pr(A∩B)=Pr(B)Pr(A∣B). More generally, for three events (with Pr(A1∩A2)>0), Pr(A1∩A2∩A3)=Pr(A1)×Pr(A2∣A1)×Pr(A3∣A1∩A2),Pr(A1∩A2∩A3)=Pr(A1)×Pr(A2∣A1)×Pr(A3∣A1∩A2), and so on for more events.

Multiply both sides of the definition by Pr(B). For three events, apply the two-event rule twice, first with B=A1∩A2: Pr(A1∩A2∩A3)=Pr(A1∩A2)×Pr(A3∣A1∩A2),Pr(A1∩A2∩A3)=Pr(A1∩A2)×Pr(A3∣A1∩A2), then to Pr(A1∩A2)=Pr(A1)Pr(A2∣A1). ◼∎

In words: the chance that both happen is the chance the first happens, times the chance the second happens given the first. Drawing two cards from a deck without replacement, the chance both are aces is 452×351: after the first ace, only 3 aces remain among 51 cards.

Example 3.12: Who Survived the Titanic? ★ lecture example

Using R's Titanic data, find the probability of survival given each class of travel, and given each sex. Then find Pr(female∣survived) and compare it with Pr(survived∣female).

prop.table(table, 1) divides each row of a table by its row total, which is exactly conditioning on the row; prop.table(table, 2) divides by column totals, conditioning on the column.

R
tt <- as.data.frame(Titanic)
by_class <- xtabs(Freq ~ Class + Survived, data = tt)
by_class
round(prop.table(by_class, 1), 3)     # Pr(survived | class): divide by row totals
by_sex <- xtabs(Freq ~ Sex + Survived, data = tt)
round(prop.table(by_sex, 1), 3)       # Pr(survived | sex)
round(prop.table(by_sex, 2), 3)       # Pr(sex | survived): divide by column totals
output
      Survived
Class   No Yes
  1st  122 203
  2nd  167 118
  3rd  528 178
  Crew 673 212
      Survived
Class     No   Yes
  1st  0.375 0.625
  2nd  0.586 0.414
  3rd  0.748 0.252
  Crew 0.760 0.240
        Survived
Sex         No   Yes
  Male   0.788 0.212
  Female 0.268 0.732
        Survived
Sex         No   Yes
  Male   0.915 0.516
  Female 0.085 0.484
R
rate <- prop.table(by_class, 1)[, "Yes"]
ggplot(data.frame(class = names(rate), rate), aes(class, rate)) +
  geom_col(width = 0.6) +
  geom_hline(yintercept = 711 / 2201, linetype = "dashed") +
  labs(x = NULL, y = "Pr(survived | class)")
Bar chart of the probability of survival given class of travel on the TitanicBar chart of the probability of survival given class of travel on the Titanic: first class 0.62, second class 0.41, third class 0.25, crew 0.24. A dashed line marks the overall survival rate of 0.32. 0.0 0.2 0.4 0.6 1st 2nd 3rd Crew Pr(survived | class)
  • Survival given class: 62% in first class, 41% in second, 25% in third, 24% among the crew. The dashed line is the overall rate, 32%: conditioning on class moves the probability a long way in both directions.
  • Survival given sex: 73% of females, 21% of males.
  • Pr(survived∣female)=344/470≈0.73, but Pr(female∣survived)=344/711≈0.48.

The last two are different questions with different answers. The first asks "of the women, what fraction survived?" (restrict to the 470 women); the second asks "of the survivors, what fraction were women?" (restrict to the 711 survivors). Same numerator, different group. Pr(A∣B) and Pr(B∣A) are not the same, and confusing them is the single most common error in probability. Section 3.6 shows how dangerous it can be.

Causal Inference: Conditioning Is Not Intervening

First-class passengers survived far more often than third-class passengers. Does that mean that buying a first-class ticket caused a better chance of survival? Partly, perhaps: first-class decks were closer to the lifeboats. But class was also tied up with sex and age (third class held many more families with children, for instance) and with where cabins were located.

A causal diagram for the TitanicA causal diagram for the Titanic. Wealth has arrows to ticket class and to cabin location. Cabin location has an arrow to survival. Ticket class has an arrow to survival through lifeboat access. Sex has an arrow to survival through the women and children first policy.wealthticket classcabin decksurvivedsexlifeboat access"women andchildren first"
Why did first-class passengers survive more often? Several routes connect class and survival.

Pr(survived∣first class) describes the people who happened to travel first class. The causal question, "what would happen to a person's chances if we moved them to first class?", is about an intervention, which statisticians write Pr(survived∣do(first class)). The two agree only when nothing else connects class and survival. Conditional probabilities describe the world as we find it; causal questions ask how it would change if we acted on it.

Reading a probability word problem

Most mistakes in probability happen before any calculation: in reading the question. A word problem hides its probabilities in everyday phrases, and the hardest part is deciding which phrase is a plain probability, which is an "and", and which is a "given". This algorithm works for almost every problem in the course.

Idea: Algorithm: From Words to Symbols

  1. Name the events. Give each yes/no feature a letter: D = "has the disease", + = "tests positive". Use complements for the opposite (Dc = "doesn't have the disease") rather than new letters.
  2. Translate every number. For each number in the question, ask: what fraction of what? The "of what" is the group you're restricted to. If it's everyone, it's a plain probability Pr(⋅). If it's a subgroup, it's a conditional probability, with the subgroup after the bar.
  3. Translate the question the same way.
  4. Choose the rule that connects what you have to what you want: complement, addition, multiplication, total probability or Bayes.
  5. Sanity check the answer: is it between 0 and 1? Is it bigger or smaller than you expected, and why?

The phrases below are clues to the translation. The most important one is that "of", "among", "if", "given that" and "for those who" all introduce the group after the bar.

phrase translation
"30% of patients have D" Pr(D)=0.3
"40% of smokers have D" / "if a person smokes, the chance of D is 40%" / "among smokers..." Pr(D∣smoker)=0.4
"10% of patients both smoke and have D" / "...are smokers with D" Pr(smoker∩D)=0.1
"of those with D, 25% smoke" Pr(smoker∣D)=0.25
"at least one", "either ... or" union, ∪
"neither", "none" complement of the union
"the test is 95% accurate for people who have D" (sensitivity) Pr(+∣D)=0.95
"a false-positive rate of 2%" Pr(+∣Dc)=0.02

Example 3.13: Translating a Word Problem ★ lecture example

In a city, 12% of adults were victims of a property crime last year. Among victims, 35% reported the crime to the police. Among non-victims, 1% filed a police report anyway (for example, for lost property later recovered). Of all the adults who filed a report, what fraction were genuine victims?

Translate every number into symbols, then solve.

Step 1, name the events. V = "was a victim", R = "filed a report". Then Vc = "not a victim".

Step 2, translate every number.

  • "12% of adults were victims": a fraction of all adults, so Pr(V)=0.12. (So Pr(Vc)=0.88.)
  • "Among victims, 35% reported": a fraction of victims, so it's conditional on V: Pr(R∣V)=0.35.
  • "Among non-victims, 1% filed a report": Pr(R∣Vc)=0.01.

Step 3, translate the question. "Of all the adults who filed a report, what fraction were victims?" The group is those who filed a report, so it goes after the bar: we want Pr(V∣R).

Notice that we were given Pr(R∣V) and are asked for Pr(V∣R): the question turns the conditional probability around. That is the signal for Bayes' theorem (Section 3.6).

Step 4, solve. It's easiest with natural frequencies. Imagine 10,000 adults:

  • 1,200 victims, of whom 35% report: 420 reports;
  • 8,800 non-victims, of whom 1% report: 88 reports.

So there are 420+88=508 reports, and 420 of them are from victims: Pr(V∣R)≈420508≈0.83.

Step 5, sanity check. About 83% of reports come from real victims, so about 17% don't, which is plausible: non-victims rarely report, but there are many more of them. Note how different this is from Pr(R∣V)=0.35.

The same reasoning as a picture. The 508 reports split into two very unequal sources:

R
ggplot(data.frame(source = c("genuine victims", "non-victims"), n = c(420, 88)),
       aes(x = "reports", y = n, fill = source)) +
  geom_col(width = 0.5) + coord_flip() +
  scale_fill_manual(values = c("grey40", "orange")) +
  labs(x = NULL, y = "reports per 10,000 adults", fill = NULL)
Stacked bar showing 508 police reports per 10,000 adultsStacked bar showing 508 police reports per 10,000 adults: 420 from genuine victims and 88 from non-victims. reports 0 100 200 300 400 500 reports per 10,000 adults genuine victims non-victims

Check Yourself

Translate each statement. A forensic glass study found: "Of the fragments from vehicle windows, 30% had a refractive index above 1.52. Overall, 8% of fragments came from vehicle windows. 4% of all fragments both came from vehicle windows and had a high refractive index." Let V = "from a vehicle window" and H = "refractive index above 1.52".

Independence

Sometimes learning that B happened tells us nothing about A: the probability stays the same.

Definition: Independent Events

Events A and B are independent if Pr(A∩B)=Pr(A)Pr(B). When Pr(B)>0 this is the same as Pr(A∣B)=Pr(A): knowing B happened doesn't change the probability of A. Events A1,…,An are (mutually) independent if, for every sub-collection of two or more of them, the probability that they all occur is the product of their probabilities.

Why are the two forms the same? If Pr(B)>0, dividing Pr(A∩B)=Pr(A)Pr(B) by Pr(B) gives Pr(A∩B)/Pr(B)=Pr(A), which says Pr(A∣B)=Pr(A); the steps reverse too.

For the Titanic, Pr(female)Pr(survived)=4702201×7112201≈0.069, but Pr(female∩survived)=3442201≈0.156. Not even close: sex and survival were strongly dependent.

In practice we usually assume independence because of how an experiment works (separate coin flips, separate patients, separate random draws with replacement), and then use the product rule to compute probabilities that would otherwise be impossible. Assuming independence is a modelling decision, and it deserves the same scepticism as any other assumption.

Watch Out: Independent Is Not the Same as Disjoint

Disjoint events are as dependent as events can be. If A and B are disjoint and both possible, then knowing A happened tells you for certain that B didn't: Pr(B∣A)=0≠Pr(B). In a Venn diagram, disjoint events don't overlap at all; independent events overlap by exactly the "right" amount, Pr(A)Pr(B).

Example 3.14: Independent Alarms?

In Example 3.6, detector A falsely alarmed on 3% of days, detector B on 4%, and both on 1%. Are the detectors' false alarms independent? What is Pr(B∣A), and what does it mean?

If they were independent, both would alarm on Pr(A)Pr(B)=0.03×0.04=0.0012 of days. In fact both alarm on 0.01 of days, more than 8 times as often. So they are not independent. Conditioning shows the strength of the connection: Pr(B∣A)=Pr(A∩B)Pr(A)=0.010.03≈0.33. On an ordinary day, B alarms with probability 0.04; on a day when A alarms, B alarms with probability 0.33. A false alarm from A makes one from B about eight times more likely, presumably because both are fooled by the same unusual traffic. Two detectors that fail together protect you less than two independent ones.

Example 3.15: The Chevalier De Méré's Dice ★ lecture example

De Méré believed these two bets were equally good:

  • Bet 1: at least one six in 4 rolls of a die;
  • Bet 2: at least one double six in 24 rolls of a pair of dice.

His reasoning: a six has chance 16 and there are 4 rolls, giving 46; a double six has chance 136 and there are 24 rolls, giving 2436=46. Yet, so the story goes, he lost money on the second bet. Find the correct probabilities.

What's wrong with de Méré's reasoning? It can't be right: by the same logic, 7 rolls would give a probability of 76>1. He added probabilities of events that are not disjoint (you can get a six on roll 1 and on roll 2), so the overlaps were counted more than once.

Use the complement and independence instead. For bet 1, "at least one six" is the complement of "no six in any of the 4 rolls". The rolls are independent and each misses a six with probability 56, so by the product rule Pr(at least one six)=1−(56)4≈1−0.4823=0.5177. For bet 2, each roll of the pair fails to give a double six with probability 3536: Pr(at least one double six)=1−(3536)24≈1−0.5086=0.4914.

R
1 - (5/6)^4
1 - (35/36)^24
output
[1] 0.5177469
[1] 0.4914039

Bet 1 wins slightly more than half the time, and bet 2 slightly less. De Méré was a sharp gambler: to notice a difference of less than 3 percentage points from his winnings, he must have played a great many times. The Law of Large Numbers at work.

A simulation of both bets shows how slowly the difference emerges, which is why de Méré needed so many games to notice it:

R
set.seed(1654)
n <- 20000
bet1 <- replicate(n, any(sample(1:6, 4, replace = TRUE) == 6))
bet2 <- replicate(n, any(sample(1:6, 24, replace = TRUE) == 6 & sample(1:6, 24, replace = TRUE) == 6))
d <- rbind(data.frame(play = 1:n, wins = cumsum(bet1) / (1:n), bet = "bet 1: one six in 4 rolls"),
           data.frame(play = 1:n, wins = cumsum(bet2) / (1:n), bet = "bet 2: double six in 24 rolls"))
ggplot(d, aes(play, wins, linetype = bet)) +
  geom_line() +
  geom_hline(yintercept = 0.5, colour = "grey60") +
  scale_x_log10() + coord_cartesian(ylim = c(0.3, 0.7)) +
  labs(x = "number of plays (log scale)", y = "fraction won so far", linetype = NULL)
Line plot of the running fraction of wins for de Méré's two bets over 20,000 simulated…Line plot of the running fraction of wins for de Méré's two bets over 20,000 simulated plays, on a logarithmic axis. Both lines swing widely at first. The line for bet 1 settles near 0.516 (its true value is 0.518) and the line for bet 2 near 0.496 (true value 0.491), on either side of a solid grey line at one half; bet 2 is drawn dashed. In this run the lines part after a few dozen plays, but they keep wobbling for hundreds more. 0.3 0.4 0.5 0.6 0.7 1 10 100 1000 10000 number of plays (log scale) fraction won so far bet 1: one six in 4 rolls bet 2: double six in 24 rolls

In this run the lines part early, but that is partly luck: with a gap of under 3 percentage points, a run of a few hundred plays could easily show the bets the other way round, and it takes a few thousand plays before the difference is reliably clear. Detecting a small difference takes a lot of data, a theme Chapters 8 and 9 make precise.

Example 3.16: Why a DNA Profile Is So Rare

Forensic DNA profiles in the US record the variants a person carries at 20 standard locations (loci) on the genome, the CODIS core loci. Suppose that at each locus, the variants found at the crime scene occur in about 1 in 10 people, and that loci are independent of each other. What is the probability that a randomly chosen unrelated person matches at all 20 loci? What assumption is doing all the work?

With independence, the probabilities multiply: Pr(match at all 20 loci)=(110)20=10−20. That is one in a hundred billion billion, far smaller than one divided by the number of people who have ever lived.

Two assumptions are doing the work. The first is independence across loci, which is approximately true for unrelated people because the loci sit far apart on the genome. The second is that the chance of matching at each locus is about 1 in 10, which is true only for people unrelated to the true source. A brother inherited his DNA from the same parents, so at each locus his chance of carrying the same variants is much higher (roughly 1 in 4 or more), and his overall match probability is vastly larger than 10−20. That's why forensic reports state match probabilities for unrelated individuals, and why defence experts ask about relatives. (Real calculations also use the actual population frequencies of each variant, which differ between loci and populations; 1 in 10 is a simplification.)

Causal Inference: A Dependence Created by Looking

Two events can be independent in the population but dependent in your data, purely because of how the data were selected. Suppose two diseases, A and B, occur independently, and either one can put you in hospital. Among hospital patients, the diseases look negatively related: if a patient doesn't have A, something else (probably B) must have brought them in.

A causal diagram with three nodesA causal diagram with three nodes. Disease A has an arrow into hospitalised, and disease B has an arrow into hospitalised. There is no arrow between disease A and disease B. Hospitalised is a collider.disease Adisease Bin hospitalno arrow: independent
Two independent causes of hospital admission. Looking only at hospital patients conditions on the collider.

A variable caused by two others, like "in hospital" here, is called a collider. Conditioning on a collider (studying only hospital patients) creates a dependence between its causes. This is Berkson's paradox, described by the statistician Joseph Berkson in 1946. A simulation shows it clearly:

R
set.seed(46)
n <- 100000
A <- rbinom(n, 1, 0.10)                  # disease A: 10% of people
B <- rbinom(n, 1, 0.10)                  # disease B: 10%, independent of A
# admitted if ill and the illness is serious enough (50%), or for other reasons (2%)
hosp <- ((A == 1 | B == 1) & runif(n) < 0.5) | (runif(n) < 0.02)
# Pr(B | A) and Pr(B | not A), in everyone and among hospital patients
c(with_A = mean(B[A == 1]), without_A = mean(B[A == 0]))
c(with_A = mean(B[A == 1 & hosp]), without_A = mean(B[A == 0 & hosp]))
output
    with_A  without_A 
0.09671642 0.10058922 
    with_A  without_A 
0.09903661 0.73431199 

In the whole population (first line), about 10% have disease B whether or not they have A. Among hospital patients (second line), only about 10% of those with A have B, but over 70% of those without A do. In hospital, the two diseases look strongly negatively related, though in reality they have nothing to do with each other. The same trap catches studies of only convicted defendants, only published papers, or only successful start-ups.

Interlude (Optional): Predicting the Next Word

A large language model, the technology behind modern AI chatbots, does one thing over and over: given the words so far, it assigns a probability to every possible next word, then picks one. In the language of this section, it computes a conditional probability for every possible word w: Pr(next word=w∣the words so far). And it estimates those conditional probabilities the way Section 3.1 estimated any probability: empirically, from how often each word followed similar text in its training data.

The idea is old. In 1948 Claude Shannon, founding information theory, generated English-like text by choosing each word according to how often it followed the previous word in a book: an empirical estimate of Pr(next word∣previous word). Here is Shannon's model, trained on a short made-up passage about a crime lab. Change the text, or paste in anything you like.

Predicting the next word

This is a tiny language model. It reads a training text and counts, for every word, which words came next. Its prediction for the next word is a conditional probability: Pr(next word = w | current word = x) = (times x was followed by w) ÷ (times x appeared). Type a word to see its predictions, or let the model write by repeatedly sampling a next word. You can replace the training text with anything you like.

Horizontal bar chart of the probability of each possible next word, given the current wordHorizontal bar chart of the probability of each possible next word, given the current word.

Conditioning on only one previous word produces text that is locally plausible and globally nonsense. Modern models condition on thousands of previous words, and estimate the conditional probabilities with neural networks trained on enormous amounts of text. They still have to solve the problems you can see here: what to do about word combinations never seen in training (should their probability really be zero?), and how to choose a word: always the most likely one (dull and repetitive), or at random according to the probabilities (more varied, sometimes wrong). When a chatbot confidently states something false, it's because a plausible-sounding next word is not the same as a true one.

Why it matters: conditional probability, estimated from data, is the engine of modern AI.

Check Yourself

In a city, 40% of adults own a car and 25% own a bicycle. 10% own both.

What is the probability that a car owner also owns a bicycle?

Are owning a car and owning a bicycle independent in this city?
Two security cameras independently fail on 2% of nights each. On what fraction of nights do both fail?

Think About It: Which Way Round Is the Evidence?

A crime lab reports: "If the suspect is innocent, the probability of finding this many glass fragments on his clothing is 0.01." A newspaper headline says: "99% chance suspect is guilty, says lab." Explain, using the notation of this section, why the headline doesn't follow. What else would you need to know?

The lab reported Pr(evidence∣innocent)=0.01. The headline claims Pr(guilty∣evidence)=0.99, the conditional probability turned around: exactly the confusion of Example 3.12. To get from one to the other you need the probability of the evidence if he is guilty (perhaps not 1: guilty people don't always carry fragments), and how plausible his guilt was before the evidence: the prior. Section 3.6 shows how to combine them.

Key Takeaways

  • Pr(A∣B)=Pr(A∩B)/Pr(B): the probability of A after zooming in to the outcomes where B happened.
  • Multiplication rule Pr(A∩B)=Pr(B)Pr(A∣B).
  • In a word problem, ask of every number: what fraction of what? The "of what" goes after the bar.
  • A and B are independent if Pr(A∩B)=Pr(A)Pr(B). Disjoint events with positive probabilities are not independent.
  • Pr(A∣B)≠Pr(B∣A) in general.
  • Conditioning describes the world as found; causal questions ask about interventions. Conditioning on a collider creates false associations.

Lecture 8 — Bayes' theorem, simulation and random variables

3.6 Thinking backwards: total probability and Bayes' theorem

From clues to causes

A detective arrives at a crime scene. She doesn't see the crime; she sees its effects: a footprint, a broken lock, a missing file. Her job is to reason backwards from the effects to the cause. A doctor does the same with symptoms, a mechanic with a strange noise, a scientist with an experiment's results.

Probability, so far, has gone forwards: if this person has the disease, how likely is a positive test? If this suspect is the thief, how likely is this footprint? Those forward probabilities are usually the ones we know, because we can study them: run the test on people known to be ill, measure the suspect's shoes. But the question we need answered goes backwards: given the positive test, how likely is the disease? Given the footprint, how likely is this suspect?

Two results connect the directions. The law of total probability says how likely a clue is overall, adding up over all the possible causes. Bayes' theorem then says what share of that total each cause is responsible for. Both are easiest to understand, and much harder to get wrong, if you start by counting.

Where do the clues come from? Total probability

Example 3.17: Where Do Lab Errors Come from? ★ lecture example

A crime lab sends DNA samples to three contract labs. Lab 1 processes 50% of the samples, lab 2 processes 30%, and lab 3 processes 20%. From audits, lab 1 makes an error on 1% of its samples, lab 2 on 2%, and lab 3 on 5%. (a) What fraction of all samples come back with an error? (b) A sample comes back with an error. What is the probability it was processed by lab 3?

Translate. Let L1,L2,L3 be the events that a sample went to each lab, and E that it comes back with an error. The question gives Pr(L1)=0.5, Pr(L2)=0.3, Pr(L3)=0.2, and, because "lab 1 makes an error on 1% of its samples" restricts to lab 1, Pr(E∣L1)=0.01, Pr(E∣L2)=0.02, Pr(E∣L3)=0.05. We want (a) Pr(E) and (b) Pr(L3∣E).

Count first. Imagine 1,000 samples.

lab samples error rate errors
1 500 1% 5
2 300 2% 6
3 200 5% 10
total 1,000 21

(a) Altogether there are 5+6+10=21 errors in 1,000 samples, so Pr(E)=21/1000=0.021. We found the overall error rate by adding up the errors from each source.

(b) Now look only at the 21 samples with errors. Ten of them came from lab 3, so Pr(L3∣E)=1021≈0.48. Lab 3 handles only 20% of the samples, but nearly half of the errors.

The same calculation in symbols. The 5, 6 and 10 were each "number of samples × error rate", that is, 1000×Pr(Li)×Pr(E∣Li). So the total was Pr(E)=Pr(E∣L1)Pr(L1)+Pr(E∣L2)Pr(L2)+Pr(E∣L3)Pr(L3)=0.01×0.5+0.02×0.3+0.05×0.2=0.005+0.006+0.010=0.021,Pr(E)=Pr(E∣L1)Pr(L1)+Pr(E∣L2)Pr(L2)+Pr(E∣L3)Pr(L3)=0.01×0.5+0.02×0.3+0.05×0.2=0.005+0.006+0.010=0.021, and the share from lab 3 was Pr(L3∣E)=Pr(E∣L3)Pr(L3)Pr(E)=0.0100.021≈0.48. These are the law of total probability and Bayes' theorem. You've just used both, without needing either formula.

Play with the same calculation below. Each square is one case. Step 1 is the law of total probability (count all the dark squares); step 2 is Bayes' theorem (zoom in on the dark squares and ask where they came from).

1,000 cases: where do the events come from?

Each small square is one of 1,000 cases, coloured by which group it belongs to. Dark squares with a dot are the cases where the event happened. Step 1 (law of total probability): count all the dark squares, group by group. Step 2 (Bayes' theorem): press look only at the event to zoom in on the dark squares and ask which group they came from. Change the rates and watch both answers move.

A grid of 1,000 squares divided into groups, with the cases where the event happened…A grid of 1,000 squares divided into groups, with the cases where the event happened marked.

Now the general statement. The idea is that the possible causes B1,…,Bk split the sample space into pieces, like the labs above, and every outcome lies in exactly one piece. Such a collection is called a partition of S.

Theorem: Law of Total Probability

Suppose the events B1,B2,…,Bk are disjoint, have positive probability, and between them cover the whole sample space (exactly one of them happens). Then for any event A, Pr(A)=Pr(A∣B1)Pr(B1)+Pr(A∣B2)Pr(B2)+⋯+Pr(A∣Bk)Pr(Bk). In words: the overall probability of A is a weighted average of its probabilities within each piece, weighted by how big each piece is.

Because exactly one Bi happens, A splits into the disjoint pieces A∩B1,…,A∩Bk ("A and the cause was B1", and so on). By axiom 3, Pr(A)=Pr(A∩B1)+⋯+Pr(A∩Bk). Apply the multiplication rule to each term: Pr(A∩Bi)=Pr(A∣Bi)Pr(Bi). ◼∎

The most common partition has just two pieces, B and Bc: Pr(A)=Pr(A∣B)Pr(B)+Pr(A∣Bc)Pr(Bc). Why is it intuitive? It's how you'd compute an overall pass rate for a course with two sections: each section's pass rate, weighted by the share of students in it. If one section has 90% passing and holds a quarter of the students, and the other has 70% passing, the overall rate is 0.9×0.25+0.7×0.75=0.75. The overall rate must lie between the section rates, and it's closer to the bigger section's.

Reasoning backwards: Bayes' theorem

Here is the classic example, in which most doctors get it wrong. We'll do it with frequencies first, and only then with the formula.

Example 3.18: A Positive Mammogram ★ lecture example

In a study by Gerd Gigerenzer and colleagues (published in Psychological Science in the Public Interest, 2007), 160 gynaecologists were given this information about mammography screening in their region:

  • the probability that a woman has breast cancer is 1% (the prevalence);
  • if she has breast cancer, the probability that the mammogram is positive is 90% (the sensitivity);
  • if she doesn't, the probability that it is nevertheless positive is 9% (the false-positive rate).

A woman's mammogram is positive. What is the probability she actually has breast cancer? Make a guess before reading on.

Translate. Write C for "has cancer" and + for "positive test". Then Pr(C)=0.01 (all women), Pr(+∣C)=0.9 ("if she has cancer"), and Pr(+∣Cc)=0.09 ("if she doesn't"). The question asks for Pr(C∣+) ("given a positive"): the reverse of what we know.

Count first: natural frequencies. Imagine 1,000 women having a mammogram.

A frequency tree for 1,000 women aged about 50 having a screening mammogramA frequency tree for 1,000 women aged about 50 having a screening mammogram. 10 have breast cancer and 990 do not. Of the 10 with cancer, 9 test positive and 1 tests negative. Of the 990 without cancer, 89 test positive and 901 test negative. In total 98 test positive, of whom only 9 have cancer.1,000 women10 with cancer990 without9 positive1 negative89 positive901 negative1%99%90%10%9%91%Pr(cancer | positive) = 9 / (9 + 89) ≈ 0.09
Natural frequencies: of the 98 positive mammograms, only 9 belong to women with cancer.

Ten have cancer, and 9 of them test positive. Of the 990 without cancer, 9% (about 89) also test positive. So there are 9+89=98 positive tests, of which only 9 come from women with cancer: Pr(C∣+)≈998≈0.09.

Only about 9%. The disease is rare, so even a small false-positive rate applied to the large healthy majority produces far more false alarms (89) than true cases (9).

The same calculation in symbols. The 98 positives came from two sources, so the law of total probability gives Pr(+)=Pr(+∣C)Pr(C)+Pr(+∣Cc)Pr(Cc)=0.9×0.01+0.09×0.99=0.009+0.0891=0.0981,Pr(+)=Pr(+∣C)Pr(C)+Pr(+∣Cc)Pr(Cc)=0.9×0.01+0.09×0.99=0.009+0.0891=0.0981, and the share of those that come from women with cancer is Pr(C∣+)=Pr(+∣C)Pr(C)Pr(+)=0.0090.0981≈0.092.

In the study, only 21% of the gynaecologists chose the right answer (about 1 in 10); nearly half chose 90%, confusing Pr(+∣C) with Pr(C∣+), and 13% chose 81%, another answer far too high. After a short training session using natural frequencies, most of them got it right. A positive screening test is a reason for a follow-up test, not a diagnosis.

Every step of the frequency argument has a symbol to match: "how many have the cause" is Pr(B); "how many of those show the clue" is Pr(A∣B); "how many show the clue altogether" is Pr(A), by total probability; and "what share of them have the cause" is Pr(B∣A). Writing that down in general gives the theorem.

Theorem: Bayes' Theorem

With B1,…,Bk a partition as in the law of total probability, and Pr(A)>0, Pr(Bj∣A)=Pr(A∣Bj)Pr(Bj)Pr(A), where Pr(A)=∑iPr(A∣Bi)Pr(Bi) is computed by the law of total probability. For a single event B and its complement: Pr(B∣A)=Pr(A∣B)Pr(B)Pr(A), where Pr(A)=Pr(A∣B)Pr(B)+Pr(A∣Bc)Pr(Bc).

By the definition of conditional probability, then the multiplication rule in the numerator, Pr(Bj∣A)=Pr(A∩Bj)Pr(A)=Pr(A∣Bj)Pr(Bj)Pr(A). Replace Pr(A) in the denominator using the law of total probability. ◼∎

Notice that the proof is two lines long. Bayes' theorem isn't deep mathematics; it's the definition of conditional probability, used twice. What makes it powerful is what it lets us do.

Definition: Prior, Likelihood, Posterior

In Bayes' theorem Pr(B∣A)=Pr(A∣B)Pr(B)/Pr(A), the parts have names:

  • Pr(B) is the prior probability of B: how plausible B was before seeing the evidence A;
  • Pr(A∣B) is the likelihood: how probable the evidence is if B is true;
  • Pr(B∣A) is the posterior probability of B: how plausible B is after seeing the evidence.

Bayes' theorem says: posterior ∝ likelihood × prior (the symbol ∝ means "proportional to"; dividing by Pr(A) just rescales so the posteriors add to 1). Both ingredients matter. Strong evidence (a big likelihood ratio) can be overwhelmed by a small enough prior, which is what happened with the mammogram: a 90% sensitive test could only lift a 1% prior to 9%.

Change the prevalence, sensitivity and specificity (one minus the false-positive rate) yourself. Then press test positive again: a second test, whose errors are independent of the first test's (given whether the person is ill), uses the first answer as its starting point.

Bayes' theorem as counting: a screening test

Imagine 10,000 people. Set how common the disease is (the prior), how often the test catches a real case (sensitivity), and how often it correctly clears a healthy person (specificity). The tree counts everyone, and the bar below shows who the positive tests really belong to. Then press test positive again: the answer to the first test becomes the prior for the second.

A frequency tree splitting 10,000 people by disease status and then by test result, and a…A frequency tree splitting 10,000 people by disease status and then by test result, and a bar dividing all positive tests into true and false positives.

Watch Out: The Base-Rate Fallacy

Ignoring the prior, as the gynaecologists who answered 90% did, is called the base-rate fallacy. Whenever you're told how accurate a test, a witness, an algorithm or a piece of evidence is, ask straight away: how common is the thing being detected? A 99% accurate test for something that affects 1 in 10,000 people produces about 100 false positives for every true one.

Bayes' theorem as a detective

Bayes' theorem is more than a formula for turning conditional probabilities around. It is a recipe for learning from evidence, and it works exactly the way a good detective thinks.

  1. List the suspects (the possible causes), and say how plausible each is before any evidence: the prior.
  2. For each clue, ask how likely it would be under each suspect: the likelihood. A clue is useful when it is much more likely under some suspects than others. A clue that is equally likely whoever did it is no help at all, however dramatic it sounds.
  3. Multiply prior by likelihood for each suspect, then rescale so the results add to 1: the posterior.
  4. The posterior becomes the new prior for the next clue. Repeat.

Sherlock Holmes said, "when you have eliminated the impossible, whatever remains, however improbable, must be the truth." Bayes' theorem is the version for clues that don't eliminate anyone completely, but make some explanations more likely than others. Try it.

The detective's notebook: Bayes one clue at a time

Evidence has gone missing from a locked evidence room. Four people had access. Before any clues, the detective's prior reflects how often each was in the building that week. Each clue comes with a likelihood: how probable that clue would be if each person were the thief. Reveal the clues in any order. For every clue, the detective multiplies prior by likelihood and rescales so the total is 1, giving the posterior, which becomes the prior for the next clue.

Bar chart of the probability that each suspect is the thief, updated as clues are revealedBar chart of the probability that each suspect is the thief, updated as clues are revealed.

Three things to notice in the widget. First, the suspect who was most likely at the start isn't necessarily most likely at the end: evidence can overturn a prior. Second, a clue moves probability towards the suspects under whom it is relatively likely; what matters is the comparison between likelihoods, not their size. Third, the order of the clues doesn't matter: you reach the same posterior however you reveal them.

Example 3.19: The Prosecutor's Fallacy ★ lecture example

A burglar leaves a trace of blood at a crime scene in New York City. Its DNA profile is found in about 1 in a million unrelated people. Police search a database and find a man whose profile matches. There is no other evidence against him. At trial the prosecutor says: "The chance of a match if he were innocent is one in a million, so the chance he is innocent is one in a million."

  1. What is wrong with this argument?
  2. NYC had about 8.8 million residents at the 2020 census. Suppose, for the sake of argument, that the burglar is equally likely to be any of them. Given the match, what is the probability that this man is the source of the blood?
  1. Translate the prosecutor's numbers. "The chance of a match if he were innocent" is Pr(match∣innocent)=10−6. The jury needs Pr(innocent∣match). These are different, just as Pr(+∣C)≠Pr(C∣+) in Example 3.18. Confusing them is called the prosecutor's fallacy. It is the base-rate fallacy in a courtroom: it ignores how many innocent people there are.

  2. Count. Among about 8.8 million residents, one is the burglar, and he matches. Of the other 8.8 million, about 8.8×106×10−6=8.8 are expected to match by chance. So roughly 1+8.8≈9.8 people match, and our man is just one of them: Pr(source∣match)≈11+8.8≈0.10.

In Bayes' terms, the prior that this man is the source is 1/(8.8 million), and the match multiplies the odds by a million, which still leaves only about 10%.

With no other evidence, a one-in-a-million match leaves about a 90% chance that the man found in a database search is not the source. In a real case, other evidence (where he lives, an alibi, a witness) changes the prior enormously, which is why DNA evidence is so powerful in combination with other evidence and can be dangerous on its own. The opposite mistake, the defence attorney's fallacy, says "there are about 10 matching people, so the match is worthless": it isn't; it cuts 8.8 million suspects down to about 10.

A picture of the reasoning. Of the roughly 9.8 people in New York who would match, only one is the source:

R
ggplot(data.frame(who = c("true source", "innocent matches"), n = c(1, 8.8)),
       aes(who, n)) +
  geom_col(width = 0.5) +
  labs(x = NULL, y = "expected matches")
Bar chart with two barsBar chart with two bars: 1 person who is the true source of the blood, and about 8.8 innocent people expected to match by chance among 8.8 million New Yorkers. The innocent bar is almost nine times as tall. 0.0 2.5 5.0 7.5 innocent matches true source expected matches

Prediction and inference. The match probability is a prediction (how often would an innocent person match?); the jury's question is inference (who left the blood?). Bayes' theorem is the bridge, and the size of the suspect population is the part the prosecutor left out.

History: Sally Clark

In 1999 Sally Clark, an English solicitor, was convicted of murdering her two baby sons, who had died suddenly as infants. A paediatrician, Sir Roy Meadow, testified that the chance of two sudden infant deaths in a family like hers was about 1 in 73 million. He got this by squaring the figure of about 1 in 8,500 for one death, which assumes the two deaths were independent, when genetic and environmental factors shared within a family make a second death far more likely. Worse, the court heard the small number as the probability she was innocent: the prosecutor's fallacy. The right comparison is between the probability of the evidence under each explanation, and double murder by a mother is itself extremely rare.

The Royal Statistical Society wrote publicly to point out the errors. Clark's conviction was overturned on appeal in 2003, after it emerged that evidence of an infection in her second son had not been disclosed. She never recovered from the ordeal and died in 2007. Two misused rules of this chapter, independence and conditional probability, helped imprison an innocent woman.

Example 3.20: A Word That Signals Spam

Of the emails arriving at a company, 45% are spam. The word "free" appears in 30% of spam emails and in 2% of genuine emails. An email contains "free". What is the probability it is spam?

Translate. S = spam, F = contains "free". Pr(S)=0.45; "in 30% of spam emails" gives Pr(F∣S)=0.30; "in 2% of genuine emails" gives Pr(F∣Sc)=0.02. We want Pr(S∣F).

Count. Of 1,000 emails, 450 are spam and 135 of those contain "free"; 550 are genuine and 11 of those contain "free". So Pr(S∣F)≈135/146.

Bayes' theorem gives the same: Pr(S∣F)=0.30×0.450.30×0.45+0.02×0.55=0.1350.146≈0.925. One word moves the probability of spam from 45% to over 92%. Early spam filters combined many words this way, treating them (wrongly, but usefully) as independent given the email's type: a method called naive Bayes. The numbers here are illustrative, but the method was used by real filters from the late 1990s onwards.

Bayesian Inference: Bayes' Theorem as a Way of Learning

The detective's recipe is the whole of Bayesian statistics. Applied to yes/no events, it's what you've just seen. Applied to unknown quantities (the true rate of a disease, the true effect of a drug), the "suspects" are all the possible values of the quantity, and the same prior × likelihood rule turns data into a posterior distribution. That is the subject of the Bayesian boxes in Chapters 5 to 9.

A friend claims to be psychic, able to call coin flips correctly 75% of the time. You're sceptical. Choose your prior and watch the evidence move you, one call at a time.

Updating a belief one observation at a time

A self-proclaimed psychic says they call coin flips correctly a proportion q of the time; a fraud would be right half the time. Choose your prior belief that the psychic is genuine, then record their predictions one at a time, or let the widget simulate ten calls by a fraud or by a genuine psychic. Each observation turns the current posterior into the prior for the next one. Try a sceptical prior like 0.001 and see how much evidence it takes to move you.

The posterior probability that the psychic is genuine, plotted after each predictionThe posterior probability that the psychic is genuine, plotted after each prediction.

A very sceptical prior needs a great deal of evidence to overturn. That is how science should treat extraordinary claims: as the astronomer Carl Sagan put it, "extraordinary claims require extraordinary evidence." Bayes' theorem makes the saying precise.

History: Bayes, Price and Laplace

The Reverend Thomas Bayes, an English Presbyterian minister, worked out how to reason from evidence back to causes, but never published it. After his death in 1761, his friend Richard Price edited his notes and read An Essay towards solving a Problem in the Doctrine of Chances to the Royal Society in 1763. The French mathematician Pierre-Simon Laplace discovered the same idea independently in 1774 and developed it far more fully, using it to analyse everything from birth ratios to the masses of planets. For much of the twentieth century Bayesian ideas were out of fashion among statisticians. Today, with computers to do the calculations, they are everywhere, from spam filters to search-and-rescue planning.

Check Yourself

A rapid drug test detects a drug in 95% of users and gives a false positive for 5% of non-users. In a group of athletes, 2% use the drug.

What fraction of all the athletes' tests will be positive?

An athlete tests positive. What is the probability they use the drug?

In the Gigerenzer study (Example 3.18), many gynaecologists answered 81% or 90%. What mistake gives 90%?
A witness says the getaway car was blue. Witnesses identify colours correctly 80% of the time. In the city, 15% of cars are blue. Which is the best estimate of the probability the car really was blue?

Think About It: Learning from Evidence, One Clue at a Time

In the detective widget, the order of the clues didn't change the final answer. Now imagine two detectives who start with different priors (one suspects Ash, the other Drew) but see the same clues. As more and more clues arrive, what do you expect to happen to their posteriors? What does that suggest about how science reaches agreement?

As evidence accumulates, the likelihoods come to dominate the priors, and the two detectives' posteriors move closer together, provided neither started with a prior of exactly 0 for the truth (a closed mind can never be persuaded). This is how science is supposed to work: people with different hunches converge on the same conclusion when the evidence is strong enough. It's also why Bayesian inference is described as learning: the data, not the starting opinions, eventually decide.

Key Takeaways

  • Law of total probability: Pr(A)=∑iPr(A∣Bi)Pr(Bi): add up the clue's probability over all possible causes.
  • Bayes' theorem turns Pr(A∣B) into Pr(B∣A); posterior ∝ likelihood × prior.
  • Count first: natural frequencies (imagine 1,000 cases) make both results transparent.
  • For rare conditions, most positives are false positives. Never ignore the base rate.
  • The prosecutor's fallacy confuses Pr(evidence∣innocent) with Pr(innocent∣evidence).
  • Bayes is a recipe for learning: today's posterior is tomorrow's prior.

Prediction and inference so far

Notice the two directions in this section. The law of total probability is a prediction: from the mechanism (labs and their error rates, or a disease and a test) it forecasts how often the evidence will appear. Bayes' theorem is inference: from the evidence it reasons back to the cause. The whole of statistics has this two-step shape, and the rest of the course keeps returning to it: first understand what each possible mechanism predicts (Chapters 4 to 7), then compare those predictions with the data to learn which mechanism is at work (Chapters 8 and 9).

3.7 Simulation: probability by computer

Some probability problems are hard to solve on paper but easy to simulate: make the computer play out the random experiment many times, and count. By the Law of Large Numbers the fraction of successes approaches the true probability, just as an empirical probability from real data does (Section 3.1). Every simulation follows the same recipe:

  1. write code that performs the experiment once and returns the outcome;
  2. repeat it many times with replicate();
  3. compute the fraction of repetitions in which the event happened, with mean().

How accurate is a simulation? Here are eight independent simulations of the probability of rolling a six, each running to 5,000 rolls. Every run wanders at first and then settles near 16, inside the dashed funnel, which narrows like 1/n (Chapter 7 explains why). To halve the error of a simulation, you need four times as many repetitions.

R
set.seed(3)
grid <- unique(round(10^seq(0, log10(5000), length.out = 300)))
runs <- do.call(rbind, lapply(1:8, function(r) {
  est <- cumsum(sample(1:6, 5000, replace = TRUE) == 6) / (1:5000)
  data.frame(run = r, n = grid, est = est[grid]) }))
band <- data.frame(n = grid, lo = 1/6 - 2 * sqrt(5/36 / grid), hi = 1/6 + 2 * sqrt(5/36 / grid))
ggplot(runs, aes(n, est, group = run)) +
  geom_line(colour = "steelblue", alpha = 0.6) +
  geom_line(data = band, aes(n, lo), inherit.aes = FALSE, linetype = "dashed") +
  geom_line(data = band, aes(n, hi), inherit.aes = FALSE, linetype = "dashed") +
  geom_hline(yintercept = 1/6) +
  scale_x_log10() + coord_cartesian(ylim = c(0, 0.5)) +
  labs(x = "number of simulated rolls (log scale)", y = "estimated Pr(six)")
Eight line plots, on one set of axes, of the running proportion of sixes in simulated die…Eight line plots, on one set of axes, of the running proportion of sixes in simulated die rolls, against the number of rolls on a logarithmic axis from 1 to 5,000. Each line swings widely in the first few dozen rolls, then all eight settle close to a horizontal line at one sixth. Dashed curves at one sixth plus and minus two standard errors form a funnel that narrows as the number of rolls grows; the lines stay mostly inside it. 0.0 0.1 0.2 0.3 0.4 0.5 1 10 100 1000 number of simulated rolls (log scale) estimated Pr(six)

Simulation is also the best way to check a calculation you're unsure of: if the formula and the simulation disagree, one of them is wrong. Here is the most argued-about probability puzzle of all.

Let's make a deal

A car is behind one door, goats behind the others. Pick a door. The host, who knows where the car is, then opens every other door except one, always revealing goats. Do you stick with your door or switch to the one he left closed? Play a few rounds by hand, then let the computer play thousands of times with each strategy. Try 10 doors too: it makes the answer much easier to see.

A row of doors, each a button you can pickA row of doors, each a button you can pick. The chosen door is outlined; doors opened by the host show goats; the result is shown after you stick or switch.

Example 3.21: The Monty Hall Problem ★ lecture example

On a game show, a car is behind one of three doors and goats are behind the other two. You pick a door. The host, who knows where the car is, opens one of the other doors to reveal a goat (choosing at random if both hide goats), then offers you the chance to switch to the remaining closed door. Should you switch? Simulate it, then explain the answer.

Step 1: one play of the game, returning whether each strategy wins:

R
play_once <- function() {
  car  <- sample(1:3, 1)
  pick <- sample(1:3, 1)
  goats_not_picked <- setdiff(1:3, c(pick, car))   # doors the host may open
  host <- goats_not_picked[sample(length(goats_not_picked), 1)]
  switch_to <- setdiff(1:3, c(pick, host))
  c(stick = pick == car, switch = switch_to == car)
}
set.seed(1990)
results <- replicate(10000, play_once())    # step 2: repeat
rowMeans(results)                           # step 3: fraction of wins for each strategy
output
 stick switch 
0.3285 0.6715 

(setdiff(a, b) gives the elements of a not in b. Sampling positions with sample(length(x), 1) avoids a quirk of sample() when x has only one element.)

Sticking wins about 1/3 of the time; switching wins about 2/3. Switch.

Why? Your first pick is right with probability 13, and nothing the host does changes that, because he can always open a goat door, so opening one tells you nothing about your own door. Sticking wins only if your first pick was right: probability 13. Switching wins whenever your first pick was wrong, probability 23, because then the host is forced to leave the car behind the other closed door.

The same answer by Bayes' theorem. Say you pick door 1 and the host opens door 3. Let Ci = "car behind door i", each with prior 13, and H3 = "host opens door 3". The likelihoods are Pr(H3∣C1)=12 (he could open 2 or 3), Pr(H3∣C2)=1 (he must open 3), and Pr(H3∣C3)=0 (he never reveals the car). So Pr(C2∣H3)=1×1312×13+1×13+0×13=1312=23.

With 10 doors (try it in the widget) the logic is obvious: you pick one door, the host opens 8 goat doors and leaves one closed. Would you stick? The key is that the host's choice is not random: it depends on where the car is. Information hides in what he was forced to do.

History: The Puzzle That Fooled Mathematicians

In September 1990 the columnist Marilyn vos Savant answered the Monty Hall problem in Parade magazine: switch. She received about 10,000 letters, many from people with PhDs, telling her she was wrong. She wasn't. The great mathematician Paul Erdős reportedly refused to believe the answer until he was shown a computer simulation. Sometimes the most convincing proof is the one you can run.

Check Yourself

What does mean(replicate(10000, sum(sample(1:6, 2, replace = TRUE)) == 7)) estimate?
In the Monty Hall game, suppose instead the host doesn't know where the car is and opens one of the other two doors at random; it happens to show a goat. Now what is your chance of winning if you switch?

Think About It: When Should You Trust a Simulation?

A simulation of 10,000 Monty Hall games gives a switching win rate of 0.664. A friend says: "That's not exactly 2/3, so the simulation proves the answer isn't 2/3." How would you respond? How could you make the simulation more convincing?

A simulation estimates a probability by an empirical frequency, so it has random error: with 10,000 games the estimate typically misses the true value by about 0.005 (Chapter 7 shows how to compute this). 0.664 is well within that error of 0.667, so it's entirely consistent with 2/3, and far from 1/2. To be more convincing, run more games (100 times as many games shrinks the error by a factor of 10), or run several independent simulations and see how much they vary. Treating a simulation's output as exact is a common mistake: it's data, and needs the same inference as any other data.

Key Takeaways

  • Simulate: write one experiment, replicate() it many times, take the mean() of the event.
  • Simulation checks intuition and handles problems too hard for pen and paper.
  • How evidence was produced matters as much as the evidence itself.

3.8 Random variables

Turning outcomes into numbers

So far, outcomes have been described in words: "positive", "survived", "goat behind door 2", "HHT". But most questions are about numbers: how many bags are fake, how many passengers show up, how long a component lasts, how much a test reading is. A random variable attaches a number to every outcome, so that we can do arithmetic with uncertainty.

Diagram of a random variableDiagram of a random variable. On the left, the sample space for two coin tosses contains four outcomes: HH, HT, TH and TT. Curved arrows labelled X equals number of heads carry each outcome to a point on a number line on the right: HH goes to 2, HT and TH both go to 1, and TT goes to 0.sample space S012real numbers: the values of XHHHTTHTTX = number of heads
A random variable is a function: every outcome is sent to exactly one number, and different outcomes may share a number.

Definition: Random Variable

A random variable is a function that assigns a real number to each outcome in a sample space. We write random variables with capital letters (X, Y, T) and the values they take with lower-case letters (x, y, t). The event "X takes the value x" is the set of outcomes that X sends to x: {X=x}={ω∈S:X(ω)=x}, read "the outcomes ω in S for which X(ω)=x". Its probability is written Pr(X=x).

The picture above shows the definition at work. Toss two coins, so S={HH,HT,TH,TT}, and let X be the number of heads. Every outcome is sent to exactly one number (X is a function), but two outcomes, HT and TH, are sent to the same number, 1. So the event {X=1} is {HT,TH}, with probability 24. A random variable groups outcomes by the feature we care about and forgets everything else (here, the order of the heads).

The word "random variable" is a little misleading. It isn't a variable, and it isn't random: it's a fixed rule. The randomness is in the outcome the experiment produces; the rule then turns that outcome into a number. Try different rules on the same experiment:

A random variable is a rule that turns outcomes into numbers

Roll two dice. The 6 × 6 grid on the left is the sample space: 36 equally likely outcomes (first die, second die). Choose a random variable: each outcome is labelled with the number the rule gives it, and coloured by that number. On the right, the distribution counts how many outcomes get each number. Click a bar (or use the value buttons) to light up the event {X = x}: the outcomes that the rule sends to x.

LeftLeft: a 6 by 6 grid of outcomes of two dice, each labelled with the value of the random variable. Right: bar chart of the distribution; each bar can be clicked to highlight its outcomes.

The same 36 outcomes give quite different distributions depending on the rule. Every rule here is a perfectly good random variable; which one you use depends on the question you're asking.

History: An Unknown, by Another Name

Not every awkward name in statistics has a troubling history; some are just confusing. "Random variable" is one of these. In Bernoulli's Fallacy (2021), Aubrey Clayton suggests replacing it with a plainer word: an unknown. The number of heads in two tosses isn't "random" in itself. It is a definite number that we don't know yet, and probability describes our uncertainty about it. This way of thinking fits the Bayesian boxes especially well, where probability measures what we know.

We keep the standard term, because you'll meet it in every other book and course. But when a problem says "let X be a random variable", it's often helpful to read it as "let X be an unknown quantity".

Anything can be a number

Random variables need numbers, but outcomes don't have to be numerical to begin with. With a little care, almost anything can be encoded as a number:

outcome random variable type
a drug test is positive or negative X=1 if positive, 0 if negative discrete (an indicator)
20 bags are tested X = number of fakes found discrete (a count: 0 to 20)
a website gets visits for an hour X = number of visits discrete (a count: 0, 1, 2, ...)
a glass fragment is analysed X = refractive index continuous (a measurement)
a patient is followed after surgery T = time until infection, in days continuous
the next word in a sentence X = the word's position in a dictionary of 50,000 words discrete (a label coded as a number)

The 0/1 indicator is the most useful encoding of all: it turns any yes/no event into a number, and its average is the proportion of "yes" (Example 3.2 used exactly this when mean(e > 3) averaged TRUEs and FALSEs). Language models encode words as numbers too (the last row), though, as with the race codes in Section 1.4, the numbers are labels: the "average word" means nothing.

Some quantities are naturally discrete: you can list their possible values, with gaps in between. Counts are the main example: you can have 3 fake bags or 4, never 3.7. Others are naturally continuous: they can take any value in an interval. Measurements of time, length, weight and concentration are the main examples. (In practice every measurement is rounded, but we model the true value as continuous.) The two kinds need different mathematics: for discrete random variables we can list Pr(X=x) for every value, while for continuous ones every single value has probability zero (the dart in Section 3.3), and we need areas under curves. Chapter 4 studies the discrete kind and Chapter 5 the continuous.

Definition: Distribution of a Random Variable

The distribution of a random variable is a description of which values it can take and with what probabilities. For a discrete random variable it can be given as a table of all possible values x and their probabilities Pr(X=x), which must be non-negative and add to 1.

The airline in Chapter 1 cared about X, the number of ticket holders who show up. The lab in Example 3.11 cares about Y, the number of fakes in its sample of 20. Both are discrete random variables, and Chapter 4 gives their distributions names (binomial and hypergeometric).

Example 3.22: The Total of Two Dice ★ lecture example

Roll two fair dice and let X be their total. Find the distribution of X, check it by simulation, and find Pr(X≥10).

The outcomes. There are 6×6=36 equally likely outcomes (first die, second die), by case 1 of the counting rules.

The rule. X sends each outcome to its total. For example, X=4 for the outcomes (1,3), (2,2), (3,1), so the event {X=4} contains 3 outcomes and Pr(X=4)=3/36. Doing this for every total gives the distribution:

x 2 3 4 5 6 7 8 9 10 11 12
outcomes 1 2 3 4 5 6 5 4 3 2 1

with Pr(X=x) = (number of outcomes)/36. Check: 1+2+3+4+5+6+5+4+3+2+1=36, so the probabilities add to 1. R can do the counting:

R
totals <- outer(1:6, 1:6, "+")      # a 6 x 6 table of all 36 totals
totals
table(totals) / 36                  # the distribution of X
output
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    2    3    4    5    6    7
[2,]    3    4    5    6    7    8
[3,]    4    5    6    7    8    9
[4,]    5    6    7    8    9   10
[5,]    6    7    8    9   10   11
[6,]    7    8    9   10   11   12
totals
         2          3          4          5          6          7 
0.02777778 0.05555556 0.08333333 0.11111111 0.13888889 0.16666667 
         8          9         10         11         12 
0.13888889 0.11111111 0.08333333 0.05555556 0.02777778 

So Pr(X=7)=6/36 is the most likely total, and the probabilities fall away symmetrically on either side. Now simulate 100,000 rolls and compare the empirical probabilities with the exact ones:

R
set.seed(36)
sim <- sample(1:6, 1e5, replace = TRUE) + sample(1:6, 1e5, replace = TRUE)
exact <- as.data.frame(table(totals) / 36)
names(exact) <- c("total", "prob")
simulated <- as.data.frame(table(sim) / 1e5)
names(simulated) <- c("total", "prob")
ggplot(exact, aes(total, prob)) +
  geom_col(width = 0.7) +
  geom_point(data = simulated, colour = "orange", size = 3) +
  labs(x = "total of two dice", y = "probability")
Bar chart of the distribution of the total of two dice, from 2 to 12Bar chart of the distribution of the total of two dice, from 2 to 12. Blue bars show the exact probabilities, rising from 1/36 at 2 to 6/36 at 7 and falling back to 1/36 at 12, a triangle shape. Orange dots show the fractions from 100,000 simulated rolls, sitting almost exactly on top of the bars. 0.00 0.05 0.10 0.15 2 3 4 5 6 7 8 9 10 11 12 total of two dice probability

The last part. The events {X=10}, {X=11}, {X=12} are disjoint, so by axiom 3 Pr(X≥10)=Pr(X=10)+Pr(X=11)+Pr(X=12)=3+2+136=16.

Check Yourself

Let X be the number of heads in 3 tosses of a fair coin.

What is Pr(X=2)?

Think About It: What Number Should We Record?

A researcher studying burglaries wants to turn each case into a random variable. Suggest three different random variables that could be defined on the same burglary (the same outcome), one discrete, one continuous and one indicator. Which would you choose to predict insurance claims, and which would help to infer whether a new policing strategy works?

For example: the number of items stolen (discrete), the value of the goods stolen in dollars (continuous, effectively), and 1 if entry was forced, 0 otherwise (indicator). For predicting insurance claims, the value stolen is the natural choice, since that is what the insurer pays. For evaluating a policing strategy, an indicator defined on each burglary, 1 if it was solved and 0 if not, is more relevant: averaged over many burglaries it gives a solve rate to compare before and after. (A count of burglaries per month is also useful, but it is a random variable on a month, not on one burglary.) The same outcomes support many random variables; choosing one is choosing which aspect of the world you are trying to predict or understand.

Key Takeaways

  • A random variable is a rule that attaches a number to each outcome; {X=x} is the event made of all outcomes sent to x.
  • Anything can be encoded as a number; a 0/1 indicator turns any event into a random variable.
  • Discrete random variables take listable values (counts); continuous ones take values in an interval (measurements).
  • The distribution says which values a random variable takes and how likely each is; probabilities of disjoint values add.

Prediction and inference in this chapter

Probability is the shared language of the course's two goals. The empirical probabilities of Section 3.1 predict future frequencies from past ones; the axioms and counting rules let us predict what a known mechanism will do (how often a sample of 20 bags misses every fake, how often 23 people share a birthday). Bayes' theorem turns prediction around into inference: the mammogram, the DNA match and the detective's notebook all reason from evidence back to causes, and the posterior of one step becomes the prior of the next. Random variables, introduced at the end, let us attach numbers to outcomes, so that the next two chapters can build whole families of models for counts and measurements, and Chapters 8 and 9 can learn the models' unknown numbers from data.

3.9 Exercises

Each exercise has a hint and an answer. For word problems, always start by naming the events and translating every number (Section 3.5).

Exercises

  1. Interpretations. For each statement, say which interpretation of probability (equally likely, long-run frequency, degree of belief) fits best, and why. (a) "The chance of drawing an ace from a shuffled deck is 1/13." (b) "This breathalyser gives a reading above the true value 2% of the time." (c) "I'm 90% sure the defendant was at the scene."

    Ask: is there a symmetry argument? Is there a repeatable process whose long-run behaviour is being described? Or is it a one-off judgement?

    (a) Equally likely: 4 aces among 52 symmetric cards. (b) Long-run frequency: it describes what happens over many readings (and would be estimated empirically). (c) Degree of belief: a one-off event that can't be repeated.

  2. Events. A server log records, for each request, whether it came from a known bot (B) and whether it was rejected (R). Write in symbols, and in words, the complement of B∪R. Use De Morgan's law to write it another way.

    B∪R means "from a bot, or rejected, or both". What is the opposite of "at least one of these"?

    (B∪R)c: requests that were neither from a known bot nor rejected. By De Morgan, (B∪R)c=Bc∩Rc: not from a bot and not rejected.

  3. Addition rule in R. Using xtabs(Freq ~ Class + Age, data = as.data.frame(Titanic)), find the probability that a randomly chosen person aboard was in third class or was a child. Check your answer by counting directly.

    You need Pr(third), Pr(child) and Pr(third∩child) from the table, each as a count over 2,201.

    Third class: 706; children: 109; third-class children: 79. Pr=(706+109−79)/2201=736/2201≈0.334. Counting directly: all 706 in third class plus the 6+24=30 children in first and second class (there were no children in the crew) gives 736.

  4. Passwords. A system requires passwords of exactly 10 characters, each a lowercase letter or digit. (a) How many passwords are possible? (b) At 1010 guesses per second, how long would an exhaustive search take? (c) Why might real attacks be much faster than your answer suggests?

    Which of the four counting cases applies? There are 26+10=36 symbols for each position.

    (a) Order matters, with replacement: 3610≈3.66×1015. (b) 3.66×105 seconds, about 4.2 days. (c) People don't choose passwords uniformly at random: attackers try dictionary words, names, dates and common patterns first, and often succeed long before searching the whole space.

  5. Sampling a seizure. In Example 3.11, how many bags would the lab need to test for the chance of missing all 100 fakes to fall below 5%? Use R: compute choose(1900, k) / choose(2000, k) for a range of k.

    k <- 1:100; p <- choose(1900, k) / choose(2000, k), then find the smallest k with p < 0.05, for example with min(k[p < 0.05]). The plot in Example 3.11 shows roughly where to look.

    58 bags. With 58 bags the chance of finding no fakes is just under 5%; with 57 it is just over. Note this is far fewer than 5% of 2,000 = 100: the number needed depends mostly on the fraction of fakes, not on the size of the seizure.

  6. Birthday matches in a database. A database holds DNA profiles of 1,000 people. Suppose any two unrelated profiles match with probability one in a million. (a) How many pairs of profiles are there? (b) About how many matching pairs would you expect by chance? (c) Explain why searching a database for any match is very different from comparing one suspect with one crime scene.

    (a) is case 3: choosing 2 profiles from 1,000, order doesn't matter. For (b), multiply the number of pairs by the chance that one pair matches. Recall the birthday problem.

    (a) (10002)=499,500 pairs. (b) About 499,500×10−6≈0.5 matching pairs, so a chance match somewhere in the database is quite plausible. (c) One comparison has a one-in-a-million chance of a coincidental match, but a search makes hundreds of thousands of comparisons, so coincidences become likely, just as 23 people make 253 pairs of birthdays.

  7. Titanic conditioning. Using R, find Pr(survived∣child) and Pr(survived∣child, third class). What does the comparison suggest? Draw a DAG with class, age and survival, and explain why the overall survival rate of children is a mixture.

    xtabs(Freq ~ Age + Survived, data = tt) and the same for subset(tt, Class == "3rd"); then use prop.table(..., 1). Also look at the survival of children in first and second class.

    Pr(survived∣child)=57/109≈0.52, but among third-class children only 27/79≈0.34; every one of the 30 children in first and second class survived. Class affected both who the children were (most children were in third class) and survival, so the overall rate for children is a weighted average (law of total probability) of very different class-specific rates. DAG: class → survival, age → survival, and class and age connected (families with children travelled mostly in third class).

  8. Independent tests? Two drug-screening tests are each wrong 5% of the time. A lab says that the chance both are wrong on the same sample is 0.052=0.0025. Under what assumption is this right? Give a realistic reason it might fail.

    When is Pr(A∩B)=Pr(A)Pr(B)? Think about what might make both tests fail on the same sample.

    It assumes the two tests' errors are independent. They may not be: if both tests react to the same interfering substance (for example, a cold medicine that both mistake for a drug), or the sample itself is contaminated or degraded, a sample that fools one test is likely to fool the other. Then Pr(both wrong) could be much larger than 0.0025, as with the dependent detectors in Example 3.14.

  9. Bayes for fingerprints. An automated fingerprint system flags a "match" for 99% of true matches and for 0.1% of non-matches. A search compares a crime-scene print with 50,000 prints from people who are not the source, and with the true source's print. (a) How many false matches do you expect? (b) Given that the system reports a match for one particular person, what is the probability that person is the source? (c) Explain your answer to a juror without using any formulas.

    Use natural frequencies: 50,000 non-sources, each flagged with probability 0.001; 1 source, flagged with probability 0.99. Then ask what fraction of all flagged people are the source.

    (a) 50,000×0.001=50 false matches. (b) About 0.99/(0.99+50)≈0.019, roughly 2%. (c) "The computer compared the print with over 50,000 people. Even though it rarely makes a mistake on any one comparison, with that many comparisons we'd expect it to wrongly flag about 50 innocent people, alongside the one real source. So on the match alone, this person is just one of about 51 people flagged."

  10. Simulation. Write an R simulation to estimate the probability that, in a group of 30 people, at least three share a birthday. (Hint: any(table(birthdays) >= 3).)

    One experiment: birthdays <- sample(365, 30, replace = TRUE), then check any(table(birthdays) >= 3). Wrap it in replicate(100000, ...) and take the mean().

    mean(replicate(1e5, any(table(sample(365, 30, replace = TRUE)) >= 3))) gives about 0.029: a triple match in 30 people is unusual, even though a pair is likely (0.71).

  11. Conditioning on a collider. A university admits students who have high test scores or excellent essays (or both). In the applicant pool, scores and essay quality are independent. Explain why, among admitted students, those with lower scores tend to have better essays. Draw the DAG.

    Admission is caused by both scores and essays. If an admitted student has a low score, what must have got them in?

    DAG: score → admitted ← essay. Among admitted students, anyone with a low score must have been admitted for an excellent essay, while high scorers could have any essay. So within the admitted group, lower scores go with better essays: a negative association created entirely by selecting on the collider (Berkson's paradox), even though scores and essays are unrelated among applicants.

  12. Translate and solve. At an airport, 0.1% of bags contain a prohibited item. The scanner flags 98% of bags that contain one, and 3% of bags that don't. (a) Translate every number into a probability statement. (b) What fraction of all bags are flagged? (c) A bag is flagged. What is the probability it contains a prohibited item?

    Let P = "contains a prohibited item" and F = "flagged". "98% of bags that contain one" restricts to bags in P. For (b) use total probability, for (c) Bayes; or imagine 100,000 bags.

    (a) Pr(P)=0.001, Pr(F∣P)=0.98, Pr(F∣Pc)=0.03. (b) Pr(F)=0.98×0.001+0.03×0.999=0.00098+0.02997=0.03095, about 3.1%. (c) Pr(P∣F)=0.00098/0.03095≈0.032. Out of 100,000 bags: 100 contain an item and 98 are flagged; 99,900 don't, and 2,997 are flagged; so only about 98 of 3,095 flagged bags (3%) contain anything. That's acceptable for screening, because a flagged bag just gets a closer look.

  13. Choosing the counting case. For each question, say which of the four counting cases applies, and give the answer. (a) How many ways can a jury of 12 be chosen from a pool of 30? (b) How many 3-letter codes can be made from 26 letters if letters may repeat? (c) A forensic team must place 5 identical evidence markers into 3 rooms. In how many ways? (d) How many ways can 4 of 10 detectives be assigned to 4 different shifts, one each?

    For each, ask: does order matter? Are repeats allowed? In (c), the markers are identical, so all that matters is how many go in each room.

    (a) Unordered, without replacement: (3012)=86,493,225. (b) Ordered, with replacement: 263=17,576. (c) Unordered, with replacement (stars and bars, n=3 rooms, k=5 markers): (75)=21. (d) Ordered, without replacement: 10×9×8×7=5,040.