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:

ruleformulawhy
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.)

Six squares, (1,6), (2,5), (3,4), (4,3), (5,2), (6,1), out of 36: \(6/36 = 1/6 \approx 0.167\). 7 is the most likely sum: it's the longest diagonal.

What's the probability of at least one six? Use the complement: first find the chance of no six.

No six means each die shows 1–5: \(\frac{5}{6} \cdot \frac{5}{6} = \frac{25}{36}\) (independent dice multiply). So at least one six is \(1 - \frac{25}{36} = \frac{11}{36} \approx 0.306\). "At least one" questions are almost always easiest through "none".

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?

23 people: 50.7%. With 50 people it's 97%. The same "many pairs" effect is why hash collisions, duplicate IDs and duplicate training examples show up far sooner than you'd expect.

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?

Your first pick is right 1/3 of the time, and staying keeps exactly that. The other 2/3 of the time the car is behind one of the two doors you didn't pick, and the host has just shown you which one it isn't. Switching collects that whole 2/3. The host's choice isn't random, and that's the information.

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.)

Inside "first die is 6" there are 6 squares, and 3 of them reach 10 or more (6+4, 6+5, 6+6): \(3/6 = 0.5\). Learning something changed the probability from 1/6 to 1/2.

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 \]

The pictureKeep only the bright dots (the evidence happened). The answer is the red share of them.
The math\(P(H \mid E) = \dfrac{P(E \mid H)\,P(H)}{P(E)}\): the prior \(P(H)\) times the likelihood \(P(E \mid H)\), divided by how common the evidence is overall. The result is the posterior.

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
  1. 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".
  2. 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.
  3. 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).
  4. 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?

\(0.009 / (0.009 + 0.0891) = 0.009 / 0.0981 \approx 0.092\). A good test on a rare condition still gives mostly false alarms. Chapter 12 meets the same trap as a fraud detector's precision collapsing when fraud is rare.

Which change raises \(P(\text{sick} \mid +)\) the most, starting from those numbers? Try each on the sliders.

With a rare condition the false alarms from the huge healthy crowd dominate, so the false positive rate is what matters: at 1% the posterior jumps to about 47%. Testing only people with symptoms (a higher prior) works too, which is why doctors don't screen everyone for everything.

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

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?

"are you free now" scores 88% spam and "free tonight?" 74%: "free" and "now" only ever appeared in spam, and with 16 training messages the filter has no idea they're normal words too. More data fixes most of it. The last line, \(1/(1 + e^{h - s})\), is the sigmoid from the warm-up: two log-scores become one probability, the same trick logistic regression (chapter 13) uses.

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:

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?

\(\binom{4}{2} = 6\) orders (HHTT, HTHT, HTTH, THHT, THTH, TTHH), each with chance \(0.5^4 = 1/16\): \(6/16 = 0.375\). The tallest bar in the picture with n = 4, p = 0.5.

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.)

\(x = -4 \ln(0.5) = 4 \ln 2 \approx 2.77\) minutes. Shorter than the 4-minute average, because a few very long waits pull the average up.

A distribution gives every value's probability; its CDF, read backwards, turns uniform random numbers into samples of it.

8. What to carry forward

All lessons: AI from scratch.

Last updated