P(spam|free) =P(free|spam) × P(spam)P(free)= ?1prior = 0.22like = 0.63alarm = 0.054p_free = 0.12 + 0.045like * prior / p_free6def bayes(prior, like, alarm):7 hit = like * prior8 miss = alarm * (1 - prior)9 return hit / (hit + miss)10bayes(0.02, 0.6, 0.05)
Board: 100 emails; filled squares are spam, ringed squares say "free"Faded squares drop out once we know the email says "free"Formula block: Bayes' theorem, its terms filling in with numbersCalculator and Python card: count, then divideEach square is one of 100 emails: 20 are spam (filled), and the 16 that say "free" have a ring (12 spam, 4 normal). Knowing an email says "free" keeps only the 16 ringed squares, and 12 of them are spam: P(spam | free) = 12/16 = 0.75. Bayes' theorem gets the same number from the rates: P(free | spam) × P(spam) ÷ P(free) = 0.6 × 0.2 ÷ 0.16. The rates in this example (20% spam, 60% of spam and 5% of normal mail saying "free") are round numbers chosen to make the counting easy. Real rates depend on the mailbox.

What we know

  1. A spam filter sees the word "free" in an email. How sure can it be that the email is spam? Bayes' theorem answers questions like this. To see it, picture 100 emails as 100 squares.

Updating on evidence

The formula

In code

Try it in the Python prompt

;; step 1/10 · A word in an email
>>> emails = 10 * 10
>>> emails
100

The Python lines in the steps build on each other: run them in order in one session. Python floats are rounded binary fractions. 0.6 * 0.2 / 0.16 happens to print 0.75 exactly, but 0.05 * 0.8 prints 0.04000000000000001.