Chapter 3
Probability
Lectures 5–8 · the language of uncertainty, how to reason with it, and how it goes wrong
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.
- Sections 3.1 to 3.3 set up the language: what a probability means, how to describe events as sets, and the three rules every probability must obey.
- Section 3.4 turns probability into counting, for situations where every outcome is equally likely.
- Sections 3.5 and 3.6 are the heart of the chapter: how probabilities change when we learn something (conditional probability), how to translate a word problem into symbols, and how to reason backwards from evidence to causes (Bayes' theorem).
- Section 3.7 shows how to let a computer do the work by simulation.
- Section 3.8 attaches numbers to outcomes, which sets up the next two chapters.
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.
- How many people do you need in a room for it to be more likely than not that two of them share a birthday?
- 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?
- 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 ? People have given three different answers.
- 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.
- Long-run frequency (frequentist). Flip the coin many, many times: the fraction of heads settles down to . 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.
- 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.
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 . Use R to roll a die 10, 100, 1,000 and 100,000 times, and compare the fraction of sixes with .
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.
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")
}
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 . With 100,000 rolls it's within a fraction of a percentage point. Notice that the error shrinks as 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 , 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:
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")
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 times, and event happened in of them. The empirical probability (or relative frequency) of is
The Law of Large Numbers is what makes empirical probabilities worth computing: if the observations are independent repetitions of the same experiment, then as grows, settles down to the true . 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 = "lasts more than 3 minutes". We count how many of the 272 eruptions are in .
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
[1] 175
[1] 272
[1] 0.6433824
[1] 0.55
So cumsum() gives running totals:
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")
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
There aren't four symmetric outcomes, and this one patient can't be treated over and over. Which reading still makes sense for a one-off event?
It's a statement about one patient, so it is most naturally a degree of belief, informed by data on similar patients. (A frequentist would rephrase it: "among patients like this one, about 25% respond", an empirical probability.)
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?
Count the times the event happened and divide by the number of observations.
Does the coin remember what it did? This belief has a name: the gambler's fallacy.
Suppose the next 990 flips come out exactly half heads. Is the excess of heads gone, or just small compared with the total?
The coin has no memory. After 10 flips with 7 heads, if the next 990 are exactly half heads you'd have 502 heads in 1,000: still 2 extra heads, but the fraction is 0.502. The fraction settles down because the early excess is swamped, not corrected.
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 estimates 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 .
- 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 of an experiment is the set of all its possible outcomes.
- An event is a set of outcomes, that is, a subset of . An event occurs if the outcome of the experiment is one of its members.
Some examples:
- A drug screen returns negative, inconclusive or positive:
. The event "not negative" is . - We count failed login attempts on a server in one hour:
. The event "more than 5 attempts" is . - We measure the time, in hours, until a lab centrifuge fails: . The event "it lasts at least 1,000 hours" is the interval .
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 ?", 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 and in a sample space :
- or (the union) : the outcomes in , in , or in both.
- and (the intersection) : the outcomes in both and .
- not (the complement) : the outcomes in that are not in .
- and are disjoint (or mutually exclusive) if they can't both happen: , where is the empty set, the event containing no outcomes.
- is a subset of , written , if every outcome in is also in : whenever happens, happens.
In mathematics, "or" always means "one or the other or both." Venn diagrams make these operations visible: draw as a rectangle and events as regions inside it. The shaded outcomes belong to the event.
Some combinations are built from these: " but not " is , and "exactly one of and " is . The best way to get fluent is to practise in both directions: from a picture to symbols, and from symbols to a picture.
Theorem: De Morgan's Laws
For any events and ,
First law. We show the two sets contain exactly the same outcomes. An outcome is in exactly when it is not in . That means it is in neither nor : it is not in (so it's in ) and not in (so it's in ). So it is in . Every step can be read backwards, so the two sets are equal.
Second law. Apply the first law to the events and (whose complements are and ): Taking the complement of both sides gives
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 () and whether the attempt came from a new device (). Write each event in symbols:
- The password was wrong.
- The password was correct and the device was new.
- At least one warning sign: a wrong password or a new device.
- No warning signs.
Strategy. Translate each phrase piece by piece: "wrong password" is "not "; "and" is ; "or" (and "at least one") is ; "no ... at all" is the complement of "at least one".
- .
- .
- The two warning signs are and , so "at least one" is .
- Neither warning sign: the password was correct and the device was not new, . By De Morgan this is , 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 ( = "a usable print was recovered") and a DNA swab ( = "a usable DNA profile was recovered").
"At least one" means one or the other or both. Which set operation means that?
: the print, the DNA, or both.
"No evidence" means no usable print and no usable DNA. Then compare with De Morgan's laws.
, which by De Morgan equals : the complement of "at least one". Note is different: it means "at least one test failed".
"But" means "and". Which event is required, and which is ruled out?
: in , and not in . Shade it in the two-event widget to check.
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 assigns to each event a number such that:
- for every event ;
- ;
- if are events no two of which can happen together (pairwise disjoint), then
Everything else follows from these. Here are the consequences you'll use constantly.
Theorem: Consequences of the Axioms
For any events and :
- Complement rule.
. - The impossible event. .
- Bounds. , and if (whenever happens, so does ) then
. - Addition rule.
. - Union bound.
.
We prove 2 first.
and are disjoint and together make up . By axiom 3 (for two events) and axiom 2,
. Subtract . Shown above.
If , split into the disjoint pieces and . Then
by axiom 1. Taking gives . Split into three disjoint pieces: only (), both (), and only (). Then
Adding the last two lines counts the middle piece twice, so . Rearrange. From 4, because . ∎
The addition rule is easiest to see in a picture. Move the sliders, and watch which areas get counted twice.
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: = female, = child. The question asks for ("or").
First the counts of sex by age group:
tt <- as.data.frame(Titanic) # one row per combination, with a count
xtabs(Freq ~ Sex + Age, data = tt) # cross-tabulate sex by age
Age
Sex Child Adult
Male 64 1667
Female 45 425
There were
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.
- On what fraction of days did at least one detector raise a false alarm?
- On what fraction of days did neither?
- Without knowing the 1% figure, what can you say for certain about part 1?
Reading the problem. Let and be the events that detectors A and B falsely alarm on a given day. Then , ,
- Addition rule:
. - Complement rule:
. - The union bound gives
, whatever the overlap.
Notice the detectors are far from independent (Section 3.5): if they were, both would alarm on only
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)?
Add the two probabilities, then remove what you counted twice.
What is the probability that it involves neither?
"Neither" is the complement of "one or the other or both".
.
What is the probability that it involves forced entry but did not happen at night?
Forced entry splits into "forced and night" and "forced and not night". You know the total and one piece.
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
. Addition rule . - "At least one" problems are often easiest through the complement: .
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 has outcomes, all equally likely, then for any event containing outcomes, In words: the number of outcomes in divided by the number of outcomes in .
The single outcomes are disjoint and together make up , so by axioms 2 and 3 their equal probabilities add to 1: each has probability . The event is the disjoint union of its outcomes, so
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 stages, with ways to do stage 1, then ways to do stage 2 (whatever happened in stage 1), and so on, the whole task can be done in ways.
Picture a tree: branches for stage 1, each splitting into 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 partial paths; each splits into , giving after stage 2; and so on. After stages there are paths. ∎
For example, a meal deal with 3 mains, 4 sides and 2 drinks gives different meals.
The four ways to choose
Most counting problems ask: in how many ways can we choose items from distinct items? The answer depends on two questions, which you should ask every time:
- Does order matter? Is "Alice then Bob" different from "Bob then Alice"? For a race (gold, silver), yes; for a committee, no.
- 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 | ||
| order doesn't matter |
Here 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: PINs.
Theorem: Ordered Selections with Replacement
The number of ordered sequences of length whose entries are each chosen from distinct items, repeats allowed, is .
Each of the positions is a stage with choices, whatever was chosen before. By the multiplication rule, there are
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 () guesses per second. How long does it take to try every possible password of length 8 if passwords use:
- lowercase letters only (26 symbols)?
- upper- and lowercase letters and digits (62 symbols)?
- 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 symbols in each of 8 positions there are passwords. Dividing by guesses per second gives the time in seconds.
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))
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
passwords: about 21 seconds. : about 6 hours. : 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:
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")
(The grey lines mark one day and one century.) Each extra character multiplies the work by , 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:
Theorem: Ordered Selections Without Replacement (Permutations)
The number of ordered sequences of different items chosen from distinct items is
Use the multiplication rule: choices for the first position, then for the second (one item is used up), down to
Factorials grow astonishingly fast. A deck of 52 cards can be shuffled into 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: 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 ways. So
Positions 1 to 3. The events "in position 1", "in position 2" and "in position 3" are disjoint, each with probability , so by axiom 3 the probability is .
factorial(6)
factorial(5) / factorial(6)
[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): equally likely lists.
- Lists with no repeats: 365 choices for person 1, 364 for person 2, ..., down to
for person 23 (case 2): .
So
1 - prod(365:343) / 365^23 # by the formula
pbirthday(23) # R has a built-in function
[1] 0.5072972
[1] 0.5072972
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)")
Why does intuition fail so badly? We think about our own birthday, and the chance someone else shares it is small:
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 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 panels. The same idea, dividing out the orderings, works in general.
Theorem: Unordered Selections Without Replacement (Combinations)
The number of ways to choose items from distinct items, without repeats and when order doesn't matter, is read " choose ". It is also the number of subsets of size of a set of size .
Count the ordered selections of items in two ways.
- Directly, by case 2: there are of them.
- In two stages: first choose which items (an unordered selection: ways, the number we want), then put those items in order ( ways, by case 2 with ). By the multiplication rule there are ordered selections.
Both count the same thing, so
Two quick checks:
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, ways. The red ball can be any of 26. By the multiplication rule there are equally likely outcomes, and one ticket matches exactly one of them.
choose(69, 5)
choose(69, 5) * 26
[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 per ticket, buying 100 tickets a week for 50 years (260,000 tickets) gives a chance of roughly
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: .
- Samples with no fakes: all 20 come from the 1,900 genuine bags, .
choose(1900, 20) / choose(2000, 20)
[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:
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)")
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 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 orders.
Theorem: Unordered Selections with Replacement (Stars and Bars)
The number of ways to choose items from distinct types, when order doesn't matter and types can repeat (equivalently, the number of ways to write
A selection is described completely by the counts of each type, with
- Every selection gives a row with exactly stars and 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 positions, and choosing which of them hold stars (the rest hold bars) determines it completely. By case 3 there are ways; choosing the 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
The widget lists every selection for small cases, so you can see where all four formulas come from.
Check Yourself
The cases are different, so does it matter which analyst gets which case? Can one analyst get two of the cases?
Giving case 1 to Ana and case 2 to Ben differs from the reverse, so order matters; and each analyst gets at most one case, so no replacement:
In how many different orders can 5 suspects be arranged in a line-up?
5 choices for the first position, then how many for the second?
A lab must choose 2 of its 5 analysts to review a case (order doesn't matter). How many different review panels are possible?
Ordered pairs: . How many times is each unordered pair counted in that 20?
choose(5, 2).
ignores order. Is 1234 the same PIN as 4321?
Each of 4 positions has 10 choices: equally likely PINs.
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?
This is case 4 with types and items: .
: the 15 boxes with two different flavours, , plus the 6 boxes with two of the same.
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 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, is the number of outcomes in divided by the total number of outcomes.
- Ask two questions: does order matter? are repeats allowed? Then: ; ; ; .
- 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:
Among the 470 women, 344 survived, so the probability of survival given that the person was female is
Definition: Conditional Probability
For events and with , the conditional probability of given is It is the probability of in a world where we know has happened. The vertical bar is read "given".
Check it on the Titanic:
Rearranging the definition gives a rule for "and" that we'll use all the time.
Theorem: Multiplication Rule
For events and with , More generally, for three events (with
Multiply both sides of the definition by . For three events, apply the two-event rule twice, first with :
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 : 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 and compare it with .
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.
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
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
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)")
- 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.
, but .
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. and 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.
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 . 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
- Name the events. Give each yes/no feature a letter: = "has the disease", = "tests positive". Use complements for the opposite ( = "doesn't have the disease") rather than new letters.
- 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 . If it's a subgroup, it's a conditional probability, with the subgroup after the bar.
- Translate the question the same way.
- Choose the rule that connects what you have to what you want: complement, addition, multiplication, total probability or Bayes.
- 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 " | |
| "40% of smokers have " / "if a person smokes, the chance of is 40%" / "among smokers..." | |
| "10% of patients both smoke and have " / "...are smokers with " | |
| "of those with , 25% smoke" | |
| "at least one", "either ... or" | union, |
| "neither", "none" | complement of the union |
| "the test is 95% accurate for people who have " (sensitivity) | |
| "a false-positive rate of 2%" |
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. = "was a victim", = "filed a report". Then = "not a victim".
Step 2, translate every number.
- "12% of adults were victims": a fraction of all adults, so . (So .)
- "Among victims, 35% reported": a fraction of victims, so it's conditional on :
. - "Among non-victims, 1% filed a report":
.
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 .
Notice that we were given and are asked for : 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
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
The same reasoning as a picture. The 508 reports split into two very unequal sources:
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)
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 = "from a vehicle window" and = "refractive index above 1.52".
"Of the fragments from vehicle windows" names the group you are restricted to. Does it go before or after the bar?
The group (vehicle windows) goes after the bar:
"Overall" means the group is all fragments. Is there any restriction?
No restriction: it's a plain probability, .
"Of all fragments" means no restriction; "both ... and" means intersection.
Independence
Sometimes learning that happened tells us nothing about : the probability stays the same.
Definition: Independent Events
Events and are independent if When this is the same as
Why are the two forms the same? If , dividing
For the Titanic,
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 and are disjoint and both possible, then knowing happened tells you for certain that didn't:
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 , and what does it mean?
If they were independent, both would alarm on
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 and there are 4 rolls, giving ; a double six has chance and there are 24 rolls, giving . 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 . 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 , so by the product rule
1 - (5/6)^4
1 - (35/36)^24
[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:
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)
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:
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 . 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 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:
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]))
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 : 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 . 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.
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?
Restrict to car owners:
Compare with , or check whether
4% would be the chance of at least one failing (approximately). Both failing needs camera 1 and camera 2 to fail.
For independent events,
Is 2% of 2% bigger or smaller than 2%?
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
Key Takeaways
: the probability of after zooming in to the outcomes where happened. - Multiplication rule
. - In a word problem, ask of every number: what fraction of what? The "of what" goes after the bar.
- and are independent if
. Disjoint events with positive probabilities are not independent. 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 be the events that a sample went to each lab, and that it comes back with an error. The question gives , , , and, because "lab 1 makes an error on 1% of its samples" restricts to lab 1,
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
(b) Now look only at the 21 samples with errors. Ten of them came from lab 3, so 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,
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).
Now the general statement. The idea is that the possible causes 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 .
Theorem: Law of Total Probability
Suppose the events are disjoint, have positive probability, and between them cover the whole sample space (exactly one of them happens). Then for any event ,
Because exactly one happens, splits into the disjoint pieces
The most common partition has just two pieces, and :
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 for "has cancer" and for "positive test". Then (all women),
Count first: natural frequencies. Imagine 1,000 women having a mammogram.
Ten have cancer, and 9 of them test positive. Of the 990 without cancer, 9% (about 89) also test positive. So there are positive tests, of which only 9 come from women with cancer:
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
In the study, only 21% of the gynaecologists chose the right answer (about 1 in 10); nearly half chose 90%, confusing with , 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 ; "how many of those show the clue" is ; "how many show the clue altogether" is , by total probability; and "what share of them have the cause" is . Writing that down in general gives the theorem.
Theorem: Bayes' Theorem
With a partition as in the law of total probability, and , where
By the definition of conditional probability, then the multiplication rule in the numerator,
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
- is the prior probability of : how plausible was before seeing the evidence ;
- is the likelihood: how probable the evidence is if is true;
- is the posterior probability of : how plausible is after seeing the evidence.
Bayes' theorem says: posterior ∝ likelihood × prior (the symbol ∝ means "proportional to"; dividing by 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.
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.
- List the suspects (the possible causes), and say how plausible each is before any evidence: the prior.
- 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.
- Multiply prior by likelihood for each suspect, then rescale so the results add to 1: the posterior.
- 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.
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."
- What is wrong with this argument?
- 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?
Translate the prosecutor's numbers. "The chance of a match if he were innocent" is
. The jury needs . These are different, just as 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. Count. Among about 8.8 million residents, one is the burglar, and he matches. Of the other 8.8 million, about
are expected to match by chance. So roughly people match, and our man is just one of them:
In Bayes' terms, the prior that this man is the source is , 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:
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")
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. = spam, = contains "free". ; "in 30% of spam emails" gives
Count. Of 1,000 emails, 450 are spam and 135 of those contain "free"; 550 are genuine and 11 of those contain "free". So
Bayes' theorem gives the same:
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.
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?
Law of total probability: positives come from users and from non-users.
An athlete tests positive. What is the probability they use the drug?
Bayes: divide the true positives, , by all positives (your previous answer). Or imagine 1,000 athletes and count.
Where does 90% appear in the question? Which conditional probability is it?
The prevalence is 1%, so using it would give a much smaller number. Which given number is exactly 90%?
90% is the sensitivity, . Reporting it as the answer confuses with , the same reversal as the prosecutor's fallacy.
That ignores the base rate. Of 100 cars, how many are blue? How many non-blue cars would be wrongly called blue?
That ignores the witness. Does the testimony change nothing?
Of 100 cars, 15 are blue and the witness calls 12 of them blue; 85 are not blue and the witness wrongly calls 17 of them blue. So of 29 "blue" reports, only 12 are right: about 41%. (This is a version of Kahneman and Tversky's famous "cab problem".)
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:
: add up the clue's probability over all possible causes. - Bayes' theorem turns into ; 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 with .
- 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:
- write code that performs the experiment once and returns the outcome;
- repeat it many times with
replicate(); - 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 , inside the dashed funnel, which narrows like (Chapter 7 explains why). To halve the error of a simulation, you need four times as many repetitions.
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)")
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.
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:
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
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 , 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 . Switching wins whenever your first pick was wrong, probability , 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 = "car behind door ", each with prior , and = "host opens door 3". The likelihoods are
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
Look at what each replicate returns: is it a total, or a TRUE/FALSE comparison?
mean() of TRUE/FALSE values gives a fraction, not a count.
Each replicate rolls two dice and checks whether the total is 7, giving TRUE or FALSE. The mean of 10,000 such values is the fraction of rolls totalling 7, which estimates the probability (exactly ).
The 2/3 relied on the host always being able to reveal a goat. When he opens a door at random, sometimes he reveals the car. How does seeing a goat by luck change things?
Try counting: there are 6 equally likely (car, door opened) combinations. Keep only those where the opened door shows a goat. In how many does switching win?
Of 3 × 2 = 6 equally likely (car position, random door opened) cases, 2 reveal the car and are thrown out. Among the remaining 4, switching wins in 2 and sticking in 2: probability ½ each. The same observation (a goat) means different things depending on the process that produced it, a lesson that runs through all of statistics.
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 themean()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.
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 (, , ) and the values they take with lower-case letters (, , ). The event " takes the value " is the set of outcomes that sends to : read "the outcomes in for which ". Its probability is written .
The picture above shows the definition at work. Toss two coins, so
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:
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 be a random variable", it's often helpful to read it as "let 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 | if positive, if negative | discrete (an indicator) |
| 20 bags are tested | = number of fakes found | discrete (a count: 0 to 20) |
| a website gets visits for an hour | = number of visits | discrete (a count: 0, 1, 2, ...) |
| a glass fragment is analysed | = refractive index | continuous (a measurement) |
| a patient is followed after surgery | = time until infection, in days | continuous |
| the next word in a sentence | = 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 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 and their probabilities , which must be non-negative and add to 1.
The airline in Chapter 1 cared about , the number of ticket holders who show up. The lab in Example 3.11 cares about , 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 be their total. Find the distribution of , check it by simulation, and find .
The outcomes. There are equally likely outcomes (first die, second die), by case 1 of the counting rules.
The rule. sends each outcome to its total. For example, for the outcomes , , , so the event contains 3 outcomes and
| 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 = (number of outcomes)/36. Check:
totals <- outer(1:6, 1:6, "+") # a 6 x 6 table of all 36 totals
totals
table(totals) / 36 # the distribution of X
[,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
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")
The last part. The events , , are disjoint, so by axiom 3
Check Yourself
Let be the number of heads in 3 tosses of a fair coin.
Could there be no heads at all? Could there be 1.5 heads?
counts heads, so it can be 0, 1, 2 or 3: a discrete random variable.
What is ?
There are equally likely sequences (HHH, HHT, ...). How many have exactly 2 heads?
HHT, HTH and THH: . Chapter 4 generalizes this count into the binomial distribution.
Which one is a measurement that could be any value in an interval, rather than a count or a code?
Time is a measurement: it can be 3.27 hours or 3.2701 hours. The others are counts or an indicator, which are discrete.
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; is the event made of all outcomes sent to .
- 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
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.
Events. A server log records, for each request, whether it came from a known bot () and whether it was rejected (). Write in symbols, and in words, the complement of . Use De Morgan's law to write it another way.
means "from a bot, or rejected, or both". What is the opposite of "at least one of these"?
: requests that were neither from a known bot nor rejected. By De Morgan,
: not from a bot and not rejected. 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 , and from the table, each as a count over 2,201.
Third class: 706; children: 109; third-class children: 79.
. Counting directly: all 706 in third class plus the children in first and second class (there were no children in the crew) gives 736. Passwords. A system requires passwords of exactly 10 characters, each a lowercase letter or digit. (a) How many passwords are possible? (b) At 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 symbols for each position.
(a) Order matters, with replacement:
. (b) 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. 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 ofk.k <- 1:100; p <- choose(1900, k) / choose(2000, k), then find the smallestkwithp < 0.05, for example withmin(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.
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)
pairs. (b) About 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. Titanic conditioning. Using R, find and . 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 forsubset(tt, Class == "3rd"); then useprop.table(..., 1). Also look at the survival of children in first and second class., but among third-class children only ; 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). 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 . Under what assumption is this right? Give a realistic reason it might fail.
When is
? 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 could be much larger than 0.0025, as with the dependent detectors in Example 3.14.
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)
false matches. (b) About , 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." 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 checkany(table(birthdays) >= 3). Wrap it inreplicate(100000, ...)and take themean().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).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.
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 = "contains a prohibited item" and = "flagged". "98% of bags that contain one" restricts to bags in . For (b) use total probability, for (c) Bayes; or imagine 100,000 bags.
(a) ,
, . (b) , about 3.1%. (c) . 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. 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:
. (b) Ordered, with replacement: . (c) Unordered, with replacement (stars and bars, rooms, markers): . (d) Ordered, without replacement: .