# Toolkit 0.3: Probability

> Random variables, the normal curve, and Bayes' rule. Opening question: How do you reason carefully about things you cannot be sure of?

From *The Book of Machine Learning*, a free interactive machine learning textbook. Interactive version, with figures to use: https://thebookofml.com/probability/

This is a toolkit chapter, and optional. Data is noisy and predictions are uncertain, so machine learning needs a language for uncertainty. That language is probability. This chapter covers the few pieces of it the book uses.

## A number for uncertainty

A probability is a number between 0 and 1 that says how likely something is. 0 means it never happens, 1 means it always does, and 0.5 means it happens half the time. The same numbers are often written as percentages.

The most useful way to read a probability is as a long-run share. Saying a fair coin has probability 0.5 of heads is a claim about many flips: about half of them will be heads. It says very little about any single flip.

Roll two dice and add them up. The total is a random variable: a quantity whose value is settled by chance. Some totals are likelier than others. There is only one way to make 2, and six ways to make 7.

> **Interactive figure: Chance settles down in the long run.** Dark bars show the share of your rolls that gave each total. Orange rings mark the true probabilities.
> Try it: roll once a few times, then roll 10, and look at how ragged the bars are. Then press the 1,000 button several times.
> (Use it at https://thebookofml.com/probability/)

After ten rolls the bars look nothing like the rings. After a few thousand they match closely. That is why more data makes for better models: every estimate made from data is a share like these, and small samples are ragged.

## Average and spread

Two numbers summarise a random quantity well.

The first is where it is centred. The expected value is the long-run average: what you would get by averaging over a great many repeats. For two dice it is 7.

The second is how spread out it is. Take the distance of each value from the average, square it, and average those. That is the variance. Its square root, the standard deviation, is easier to read because it is back in the original units: roughly, how far a typical value sits from the average.

**Example: Eight quiz marks**

The marks are 2, 4, 4, 4, 5, 5, 7, 9.

1. Average: $(2 + 4 + 4 + 4 + 5 + 5 + 7 + 9) / 8 = 5$.
2. Distances from 5: −3, −1, −1, −1, 0, 0, 2, 4.
3. Squared: 9, 1, 1, 1, 0, 0, 4, 16. Their average is $32 / 8 = 4$. That is the variance.
4. Standard deviation: $\sqrt{4} = 2$.

A typical mark is about 2 away from the average of 5.

**Note:** Squaring should feel familiar. Mean squared error, from [the linear regression chapter](https://thebookofml.com/linear-regression/), is the same calculation with "distance from the prediction" in place of "distance from the average".

## The bell curve

Many quantities in the world pile up around an average and thin out symmetrically on both sides: heights, measurement errors, exam scores. The curve that describes this is the normal distribution, the bell curve. It is fixed entirely by two numbers, its average and its standard deviation.

> **Interactive figure: Centre and spread.** The height of the curve shows how common each score is. The shaded band covers the chosen number of standard deviations either side of the average.
> Try it: change the spread and watch the curve get taller and narrower, or lower and wider. Then switch the shaded range between 1, 2 and 3.
> (Use it at https://thebookofml.com/probability/)

Whatever the average and spread, the same shares always apply:

| Within | Share of values |
|---|---|
| 1 standard deviation of the average | about 68% |
| 2 standard deviations | about 95% |
| 3 standard deviations | about 99.7% |

So if exam scores average 67 with a standard deviation of 10, about two thirds of students score between 57 and 77, and almost nobody scores below 37.

The bell curve matters to this book for a specific reason. The usual picture of noisy data is "the true pattern, plus bell-shaped noise". Under that picture, the model that makes the observed data most probable is exactly the one with the smallest squared error. That is the deeper justification for least squares.

## When something is already known

Probabilities change when you learn something. The chance that a message is spam is one number. The chance that it is spam *given that it contains the word "free"* is a different, larger number. A probability that takes known information into account is a conditional probability.

Conditioning sounds abstract and is really just narrowing your attention. Here are the 34 messages from [the Naive Bayes chapter](https://thebookofml.com/naive-bayes/), sorted two ways at once.

> **Interactive figure: Conditioning is looking at one row or one column.** Each cell counts messages. The dark cell is the one being asked about; greyed cells are ruled out by what is known.
> Try it: choose 'given: it is spam' and read the answer. Then choose 'given: it contains free'. The dark cell is the same, but the answer is not.
> (Use it at https://thebookofml.com/probability/)

The two answers differ because they divide the same 9 messages by different totals:

- Of the **14 spam messages**, 9 contain "free": 64%.
- Of the **10 messages containing "free"**, 9 are spam: 90%.

Confusing these two is one of the most common mistakes in reasoning with data. Converting one into the other is what Bayes' rule does, and the [Naive Bayes chapter](/naive-bayes/) builds a whole classifier on it.

Two things are independent when knowing one tells you nothing about the other, so conditioning changes nothing. Two dice are independent. "Is spam" and "contains free" clearly are not.

**Check your understanding:** In a town, 90% of taxi drivers have a driving licence for over ten years, and 2% of all residents are taxi drivers. You meet someone who has had a licence for over ten years. Which statement is justified?

- There is a 90% chance they are a taxi driver — That reverses the condition. 90% is the chance of a long-held licence given a taxi driver, not the other way round.
- They are probably not a taxi driver **(correct)** — Taxi drivers are only 2% of residents, and many other people have long-held licences too. The 90% describes taxi drivers, not licence holders.
- Nothing can be said — Something can: taxi drivers are rare, so even strong evidence leaves the chance low. The exact number needs the share of non-drivers with long-held licences.

**Common mistake: Reading a conditional backwards**

"Most people with the illness test positive" does not mean "most people who test positive have the illness". If the illness is rare, the positives are mostly healthy people the test got wrong. Whenever you see a "given", check which group is being counted in the bottom of the fraction. This single confusion is behind a large share of the bad statistics in news reports and courtrooms.

## In code

```python
import numpy as np

rng = np.random.default_rng(0)                  # a seeded random generator

# Two dice, rolled 100,000 times.
totals = rng.integers(1, 7, 100_000) + rng.integers(1, 7, 100_000)
print(np.mean(totals == 7))                     # 0.167  share of sevens
print(totals.mean(), totals.std())              # 7.0  2.4  average and spread

# Exam scores from a bell curve with average 67 and spread 10.
scores = rng.normal(67, 10, 100_000)
print(np.mean(np.abs(scores - 67) < 10))        # 0.68  within one standard deviation

# Conditional probability is a share within a filtered subset.
is_spam  = np.array([1] * 14 + [0] * 20)
has_free = np.array([1] * 9 + [0] * 5 + [1] * 1 + [0] * 19)
print(has_free[is_spam == 1].mean())            # 0.64  P(free | spam)
print(is_spam[has_free == 1].mean())            # 0.90  P(spam | free)
```

## Key takeaways

- A **probability** is a long-run share between 0 and 1. Small samples are ragged; large ones settle.
- The **expected value** says where a random quantity is centred; the **standard deviation** says how spread out it is.
- The **normal distribution** is fixed by those two numbers. About 68% of values fall within one standard deviation.
- A **conditional probability** narrows attention to the cases where something is known to be true.
- "Chance of A given B" and "chance of B given A" are different numbers.

## What you should now be able to do

- Work out the average and standard deviation of a small set of numbers.
- Use the 68% and 95% rules to say where values from a bell curve will fall.
- Read a conditional probability off a table of counts, in either direction.

## Exercises

### Exercise (by hand)

Eight quiz scores are 2, 4, 4, 4, 5, 5, 7 and 9. Find the average, then the standard deviation (divide by the number of values).

**Hint:**

Find the average first. Then average the squared distances from it, and take the square root.

**Solution:**

The scores add up to 40, so the average is $40 / 8 = 5$.

The distances from the average are −3, −1, −1, −1, 0, 0, 2 and 4. Squared, they are 9, 1, 1, 1, 0, 0, 4 and 16, which add up to 32. The average squared distance is $32 / 8 = 4$, and its square root is the standard deviation: 2.

A typical score is about 2 points away from 5.

### Exercise (by hand)

Exam scores follow a bell curve with an average of 70 and a standard deviation of 8. Roughly what share of students score between 62 and 78? Between 54 and 86? Above 86?

**Hint:**

Count how many standard deviations each end of the range is from 70.

**Solution:**

62 to 78 is one standard deviation either side of the average: about 68%.

54 to 86 is two standard deviations either side: about 95%.

That leaves about 5% outside the range 54 to 86, split evenly between the two tails, so about 2.5% score above 86.

### Exercise (by hand)

Out of 100 emails, 30 are spam. The word "free" appears in 18 of the spam emails and in 7 of the others. What is the chance that a spam email contains "free"? What is the chance that an email containing "free" is spam?

**Hint:**

The top of both fractions is the same 18 emails. Decide which group goes on the bottom each time.

**Solution:**

Given spam, look only at the 30 spam emails: $18 / 30 = 0.6$.

Given "free", look only at the emails that contain it. There are $18 + 7 = 25$ of them, and 18 are spam: $18 / 25 = 0.72$.

The same 18 emails sit on top of both fractions. The answers differ because the bottoms differ: 30 spam emails in one case, 25 "free" emails in the other.

### Exercise (in code)

Simulate rolling a die 10 times and work out the share of sixes. Run it several times. Then do the same with 10,000 rolls. What changes?

**Hint:**

`rng.integers(1, 7, size=n)` gives n rolls. `(rolls == 6).mean()` gives the share of sixes.

**Solution:**

```python
import numpy as np

rng = np.random.default_rng()
for n in (10, 10_000):
    rolls = rng.integers(1, 7, size=n)   # whole numbers from 1 to 6
    print(n, (rolls == 6).mean())
```

Your numbers will differ on every run. With 10 rolls the share of sixes jumps around, and anything from 0 to 0.4 is common. With 10,000 rolls it stays within about 0.01 of the true value, $1/6 \approx 0.167$. A probability describes the long run, and small samples are ragged.

### Exercise (with the figure)

In the figure "Chance settles down in the long run", roll ten times and note the tallest and shortest bars. Press Reset and repeat a few times. Then press the 1,000 button several times. How far from the rings do the bars stray in each case?

**Hint:**

With ten rolls, each roll moves a bar by ten percentage points.

**Solution:**

With ten rolls the bars are wild. A face often does not appear at all, and one face commonly takes 30% or 40%, although each should have about 17%. No two tries look alike.

After a few thousand rolls every bar sits within a point or two of its ring, and repeating the experiment gives nearly the same picture every time. The chance of each face did not change. What changed is how much evidence there was about it.

## References

- D. Kunin and others, [Seeing Theory](https://seeing-theory.brown.edu), a visual introduction to probability and statistics.
- M. P. Deisenroth, A. A. Faisal and C. S. Ong, *Mathematics for Machine Learning*, chapter 6. Free at [mml-book.github.io](https://mml-book.github.io).
- K. P. Murphy, *Probabilistic Machine Learning: An Introduction*, chapter 2, [probml.github.io/pml-book](https://probml.github.io/pml-book/).

## Next

That is the whole toolkit: vectors to hold data, derivatives to measure change, and probability to describe uncertainty. The book proper starts with the question all three serve. What does it mean for a program to learn?
