AI from scratch · Probability 1 · Stage 1: the math of learning
Probability and Bayes
Every model on this path ends up saying how sure it is: "82% cat", "next word: the, 31%". This lesson builds the rules those numbers obey, from counting dice to Bayes' rule, the one formula for changing your mind when evidence arrives. You'll test two famous puzzles by simulation (your intuition will lose at least once), train a spam filter, and learn to make a computer draw random numbers from any distribution you like.
1. Probability is counting
Roll two dice. There are 36 equally likely outcomes, one per square below (across: the first die, up: the second). When every outcome is equally likely, the probability of an event is just
\[ P(A) = \frac{\text{outcomes in } A}{\text{all outcomes}} \]
Pick two events. Squares only in \(A\) are blue, only in \(B\) red, in both yellow.
Three rules fall straight out of counting:
| rule | formula | why |
|---|---|---|
| Complement | \(P(\text{not } A) = 1 - P(A)\) | every square is either in \(A\) or not |
| Sum rule | \(P(A \text{ or } B) = P(A) + P(B) - P(A \text{ and } B)\) | adding counts the yellow squares twice, so take them off once |
| Independence | \(P(A \text{ and } B) = P(A) \cdot P(B)\) | only when knowing one tells you nothing about the other, like two separate dice |
What is the probability that two dice add up to 7? (Pick "sum is 7" and count.)
What's the probability of at least one six? Use the complement: first find the chance of no six.
2. When intuition fails, simulate
How many people must be in a room before it's more likely than not that two share a birthday? Most people guess around 180. Slide \(n\) and see the exact chance (yellow curve), then let the computer fill 1000 random rooms to check.
The math, step by step
Through the complement: the chance that all \(n\) birthdays are different. The first person can have any day; the second must miss that one (364 of 365 days), the third must miss two (363/365), and so on:
\[ P(\text{no match}) = \frac{365}{365} \cdot \frac{364}{365} \cdot \frac{363}{365} \cdots \frac{365 - n + 1}{365}, \qquad P(\text{match}) = 1 - P(\text{no match}) \]
The surprise is because a match can be between any two people: 23 people make \(23 \cdot 22 / 2 = 253\) pairs, and each pair is another chance.
What's the smallest room where a shared birthday is more likely than not?
Now a game show. A car is behind one of three doors, goats behind the other two. You pick a door. The host, who knows where the car is, opens a different door with a goat, and offers you a switch. Should you? Play a few rounds, then let the computer play a thousand.
Before you play many rounds: does switching help?
- No: two doors are left, so it's 50/50
- Yes: switching wins 2/3 of the time
- It hurts: the host is trying to trick you
3. Conditional probability: shrink the world
"Given that \(B\) happened" means: throw away every outcome where it didn't, and count again inside what's left.
\[ P(A \mid B) = \frac{P(A \text{ and } B)}{P(B)} \]
Read the bar as "given". Here's the same dice square, with the outcomes outside \(B\) dimmed:
The first die shows a 6. What's the probability the sum is at least 10 now? (Before you knew, it was 6/36.)
Two events are independent exactly when conditioning changes nothing: \(P(A \mid B) = P(A)\). Try "a double" given "first die is 6": still 1/6. Every classifier in this course is a conditional probability: \(P(\text{cat} \mid \text{these pixels})\).
Conditioning is shrinking the world to what you now know, and counting again inside it.
4. Bayes' rule: turning a probability around
A test for a disease catches 90% of people who have it (its sensitivity) and wrongly flags 9% of healthy people (its false positive rate). One person in a hundred has the disease. You test positive. How worried should you be? Here are 1000 people: red have the disease, grey don't, and a bright dot means a positive test.
Count the bright dots: most of them are grey. Ten people are sick and 9 of them test positive, but 990 are healthy and 9% of them, about 89, test positive too. A positive test means you're one of about 98 bright dots, and only 9 of those are red: about 9%. That's Bayes' rule:
\[ P(\text{sick} \mid +) = \frac{P(+ \mid \text{sick})\, P(\text{sick})}{P(+)} = \frac{0.9 \times 0.01}{0.9 \times 0.01 + 0.09 \times 0.99} \approx 0.092 \]
Bayes: what you believe after the evidence is what you believed before, times how well each explanation predicted that evidence, rescaled to add up to 1.
Why is Bayes' rule true, and a faster way to use it
- Count the outcomes where both happen in two ways. Shrink to \(B\) first: \(P(A \text{ and } B) = P(A \mid B)\, P(B)\). Or shrink to \(A\) first: \(P(A \text{ and } B) = P(B \mid A)\, P(A)\). Both are just the definition of "given".
- They count the same squares, so they're equal. Divide by \(P(B)\): \(P(A \mid B) = P(B \mid A)\, P(A) / P(B)\). That's all Bayes' rule is.
- For mental math, use odds (sick : healthy). Before the test: 1 : 99. The test is \(0.9 / 0.09 = 10\) times likelier to come back positive for a sick person (the likelihood ratio).
- After a positive test, multiply: 10 : 99, which is \(10/109 \approx 9.2\%\). Evidence multiplies odds by its likelihood ratio, and a second independent positive test would multiply by 10 again: 100 : 99, about 50%.
With 1% sick, 90% sensitivity and 9% false positives, what is \(P(\text{sick} \mid +)\) to three decimals?
Which change raises \(P(\text{sick} \mid +)\) the most, starting from those numbers? Try each on the sliders.
- Cutting false positives from 9% to 1%
- Raising sensitivity from 90% to 99%
5. A spam filter from Bayes' rule
Turn it around for email: \(P(\text{spam} \mid \text{words})\). Bayes says that's proportional to \(P(\text{spam}) \cdot P(\text{words} \mid \text{spam})\), and the "naive" part assumes words appear independently given the class, so the likelihood is a product over words:
\[ P(\text{spam} \mid w_1 \dots w_k) \;\propto\; P(\text{spam}) \prod_{i=1}^{k} P(w_i \mid \text{spam}) \]
Each \(P(w \mid \text{spam})\) is counted from examples: how often the word appears in spam. Two practical tricks from the math warm-up: add 1 to every count (so an unseen word doesn't zero out the whole product), and add logs instead of multiplying (so long emails don't underflow). The independence assumption is plainly false ("free" and "prize" go together) yet the filter works well, which is a theme in ML: a wrong model can still be a useful one.
Where it breaks: borrowed priors and evidence that repeats itself
- The wrong prior. "1 in 100 has it" is true of the whole population, not of someone who came in with symptoms. Use the base rate of the group the person actually belongs to, or the posterior is off by as much as the prior is.
- Turning it around by mistake. \(P(\text{positive} \mid \text{sick}) = 90\%\) is not \(P(\text{sick} \mid \text{positive})\). Swapping them (the "prosecutor's fallacy") is the most common probability error in courts and news reports.
- Evidence that isn't independent. Two positive results from the same faulty sample are one piece of evidence, not two; multiplying both likelihood ratios double-counts it. Naive Bayes does exactly this with words that travel together ("free" and "prize"), which is why its probabilities come out far too extreme (99.9% spam) even when its ranking of emails is good. Chapter 12 shows how to check and fix such overconfident probabilities (calibration).
Change the last messages and run again. Find a short message that's clearly not spam but the filter calls spam. Why does it fail?
6. Distributions: every value's probability at once
A random variable is a number that comes out of a random process: the sum of two dice, the number of heads in 10 flips. Its distribution says how likely each value is. Three you'll meet constantly:
- Bernoulli(\(p\)): one yes/no trial, 1 with probability \(p\), else 0. A click, a fraud, a correct prediction.
- Binomial(\(n, p\)): the number of yeses in \(n\) independent Bernoulli trials. \(P(k) = \binom{n}{k} p^k (1-p)^{n-k}\), where \(\binom{n}{k}\) ("n choose k") counts the orders the \(k\) yeses could come in.
- Uniform: every value in a range equally likely. NumPy's
rng.random()is uniform between 0 and 1.
Below, the bars are the binomial's PMF (probability mass function: the probability of each exact value) and the green steps its CDF (cumulative distribution function: the probability of that value or less, a running sum of the bars).
Four fair coin flips: what's the probability of exactly 2 heads?
For values that can be anything in a range (a time, a height), single exact values have probability zero, so a PDF (density) replaces the bars, and probability is area under it (Calculus 4). The CDF works the same for both: it climbs from 0 to 1, and \(P(a < X \le b) = F(b) - F(a)\).
7. Drawing samples from any distribution
A computer only makes uniform random numbers. To get waiting times for a train that comes on average every 4 minutes (an exponential distribution, CDF \(F(x) = 1 - e^{-x/4}\)), use the CDF backwards: pick a uniform \(u\) between 0 and 1 on the up axis, go across until you hit the CDF, and drop down. That \(x\) is your sample. Steep parts of the CDF catch many \(u\)'s, so values land there often.
The math, step by step
Solve \(u = F(x)\) for \(x\): \(u = 1 - e^{-x/4}\), so \(e^{-x/4} = 1 - u\), so \(x = -4 \ln(1 - u)\). Write \(F^{-1}\) for that undoing (the CDF read backwards, as a matrix inverse undoes a move in linear algebra 1). If \(U\) is uniform, then \(P(F^{-1}(U) \le x) = P(U \le F(x)) = F(x)\): the samples have exactly the CDF we wanted.
For a list of options it's the same idea with a staircase CDF: walk the running total of the probabilities until it passes \(u\). That's exactly how chapter 5 and the tiny transformer pick the next word from softmax's probabilities.
Which waiting time does \(u = 0.5\) map to? (Half of all waits are shorter than this: it's the median.)
A distribution gives every value's probability; its CDF, read backwards, turns uniform random numbers into samples of it.
8. What to carry forward
- With equally likely outcomes, probability is counting. Complement: \(1 - P(A)\). Sum rule: subtract the overlap. Independent events multiply.
- When a puzzle feels slippery (birthdays, Monty Hall), simulate it: a few lines of code beat intuition.
- \(P(A \mid B)\) counts inside \(B\) only. Independence means conditioning changes nothing.
- Bayes: posterior ∝ likelihood × prior. Rare things stay unlikely after weak evidence; false positives from a big crowd dominate.
- Naive Bayes: count words per class, add one, add logs.
- PMF for counts, PDF for continuous values (area is probability), CDF for both. Inverting the CDF turns uniform random numbers into any distribution.
All lessons: AI from scratch.
Last updated