What we know
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.
Suppose 20 of the 100 emails are spam. Before reading any words, the chance an email is spam is 20/100 = 0.2. This starting belief is called the prior, written P(spam).
Suppose 60% of spam says "free": 12 of the 20 spam emails get a ring. This is the likelihood P(free | spam). The bar | means "given": the chance of "free", given that the email is spam.
Normal email, called ham, says "free" too, just less often. Suppose 5% of the 80 ham emails do: 4 more rings. These are false alarms: P(free | ham) = 4/80 = 0.05.
Updating on evidence
How often does "free" appear at all? Add both groups: 12 spam plus 4 ham is 16 of 100 emails, so P(free) = 0.16. Adding up over every possible cause like this is the law of total probability.
Now use the clue: this email says "free". So it must be one of the 16 ringed emails, and the other 84 drop out. Conditioning on evidence means shrinking the world to the outcomes that fit it.
Among the 16 emails left, 12 are spam. So P(spam | free) = 12/16 = 0.75. Seeing "free" raised the chance of spam from 0.2 to 0.75. This updated belief is called the posterior.
The formula
Bayes' theorem does the same sum with probabilities: P(spam | free) = P(free | spam) × P(spam) ÷ P(free). Put in the numbers: 0.6 × 0.2 ÷ 0.16 = 0.12 ÷ 0.16 = 0.75. Same answer as counting.
Now suppose only 2% of mail is spam. Then P(free) = 0.6 × 0.02 + 0.05 × 0.98 = 0.061, and P(spam | free) = 0.012 ÷ 0.061 ≈ 0.20. When the cause is rare, it stays fairly unlikely even after good evidence.
In code
The whole rule fits in a short Python function: multiply the likelihood by the prior, then divide by the total chance of the evidence. Naive Bayes spam filters make an update like this for every word in an email.
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.