Velamuvi AIAcademy
Probability

Lesson 6 of 16 · Conditioning

Bayes' Theorem

Bayes' theorem step by step: prior, likelihood, evidence and posterior, the law of total probability and updating beliefs with new evidence, in runnable Python.

  • 7 min read
  • Intermediate
  • Reviewed
In this lesson you will learn
  • State Bayes' theorem and explain where it comes from
  • Name the prior, likelihood, evidence and posterior
  • Use the law of total probability to find P(evidence)
  • Write a Bayes' theorem function in Python
  • Update a belief step by step as new evidence arrives

Turning a condition around

Lesson 5 ended with a problem: P(free | spam) and P(spam | free) are different numbers. Often the first is easy to measure and the second is what we actually want:

  • A doctor knows P(positive test | disease) from trials, but the patient wants P(disease | positive test).
  • A spam filter can count P(word | spam) in old emails, but it needs P(spam | word) for a new one.

Bayes' theorem turns one into the other.

Where it comes from

The general multiplication rule from lesson 5 can be written two ways, because “A and B” is the same event as “B and A”:

P(A and B) = P(A | B) × P(B)
P(A and B) = P(B | A) × P(A)

Set the two right-hand sides equal and divide by P(B):

Each part has a name:

PartNameMeaning
P(H)priorHow likely H was before seeing the evidence
P(E | H)likelihoodHow likely the evidence is if H is true
P(E)evidenceHow likely the evidence is overall
P(H | E)posteriorHow likely H is after seeing the evidence

In words: posterior = likelihood × prior ÷ evidence.

Finding P(evidence)

P(E) is often the one number you don't have directly. You can build it from the two ways the evidence can happen: with H true, or with H false.

Putting it together in Python:

Try it yourselfPython
def bayes(prior, p_e_given_h, p_e_given_not_h):
    """Return P(H | E), given P(H), P(E | H) and P(E | not H)."""
    p_e = p_e_given_h * prior + p_e_given_not_h * (1 - prior)    # law of total probability
    return p_e_given_h * prior / p_e

# Lesson 5's emails. H = the email is spam, E = it contains "free"
print(f"P(spam | free) = {bayes(prior=0.2, p_e_given_h=0.6, p_e_given_not_h=0.35):.3f}")

# Chargers. H = it came from factory B, E = it is faulty
print(f"P(factory B | faulty) = {bayes(prior=0.4, p_e_given_h=0.05, p_e_given_not_h=0.02):.3f}")

The first result matches the 0.30 we got by counting the table in lesson 5, but this time we only needed three rates instead of the whole table: 20% of emails are spam, 60% of spam contains “free”, and 35% of normal email does too.

Updating step by step

Bayes' theorem really shines when evidence arrives a piece at a time. After each piece, today's posterior becomes the prior for the next update.

Someone hands you a coin that is either fair or biased to land heads 80% of the time. You start at 50/50 and flip it eight times:

Try it yourselfPython
# Is this coin fair, or biased so that it lands heads 80% of the time?
p_heads = {"biased": 0.8, "fair": 0.5}
p_biased = 0.5                       # prior: no idea, so 50/50

for flip in "HHTHHHHH":
    like_biased = p_heads["biased"] if flip == "H" else 1 - p_heads["biased"]
    like_fair = p_heads["fair"] if flip == "H" else 1 - p_heads["fair"]
    evidence = like_biased * p_biased + like_fair * (1 - p_biased)
    p_biased = like_biased * p_biased / evidence     # this posterior is the next prior
    print(f"after {flip}: P(biased) = {p_biased:.3f}")

Each head nudges the belief towards “biased”, the tail pulls it back, and after eight flips you're about 92% sure the coin is biased. The more evidence you gather, the less the starting prior matters.

Common mistakes

Practice exercise

The weather forecast says rain. How likely is rain now? Use the law of total probability and then Bayes' theorem.

Your solutionPython
p_rain = 0.20                    # it rains on 20% of days
p_forecast_given_rain = 0.80     # on rainy days, the forecast said rain 80% of the time
p_forecast_given_dry = 0.10      # on dry days, the forecast still said rain 10% of the time

# The forecast says rain. Calculate:
#   1. P(forecast says rain), using the law of total probability
#   2. P(rain | forecast says rain), using Bayes' theorem
# Print both on one line, rounded to 2 decimals.
Knowledge check

In Bayes' theorem, what is the prior?

Summary

  • Bayes' theorem: P(H | E) = P(E | H) × P(H) / P(E). It turns P(E | H) into P(H | E).
  • The parts are the prior, likelihood, evidence and posterior.
  • Law of total probability: P(E) = P(E | H) × P(H) + P(E | not H) × P(not H).
  • When evidence arrives in steps, each posterior becomes the next prior.

Next: the base rate trap.

Finished reading? Tick it off to track your progress.