Toolkit 0.3 // Toolkit

Probability.

How do you reason carefully about things you cannot be sure of?

Reading time
12 min

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

Figure

Chance settles down in the long run

Total 2: 0.0% of rollsTotal 3: 0.0% of rollsTotal 4: 0.0% of rollsTotal 5: 0.0% of rollsTotal 6: 0.0% of rollsTotal 7: 0.0% of rollsTotal 8: 0.0% of rollsTotal 9: 0.0% of rollsTotal 10: 0.0% of rollsTotal 11: 0.0% of rollsTotal 12: 0.0% of rollsTrue probability of 2: 2.8%True probability of 3: 5.6%True probability of 4: 8.3%True probability of 5: 11.1%True probability of 6: 13.9%True probability of 7: 16.7%True probability of 8: 13.9%True probability of 9: 11.1%True probability of 10: 8.3%True probability of 11: 5.6%True probability of 12: 2.8%
  • Share of your rolls
  • True probability
Rolls so far
0
Last roll
–
Share of sevens (true: 16.7%)
–
Average total (true: 7)
–
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.

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 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 , is easier to read because it is back in the original units: roughly, how far a typical value sits from the average.

ExampleEight 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 + 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=432 / 8 = 4. That is the variance.
  4. Standard deviation: 4=2\sqrt{4} = 2.

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

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 , the bell curve. It is fixed entirely by two numbers, its average and its standard deviation.

Figure

Centre and spread

Average (centre)
67
Standard deviation (spread)
10
Scores from 57 to 77
68.3%
67
10
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.

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

WithinShare of values
1 standard deviation of the averageabout 68%
2 standard deviationsabout 95%
3 standard deviationsabout 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 .

Conditioning sounds abstract and is really just narrowing your attention. Here are the 34 messages from , sorted two ways at once.

Figure

Conditioning is looking at one row or one column

contains "free"does nottotal
spam9514
normal11920
total102434
Chance a message is spam and contains "free"
9 of 34 = 26%
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.

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 builds a whole classifier on it.

Two things are 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.

Checkpoint

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?

In code

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.
You can now
  • 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

Try each one before opening its solution. Getting stuck for a few minutes is where most of the learning happens.

Exerciseby 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=540 / 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=432 / 8 = 4, and its square root is the standard deviation: 2.

A typical score is about 2 points away from 5.

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

Exerciseby 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.618 / 30 = 0.6.

Given “free”, look only at the emails that contain it. There are 18+7=2518 + 7 = 25 of them, and 18 are spam: 18/25=0.7218 / 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.

Exercisein 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
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≈0.1671/6 \approx 0.167. A probability describes the long run, and small samples are ragged.

Exercisewith 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 and further reading

  • D. Kunin and others, Seeing Theory, 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.
  • K. P. Murphy, Probabilistic Machine Learning: An Introduction, chapter 2, probml.github.io/pml-book.

Last updated Spotted a mistake? Suggest an editWhat changed

In this chapter
  1. Top of the chapter
  2. 0.3.1A number for uncertainty
  3. 0.3.2Average and spread
  4. 0.3.3The bell curve
  5. 0.3.4When something is already known
  6. 0.3.5In code
  7. Exercises
Search

    The Book of Machine Learning
    Search
    Reading settings
    Text size
    Colours

    Saved in this browser only.

    Keyboard shortcuts
    /
    Search the book
    ← →
    Previous and next chapter
    g
    Glossary
    c
    Table of contents
    e
    Jump to the exercises
    t
    Reading settings
    ?
    Show this list
    Esc
    Close a window or pop-in