You tested positive. Now what?
A screening test for a condition is described as "95% accurate": it detects of people who have the condition, and it gives a correct negative result for of people who do not. About person in who take the test has the condition. You take the test, and the result is positive. How likely is it that you have the condition?
Most people answer "about ". The true answer is about .
That is not a trick, and it is not a flaw in the test. It is what happens when we confuse two different questions — "how likely is a positive result, if you have the condition?" and "how likely is the condition, if your result is positive?" — and forget how rare the condition was to begin with. Doctors, juries, journalists and scientists have all made this mistake, sometimes with serious consequences. This lesson gives you the tools to get it right: conditional probability, independence and Bayes' theorem.
New information shrinks the sample space
Roll two fair dice. The probability that the first die shows a is . Now suppose a friend peeks and tells you: "the total is ". Only three of the equally likely outcomes are left:
In one of these three the first die shows a . So, given that the total is , the probability that the first die is a has risen from to .
Conditioning on an event means throwing away every outcome outside and rescaling, so that the outcomes left over carry all the probability. Here is a second example, from a survey of secondary-school students in Hanoi about how they travel to school and whether they arrived late at least once last month:
| late | not late | total | |
|---|---|---|---|
| cycle | 30 | 170 | 200 |
| bus | 50 | 150 | 200 |
| total | 80 | 320 | 400 |
Pick a student at random. . Among the cyclists only, ; among the bus riders, . And among the late students, — a quite different number from , because it divides by a different total.
Definitions
We work, as in the lesson on probability, with a finite sample space of outcomes. Each outcome has a probability , these add up to , and the probability of an event is . Equally likely outcomes are the special case , where .
Definition— conditional probability
For events and with , the conditional probability of given is
It is not defined when .
Definition— independent events
Events and are independent if .
Definition— mutually exclusive events
Events and are mutually exclusive if they cannot both happen: .
Definition— partition
Events partition the sample space if they are pairwise mutually exclusive and together cover it: every outcome lies in exactly one . For example, and its complement form a partition.
The definition of independence is symmetric in and and makes sense even when a probability is ; Theorem 5 below explains why it captures the idea "knowing tells us nothing about ".
Worked examples
Example— Two cards without replacement
Draw two cards from a shuffled pack of , without putting the first back. What is the probability that both are aces? The first is an ace with probability . Given that it was, cards remain, of which are aces, so the second is an ace with conditional probability . Multiplying along the branches of the tree,
The draws are not independent: .
Example— Independent events from dice
Roll two dice. Let = "the first die is even" and = "the total is ". Then , , and , so . They are independent: whatever the first die shows, exactly one face of the second die makes the total .
By contrast, = "the first die is " and = "the total is at least " are not independent: , but .
Example— Mutually exclusive is not independent
With one die, "roll a " and "roll a " are mutually exclusive. Are they independent? , but . No — learning that you rolled a tells you for certain that you did not roll a . Mutually exclusive events with positive probabilities are as far from independent as can be.
Example— Pairwise is not enough
Toss two fair coins. Let = "the first is heads", = "the second is heads", = "the two coins show the same face". Each has probability , and each pair is independent: for instance = "both heads" has probability . But and together force : . For three events to be (mutually) independent we require the product rule for every pair and for all three together.
The rules, with proofs
Throughout, is a finite sample space with probabilities as above.
Theorem— Theorem 1 (basic rules)
For all events and : if then ; in general
Proof
If and are disjoint, the sum of over splits into the sum over plus the sum over . In general, adds twice for each and once for every other outcome of ; subtract . Finally and are disjoint with union , so .
∎
Theorem— Theorem 2 (conditioning gives a new probability)
Fix an event with . Then is again a probability: , , and when .
Proof
Since , we have ; divide by . Next, . If and are disjoint, so are and , and their union is ; apply Theorem 1 and divide by .
∎
In fact gives each outcome the new probability and each outcome outside probability : the "throw away and rescale" of the intuition section. So every rule of probability holds for conditional probabilities too — for instance .
Theorem— Theorem 3 (multiplication rule)
If then . More generally, if ,
Proof
The first statement is the definition of multiplied by . For the second, write out the right-hand side: ; everything cancels except . (Both denominators are positive, since .)
∎
This is why we multiply along the branches of a tree diagram: each branch carries a conditional probability, given everything on the path before it.
Theorem— Theorem 4 (law of total probability)
If partition and each , then for every event ,
In particular, if : .
Proof
Every outcome of lies in exactly one , so is the union of the pairwise disjoint pieces , and by Theorem 1 (applied repeatedly). By the multiplication rule, .
∎
On a tree diagram: to find , add up the probabilities of all the paths that end in .
Theorem— Theorem 5 (Bayes' theorem)
If and , then
Combined with Theorem 4, when :
Proof
By the multiplication rule, used twice, . Divide by . For the second form, expand the denominator by the law of total probability with the partition .
∎
Bayes' theorem reverses a conditional probability. It needs one extra ingredient: the base rate (or prior probability) .
Example— The screening test, solved
Let = "has the condition" and = "tests positive". We know , and . By Bayes' theorem,
Natural frequencies make this transparent. Imagine people. About have the condition, and of them test positive. Of the who do not, — that is — also test positive. So of the positive results, only come from people with the condition: . The false positives outnumber the true ones because healthy people are so much more numerous.
Independence
Theorem— Theorem 6 (independence as irrelevance)
If , then and are independent if and only if .
Proof
means , which (multiplying by ) is the same as .
∎
Theorem— Theorem 7 (complements)
If and are independent, so are and (and hence also and , and and ).
Proof
is the disjoint union of and , so
using independence in the second step and the complement rule in the last. Applying this again with the roles of the events exchanged gives the other two statements.
∎
Theorem— Theorem 8 (exclusive events are dependent)
If and are mutually exclusive and , , then and are not independent.
Proof
, while .
∎
The rules, checked by Lean
We formalise a finite probability space exactly as in the definitions: a finite type of outcomes and a rational probability for each, adding up to . Using rational numbers keeps every calculation exact.
/-- A **finite probability space** on a finite type of outcomes `Ω`: a probability `p ω ≥ 0`
for each outcome, adding up to `1`. -/
structure FinProb (Ω : Type*) [Fintype Ω] where
/-- the probability of each single outcome -/
p : Ω → ℚ
nonneg : ∀ ω, 0 ≤ p ω
sum_eq_one : ∑ ω, p ω = 1/-- The **probability of an event** `A` (a set of outcomes): the sum of the probabilities of
its outcomes. -/
def FinProb.P {Ω : Type*} [Fintype Ω] (μ : FinProb Ω) (A : Finset Ω) : ℚ :=
∑ ω ∈ A, μ.p ω/-- **Conditional probability:** `P(A | B) = P(A ∩ B) / P(B)`, the probability of `A` when we
know that `B` happened. It is meant to be used only when `P(B) > 0`; Lean's convention `x / 0 = 0`
gives it the meaningless value `0` otherwise, and every theorem below that needs `P(B) ≠ 0`
assumes it. -/
def FinProb.cond {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω) : ℚ :=
μ.P (A ∩ B) / μ.P B/-- Events `A` and `B` are **independent** when `P(A ∩ B) = P(A) P(B)`. -/
def FinProb.Indep {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω) :
Prop :=
μ.P (A ∩ B) = μ.P A * μ.P BThe basic rules (Theorem 1) and the multiplication rule:
/-- **Complement rule:** `P(Aᶜ) = 1 − P(A)`. The outcomes of `A` and of `Aᶜ` together are all
the outcomes, whose probabilities add up to `1`. -/
theorem prob_compl {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A : Finset Ω) :
μ.P Aᶜ = 1 - μ.P A := by
have h := sum_add_sum_compl A μ.p
rw [μ.sum_eq_one] at h
unfold P
linarith/-- **Addition rule:** `P(A ∪ B) = P(A) + P(B) − P(A ∩ B)`: adding `P(A)` and `P(B)` counts the
outcomes of `A ∩ B` twice. -/
theorem prob_union {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω) :
μ.P (A ∪ B) = μ.P A + μ.P B - μ.P (A ∩ B) := by
have h := sum_union_inter (s₁ := A) (s₂ := B) (f := μ.p)
unfold P
linarith/-- **Multiplication rule:** `P(A ∩ B) = P(A | B) · P(B)` whenever `P(B) ≠ 0` — "multiply along
the branches of the tree". It is the definition of `P(A | B)`, rearranged. -/
theorem mul_rule {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω)
(hB : μ.P B ≠ 0) : μ.P (A ∩ B) = μ.cond A B * μ.P B := by
rw [cond, div_mul_cancel₀ _ hB]Bayes' theorem and the law of total probability (Theorems 4 and 5), and the screening test as a theorem about every probability space with those three numbers:
/-- **Bayes' theorem:** `P(A | B) = P(B | A) P(A) / P(B)` when `P(A) ≠ 0`. Both `P(A | B) P(B)`
and `P(B | A) P(A)` equal `P(A ∩ B)`: the same probability, computed along two different
trees. -/
theorem bayes {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω)
(hA : μ.P A ≠ 0) : μ.cond A B = μ.cond B A * μ.P A / μ.P B := by
rw [← mul_rule μ B A hA, inter_comm, cond]/-- **Law of total probability.** If the events `B i` (for `i ∈ s`) are pairwise disjoint,
cover every outcome, and each has positive probability, then `P(A) = Σᵢ P(A | Bᵢ) P(Bᵢ)`.
Proof: `A` is the disjoint union of the pieces `A ∩ Bᵢ`, so `P(A) = Σᵢ P(A ∩ Bᵢ)`, and each
piece is `P(A | Bᵢ) P(Bᵢ)` by the multiplication rule. -/
theorem total_probability {Ω ι : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
(A : Finset Ω) (s : Finset ι) (B : ι → Finset Ω) (hdisj : (s : Set ι).PairwiseDisjoint B)
(hcover : ∀ ω, ∃ i ∈ s, ω ∈ B i) (hpos : ∀ i ∈ s, μ.P (B i) ≠ 0) :
μ.P A = ∑ i ∈ s, μ.cond A (B i) * μ.P (B i) := by
-- `A` is the disjoint union of the pieces `A ∩ B i`
have hA : A = s.biUnion fun i => A ∩ B i := by
ext ω
simp only [mem_biUnion, mem_inter]
constructor
· intro hω
obtain ⟨i, hi, hωi⟩ := hcover ω
exact ⟨i, hi, hω, hωi⟩
· rintro ⟨i, -, hω, -⟩
exact hω
have hdisj' : (s : Set ι).PairwiseDisjoint fun i => A ∩ B i := by
intro i hi j hj hij
exact Disjoint.mono inter_subset_right inter_subset_right (hdisj hi hj hij)
calc μ.P A = ∑ ω ∈ s.biUnion (fun i => A ∩ B i), μ.p ω := by rw [← hA]; rfl
_ = ∑ i ∈ s, μ.P (A ∩ B i) := sum_biUnion hdisj'
_ = ∑ i ∈ s, μ.cond A (B i) * μ.P (B i) :=
sum_congr rfl fun i hi => mul_rule μ A (B i) (hpos i hi)/-- **Total probability with two cases:** `P(A) = P(A | B) P(B) + P(A | Bᶜ) P(Bᶜ)` when
`0 < P(B) < 1`. Either `B` happens or it does not. -/
theorem total_probability_two {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
(A B : Finset Ω) (hB : μ.P B ≠ 0) (hBc : μ.P Bᶜ ≠ 0) :
μ.P A = μ.cond A B * μ.P B + μ.cond A Bᶜ * μ.P Bᶜ := by
rw [← mul_rule μ A B hB, ← mul_rule μ A Bᶜ hBc]
have h := sum_filter_add_sum_filter_not A (· ∈ B) μ.p
have e1 : A.filter (· ∈ B) = A ∩ B := by ext; simp [mem_inter]
have e2 : A.filter (· ∉ B) = A ∩ Bᶜ := by ext; simp [mem_inter]
rw [e1, e2] at h
unfold P
linarith/-- **Bayes' theorem for a test result.** With `D` = "has the condition" and `T` = "tests
positive",
`P(D | T) = P(T | D) P(D) / (P(T | D) P(D) + P(T | Dᶜ) P(Dᶜ))`:
Bayes' theorem with the denominator `P(T)` expanded by total probability. -/
theorem bayes_total {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (D T : Finset Ω)
(hD : μ.P D ≠ 0) (hDc : μ.P Dᶜ ≠ 0) :
μ.cond D T = μ.cond T D * μ.P D / (μ.cond T D * μ.P D + μ.cond T Dᶜ * μ.P Dᶜ) := by
rw [bayes μ D T hD, ← total_probability_two μ T D hD hDc]/-- **A positive test is not a diagnosis.** Suppose `1%` of people have a condition, the test
detects it `95%` of the time (`P(T | D) = 0.95`), and it wrongly flags `5%` of healthy people
(`P(T | Dᶜ) = 0.05`). Then a positive result means only `P(D | T) = 19/118 ≈ 16%`. The base rate
`P(D) = 0.01` matters as much as the accuracy of the test. -/
theorem base_rate_example {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
(D T : Finset Ω) (hD : μ.P D = 1 / 100) (hTD : μ.cond T D = 95 / 100)
(hTDc : μ.cond T Dᶜ = 5 / 100) : μ.cond D T = 19 / 118 := by
have hDc : μ.P Dᶜ = 99 / 100 := by rw [prob_compl, hD]; norm_num
rw [bayes_total μ D T (by rw [hD]; norm_num) (by rw [hDc]; norm_num), hD, hDc, hTD, hTDc]
norm_numIndependence (Theorems 6, 7 and 8):
/-- **Independence means "knowing `B` tells us nothing about `A`":** when `P(B) ≠ 0`, `A` and
`B` are independent exactly when `P(A | B) = P(A)`. -/
theorem indep_iff_cond {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
(A B : Finset Ω) (hB : μ.P B ≠ 0) : μ.Indep A B ↔ μ.cond A B = μ.P A := by
rw [Indep, cond, div_eq_iff hB]/-- **Mutually exclusive is the opposite of independent.** If `A` and `B` cannot both happen
and each has positive probability, they are *not* independent: `P(A ∩ B) = 0`, but
`P(A) P(B) > 0`. Learning that `B` happened tells us for certain that `A` did not. -/
theorem exclusive_not_indep {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω)
(A B : Finset Ω) (hdisj : A ∩ B = ∅) (hA : μ.P A ≠ 0) (hB : μ.P B ≠ 0) :
¬ μ.Indep A B := by
intro h
rw [Indep, hdisj] at h
have h0 : μ.P ∅ = 0 := sum_empty
rw [h0] at h
exact mul_ne_zero hA hB h.symm/-- **Independence survives complements:** if `A` and `B` are independent, so are `A` and
`Bᶜ`. Proof: `P(A ∩ Bᶜ) = P(A) − P(A ∩ B) = P(A) − P(A) P(B) = P(A)(1 − P(B)) = P(A) P(Bᶜ)`. -/
theorem indep_compl {Ω : Type*} [Fintype Ω] [DecidableEq Ω] (μ : FinProb Ω) (A B : Finset Ω)
(h : μ.Indep A B) : μ.Indep A Bᶜ := by
have hsplit := sum_filter_add_sum_filter_not A (· ∈ B) μ.p
have e1 : A.filter (· ∈ B) = A ∩ B := by ext; simp [mem_inter]
have e2 : A.filter (· ∉ B) = A ∩ Bᶜ := by ext; simp [mem_inter]
rw [e1, e2] at hsplit
have hc := prob_compl μ B
unfold Indep at h ⊢
rw [hc]
unfold P at *
rw [mul_sub, mul_one]
linarithFor equally likely outcomes, probability is counting, and independence becomes a statement about counts that Lean can check by listing all outcomes of two dice:
/-- **Equally likely outcomes:** each of the `|Ω|` outcomes has probability `1/|Ω|`. -/
def uniform (Ω : Type*) [Fintype Ω] [Nonempty Ω] : FinProb Ω where
p _ := 1 / Fintype.card Ω
nonneg _ := by positivity
sum_eq_one := by
rw [sum_const, card_univ, nsmul_eq_mul]
have : (Fintype.card Ω : ℚ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero
field_simp/-- With equally likely outcomes, `P(A) = |A| / |Ω|`: probability is counting, divided. -/
theorem uniform_P {Ω : Type*} [Fintype Ω] [Nonempty Ω] (A : Finset Ω) :
(uniform Ω).P A = #A / Fintype.card Ω := by
simp only [P, uniform, sum_const, nsmul_eq_mul]
ring/-- With equally likely outcomes, independence is a statement about counting:
`A` and `B` are independent exactly when `|A ∩ B| · |Ω| = |A| · |B|`. -/
theorem uniform_indep_iff {Ω : Type*} [Fintype Ω] [DecidableEq Ω] [Nonempty Ω]
(A B : Finset Ω) : (uniform Ω).Indep A B ↔ #(A ∩ B) * Fintype.card Ω = #A * #B := by
have hN : (Fintype.card Ω : ℚ) ≠ 0 := by exact_mod_cast Fintype.card_ne_zero
rw [Indep, uniform_P, uniform_P, uniform_P, div_mul_div_comm,
div_eq_div_iff hN (mul_ne_zero hN hN)]
constructor
· intro h
have h' : ((#(A ∩ B) : ℚ) * Fintype.card Ω) * Fintype.card Ω =
((#A : ℚ) * #B) * Fintype.card Ω := by
rw [mul_assoc]
exact h
exact_mod_cast mul_right_cancel₀ hN h'
· intro h
have h' : ((#(A ∩ B) : ℚ) * Fintype.card Ω) = (#A : ℚ) * #B := by exact_mod_cast h
rw [← mul_assoc, h']/-- **Two dice, independent events.** Roll two fair dice (outcome `(i, j)` means faces `i + 1`
and `j + 1`). "The first die is even" and "the total is 7" are independent:
`P(both) = 3/36 = 1/12 = (18/36)(6/36)`. Lean counts the outcomes: `3 · 36 = 18 · 6`. -/
theorem dice_even_seven :
(uniform (Fin 6 × Fin 6)).Indep
{ω | (ω.1.val + 1) % 2 = 0} {ω | ω.1.val + ω.2.val + 2 = 7} :=
(uniform_indep_iff _ _).2 (by decide)/-- **Two dice, dependent events.** "The first die shows 6" and "the total is at least 10" are
*not* independent: `P(both) = 3/36 = 1/12`, but `P(first is 6) P(total ≥ 10) = (1/6)(1/6) = 1/36`.
Knowing that the first die is a 6 makes a high total three times as likely. Lean counts:
`3 · 36 ≠ 6 · 6`. -/
theorem dice_six_high :
¬ (uniform (Fin 6 × Fin 6)).Indep
{ω | ω.1.val + 1 = 6} {ω | 10 ≤ ω.1.val + ω.2.val + 2} := by
rw [uniform_indep_iff]
decideAt university, probability is built on measure theory, which also handles infinitely many outcomes (a point chosen at random on a line, a random walk that goes on forever). Mathlib's probability library is written in that language; here are Bayes' theorem and total probability as it states them. The notation μ[t | s] is , and probabilities take values in :
/-- **Bayes' theorem** for any finite measure (in particular any probability measure), with
`μ[t | s]` the conditional probability of `t` given `s`:
`P(t | s) = P(s)⁻¹ · P(s | t) · P(t)`. Probabilities here take values in `[0, ∞]`, so no
positivity hypothesis is needed: `0⁻¹ = ∞` and the conventions are arranged to make the identity
true. This applies Mathlib's `ProbabilityTheory.cond_eq_inv_mul_cond_mul`. -/
theorem bayes_library {Ω : Type*} [MeasurableSpace Ω] (μ : Measure Ω) [IsFiniteMeasure μ]
{s t : Set Ω} (hs : MeasurableSet s) (ht : MeasurableSet t) :
μ[t | s] = (μ s)⁻¹ * μ[s | t] * μ t :=
cond_eq_inv_mul_cond_mul hs ht μ/-- **Total probability with two cases**, for any finite measure:
`P(t | s) P(s) + P(t | sᶜ) P(sᶜ) = P(t)`. This applies Mathlib's
`ProbabilityTheory.cond_add_cond_compl_eq`. -/
theorem total_probability_library {Ω : Type*} [MeasurableSpace Ω] (μ : Measure Ω)
[IsFiniteMeasure μ] {s t : Set Ω} (hs : MeasurableSet s) :
μ[t | s] * μ s + μ[t | sᶜ] * μ sᶜ = μ t :=
cond_add_cond_compl_eq hs μOur finite spaces are a special case of Mathlib's measures; we have not formally proved that the two notions of conditional probability agree on them, though they do.
Tables and simulations
"""Bayes' theorem with natural frequencies: tests, base rates and courtrooms.
A diagnostic test is imagined on 100,000 people and every count is exact.
The two-way table shows why P(condition | positive) and P(positive |
condition) are different numbers, and the same test is re-run with base
rates from 0.1% to 50% to show how strongly the answer depends on them. A
second independent positive test is handled by using the first posterior as
the new prior. Finally the prosecutor's fallacy: a DNA profile shared by one
person in a million, in a city of two million.
"""
from fractions import Fraction
def two_way_table(population, prevalence, sensitivity, specificity):
"""Counts (true pos, false neg, false pos, true neg) as exact Fractions."""
sick = population * prevalence
well = population - sick
return (sick * sensitivity, sick * (1 - sensitivity),
well * (1 - specificity), well * specificity)
def posterior(prior, p_pos_given_d, p_pos_given_not_d):
"""P(D | positive) by Bayes' theorem with total probability below."""
top = p_pos_given_d * prior
return top / (top + p_pos_given_not_d * (1 - prior))
def fmt(q):
"""An exact count as a whole number with thousands separators."""
assert q.denominator == 1
return f"{q.numerator:,}"
def main():
sens, spec = Fraction(95, 100), Fraction(95, 100)
tp, fn, fp, tn = two_way_table(Fraction(100000), Fraction(1, 100),
sens, spec)
print("Test: sensitivity 95%, specificity 95%; base rate 1%.")
print("Imagine 100,000 people:")
print(" test + test - total")
print(f" condition {fmt(tp):>9} {fmt(fn):>9} {fmt(tp + fn):>9}")
print(f" no condition {fmt(fp):>9} {fmt(tn):>9} {fmt(fp + tn):>9}")
print(f" total {fmt(tp + fp):>9} {fmt(fn + tn):>9} "
f"{fmt(tp + fn + fp + tn):>9}")
ppv = tp / (tp + fp)
print(f"P(condition | +) = {fmt(tp)}/{fmt(tp + fp)} = {ppv} "
f"= {float(ppv):.3f}")
print(f"P(+ | condition) = {fmt(tp)}/{fmt(tp + fn)} = "
f"{float(tp / (tp + fn)):.3f} (a different question!)")
print()
print("Same test, different base rates:")
print(" base rate P(condition | +) P(no condition | -)")
for rate in ("1/1000", "1/100", "1/10", "1/2"):
prior = Fraction(rate)
ppv_r = posterior(prior, sens, 1 - spec)
npv_r = posterior(1 - prior, spec, 1 - sens)
print(f" {float(prior):9.1%} {float(ppv_r):16.4f}"
f" {float(npv_r):19.5f}")
second = posterior(ppv, sens, 1 - spec)
print(f"After a second, independent positive test: {float(ppv):.3f} -> "
f"{float(second):.3f}")
print()
match = posterior(Fraction(1, 2_000_000), Fraction(1), Fraction(1, 10**6))
print("DNA profile shared by 1 person in 1,000,000; city of 2,000,000;")
print("no other evidence. P(match | innocent) = 0.000001, but")
print(f"P(innocent | match) = {float(1 - match):.4f}")
print()
print("Epistemic status: exact arithmetic in a model whose inputs (base")
print("rate, sensitivity, specificity, independence of the two tests)")
print("are assumptions. Change them and the answers change; the")
print("structure of the calculation (Bayes' theorem) does not.")
if __name__ == "__main__":
main()Look at the base-rate table. The test never changes, yet a positive result means anything from a to a chance of having the condition, depending on how common the condition is among the people tested. That is why screening programmes usually follow a positive result with a second, different test — and why a test used on people who already have symptoms (a higher base rate) is more informative than the same test used on everyone.
The last lines are the prosecutor's fallacy. "Only one person in a million has this DNA profile" is . But in a city of two million there are about two innocent people who match as well as the guilty one, so, if the match is the only evidence and the suspect was found by searching, is about . Real cases have other evidence, which changes the numbers — but the two conditional probabilities must never be confused.
"""Conditional probability as a relative frequency: simulated dice, doors, cards.
A conditional probability P(A | B) can be estimated by looking only at the
trials in which B happened and asking how often A happened too. A seeded
pseudo-random generator rolls two dice 60,000 times: "first die even" is
independent of "total 7", but "first die 6" is not independent of "total at
least 10", and two mutually exclusive events are as dependent as can be. The
Monty Hall game and drawing two cards without replacement show conditioning
changing a probability. Every estimate is printed next to its exact value.
"""
import random
from fractions import Fraction
def roll_pairs(rng, n):
"""n rolls of two fair dice, as (first, second) faces 1..6."""
return [(rng.randint(1, 6), rng.randint(1, 6)) for _ in range(n)]
def estimate(trials, event, given=None):
"""Relative frequency of `event` among the trials where `given` holds."""
pool = [t for t in trials if given is None or given(t)]
return sum(1 for t in pool if event(t)) / len(pool)
def exact(event, given=None):
"""The exact probability over the 36 equally likely outcomes."""
pool = [(a, b) for a in range(1, 7) for b in range(1, 7)
if given is None or given((a, b))]
return Fraction(sum(1 for t in pool if event(t)), len(pool))
def monty_hall(rng, games):
"""Win rates (stick, switch) when the host always opens a goat door."""
stick = switch = 0
for _ in range(games):
car, pick = rng.randrange(3), rng.randrange(3)
opened = rng.choice([d for d in range(3) if d not in (car, pick)])
other = next(d for d in range(3) if d not in (pick, opened))
stick += pick == car
switch += other == car
return stick / games, switch / games
def second_ace_given_first(rng, draws):
"""Estimate P(second card is an ace | first is an ace), no replacement."""
deck = ["A"] * 4 + ["x"] * 48
both = first = 0
for _ in range(draws):
c1, c2 = rng.sample(deck, 2)
first += c1 == "A"
both += c1 == "A" and c2 == "A"
return both / first
def main():
rng = random.Random(1654)
rolls = roll_pairs(rng, 60000)
pairs = [
("first even | total 7", lambda t: t[0] % 2 == 0,
lambda t: t[0] + t[1] == 7),
("first is 6 | total >= 10", lambda t: t[0] == 6,
lambda t: t[0] + t[1] >= 10),
("first is 1 | first is 6", lambda t: t[0] == 1, lambda t: t[0] == 6),
]
print("60,000 rolls of two dice P(A) P(A | B)")
print(" sim exact sim exact")
for name, a, b in pairs:
line = (f" {name:26} {estimate(rolls, a):.3f} {str(exact(a)):5} "
f"{estimate(rolls, a, b):.3f} {exact(a, b)}")
print(line)
print("Independent: P(A | B) = P(A). Not independent: knowing B")
print("changes the chance of A (to 1/2 in row 2, to 0 in row 3).")
print()
stick, switch = monty_hall(rng, 30000)
print(f"Monty Hall, 30,000 games: stick wins {stick:.3f} (exact 1/3), "
f"switch {switch:.3f} (2/3)")
est = second_ace_given_first(rng, 60000)
print(f"Two cards, 60,000 draws: P(2nd ace | 1st ace) = {est:.3f}")
print(f" (exact 3/51 = {3 / 51:.3f}, while P(ace) = 4/52 = "
f"{4 / 52:.3f})")
print()
print("Epistemic status: statistical evidence from one seeded run of a")
print("pseudo-random generator; another seed gives slightly different")
print("estimates. The exact values come from counting equally likely")
print("outcomes, and the lesson proves the rules that connect them.")
if __name__ == "__main__":
main()Explore: the Monty Hall problem
Stick or switch?
Three doors, one car. After the host opens a door with a goat, should you stick or switch?
- switch: share of wins so far
- stick: share of wins so far
- exact 1/3 and 2/3
Switching wins
Simulated67.5%
Exact2/3 ≈ 66.7%
Sticking wins
Simulated32.5%
Exact1/3 ≈ 33.3%
Simulation of 1,000 games: switching won 67.5%, sticking won 32.5%. The exact values are 2/3 and 1/3.
Play it yourself
Pick a door.
Evidence, not proofThis is a simulation of 1,000 games (run 1) using a seeded random number generator. It is evidence, not proof: the exact values come from mathematics, and a new run gives slightly different numbers.
Your first pick is right with probability 1/3. The host always opens a goat door, so switching wins exactly when your first pick was wrong: probability 2/3. In every game exactly one of the two strategies wins.
In a game show there are three doors: a car behind one, goats behind the other two. You pick a door. The host, who knows where the car is, always opens a different door with a goat behind it (choosing at random if there are two), and offers you the chance to switch. Should you? Play a few rounds yourself, then run thousands.
Bayes' theorem explains the answer. Say you picked door and the host opened door . Each door hides the car with prior probability . If the car is behind door , the host opens door with probability ; if it is behind door , he must open door (probability ); if it is behind door , he never opens it. By total probability, , and by Bayes
Switching wins with probability . The host's choice carries information, because it depends on where the car is.
Exercises
1. Conditional probability and independence
Warm-upHumanTwo fair dice are rolled and you are told that the total is . What is the probability that the first die shows a ?
2. Conditional probability and independence
Warm-upHumanIn the lesson's survey of students in Hanoi, cycle to school, were late at least once, and cyclists were late. A student is chosen at random from those who were late. What is the probability that they cycle?
3. Conditional probability and independence
CoreHumanA condition affects of a population of people. A test detects it in of people who have it, and gives a false positive for of people who do not. If everyone is tested, how many positive results are expected?
4. Conditional probability and independence
CoreHumanWith the numbers of the previous exercise (base rate , detection, false positives), a randomly chosen person tests positive. About how likely is it that they have the condition?
5. Conditional probability and independence
CoreHumanTwo fair dice are rolled. Which pairs of events are independent? (Choose all that apply.)
6. Conditional probability and independence
CoreHumanEvents and are mutually exclusive, with and . Which statement is true?
7. Conditional probability and independence
CoreHumanTwo cards are drawn from a shuffled pack of without replacement. The probability that both are aces is . What is ?
8. Conditional probability and independence
StretchHumanHere is the proof that if and are independent then so are and :
.
Which step uses the hypothesis that and are independent?
9. Conditional probability and independence
StretchFormalIn the lesson's Lean model, μ.cond A B is defined as μ.P (A ∩ B) / μ.P B, and Lean's convention makes x / 0 = 0. The lesson proves
theorem bayes (μ : FinProb Ω) (A B : Finset Ω) (hA : μ.P A ≠ 0) : μ.cond A B = μ.cond B A * μ.P A / μ.P B.
What is the role of the hypothesis hA?
10. Conditional probability and independence
StretchComputationalWrite posterior(prior, sensitivity, false_positive_rate) returning by Bayes' theorem, and after_positives(prior, sensitivity, false_positive_rate, k) returning the probability of after positive results from independent tests (use each posterior as the next prior). The tests pass Fractions, so keep the arithmetic exact.
Common misconceptions
Misconception
Confusing with . The probability that a person who has the condition tests positive () is not the probability that a person who tests positive has the condition (about ). In court this is the prosecutor's fallacy: "the chance of this evidence if the defendant were innocent is tiny" is not "the chance that the defendant is innocent is tiny". Bayes' theorem converts one into the other, and it needs the base rate.
Misconception
Ignoring base rates. A very accurate test for a very rare condition produces mostly false positives, simply because there are so many more people without the condition. Always ask: "out of how many people, and how many of them had it to begin with?"
Misconception
"Independent means mutually exclusive." Almost the opposite: mutually exclusive events with positive probabilities are never independent (Theorem 8). "First coin heads" and "second coin heads" are independent and can perfectly well happen together.
Misconception
"Independence can always be read off the story." Sometimes it can (separate coins, separate dice), but often it must be checked with numbers. "First die even" and "total even" are independent, which surprises many people; and two events can be dependent through a common cause, like two family members' illnesses. Assuming independence when it fails can turn a large probability into a tiny one — as happened in the case of Sally Clark (see the history section).
Other ways of seeing
Geometry— Probability as area
Picture as a unit square and events as regions, with probability equal to area. Conditioning on means zooming in on the region and rescaling it to have area ; is the fraction of covered by . Two events are independent when they look like a vertical strip and a horizontal strip: the strip and the strip meet in a rectangle of area , exactly the product of their areas. Choosing a random point in the square, "" and "" are independent — the two coordinates do not influence each other.
Algebra— Bayes in odds form
Write probabilities as odds: . Dividing Bayes' theorem for by Bayes' theorem for cancels and leaves
For the screening test the likelihood ratio is , the prior odds are , so the posterior odds are — the we found. Evidence acts by multiplication, and independent pieces of evidence multiply their likelihood ratios; taking logarithms turns this into addition, which is how Alan Turing and I. J. Good scored evidence at Bletchley Park.
Computation— Learning from data
Bayes' theorem is the engine of a large part of modern statistics and machine learning. A spam filter estimates from the frequencies of words in spam and in ordinary mail; a "naive Bayes" filter simply assumes the words are independent given the class, and works surprisingly well although the assumption is false. In statistical inference, Bayesian methods treat an unknown quantity as uncertain and update a prior distribution into a posterior distribution as data arrive — the screening-test calculation, repeated with many hypotheses at once.
Set-theoretic connection
Every rule in this lesson is a statement about subsets of . Conditioning on replaces the universe by and each event by . A partition is a way of cutting into disjoint pieces — the same notion as the classes of an equivalence relation — and the law of total probability adds the probability of up piece by piece. Mutually exclusive means disjoint, a set-theoretic property; independence is a numerical one, which is why the two are so different.
History and global context
- Bayes and Laplace. Thomas Bayes, an English minister, worked out how to reason from observed outcomes back to unknown chances; his essay was published in 1763, after his death, by his friend Richard Price. Pierre-Simon Laplace discovered the theorem independently (1774) and developed it into a general method, applying it, for example, to birth records from Paris and London.
- Foundations. Andrey Kolmogorov's book of 1933, which set out the axioms of probability used today, defines conditional probability by the ratio used in this lesson.
- Codebreaking. During the Second World War, Alan Turing and I. J. Good used Bayes factors — likelihood ratios, added on a logarithmic scale — to weigh evidence when breaking German naval codes at Bletchley Park.
- Base-rate neglect. In a 1978 study by Ward Casscells, Arno Schoenberger and Thomas Graboys, staff and students at Harvard Medical School were asked about a test with a false-positive rate for a disease affecting person in . The most common answer for the chance that a person with a positive result has the disease was ; fewer than one in five gave the correct answer, about . Gerd Gigerenzer and Ulrich Hoffrage showed in 1995 that people reason far more accurately with natural frequencies than with percentages.
- A miscarriage of justice. In 1999 Sally Clark, a solicitor in England, was convicted of murdering her two baby sons. An expert witness told the court that the chance of two sudden infant deaths in such a family was about in million, obtained by squaring the chance of one — assuming the two deaths independent, although shared genetic and environmental factors make that assumption doubtful — and the figure was widely misread as the chance of her innocence. The Royal Statistical Society publicly criticised this use of statistics in 2001, and her convictions were overturned in 2003.
- Monty Hall. The puzzle was posed by the statistician Steve Selvin in 1975 and became famous in 1990, when Marilyn vos Savant's correct answer — switch — drew thousands of letters insisting she was wrong.
Further reading
- Joseph K. Blitzstein and Jessica Hwang, Introduction to Probability (2014), chapter 2 on conditional probability.
- Charles M. Grinstead and J. Laurie Snell, Introduction to Probability (1997).
- Gerd Gigerenzer, Calculated Risks: How to Know When Numbers Deceive You (2002).
- David Spiegelhalter, The Art of Statistics: Learning from Data (2019).
- William Feller, An Introduction to Probability Theory and Its Applications, volume 1 (1950), chapter 5 — a classic, for later.