Law of Total Probability and Bayes' Theorem

Master the law of total probability and Bayes' theorem for probabilistic inference.

25 min read
Intermediate

Introduction

Two of the most powerful tools in probability: the Law of Total Probability (breaking problems into cases) and Bayes' Theorem (updating beliefs with evidence).

Learning Objectives:

  • Apply law of total probability
  • Use Bayes' theorem for inference
  • Solve real-world problems

Law of Total Probability

If B1,B2,...,BnB_1, B_2, ..., B_n partition the sample space (disjoint and cover ฮฉ\Omega), then:

P(A)=โˆ‘i=1nP(AโˆฃBi)P(Bi)P(A) = \sum_{i=1}^{n} P(A | B_i) P(B_i)

Strategy: Break AA into cases based on which BiB_i occurs.

Bayes' Theorem

P(BiโˆฃA)=P(AโˆฃBi)P(Bi)P(A)=P(AโˆฃBi)P(Bi)โˆ‘jP(AโˆฃBj)P(Bj)P(B_i | A) = \frac{P(A | B_i) P(B_i)}{P(A)} = \frac{P(A | B_i) P(B_i)}{\sum_j P(A | B_j) P(B_j)}

Interpretation:

  • P(Bi)P(B_i): Prior probability (before seeing AA)
  • P(BiโˆฃA)P(B_i | A): Posterior probability (after seeing AA)
  • P(AโˆฃBi)P(A | B_i): Likelihood (how likely AA is under BiB_i)
python
# Medical test example
def bayes_medical_test():
    # Prior: 1% have disease
    p_disease = 0.01
    p_no_disease = 0.99
    
    # Likelihood: test accuracy
    p_pos_given_disease = 0.95  # sensitivity
    p_pos_given_no_disease = 0.05  # false positive rate
    
    # Total probability of positive test
    p_pos = p_pos_given_disease * p_disease + p_pos_given_no_disease * p_no_disease
    
    # Bayes: P(disease | positive test)
    p_disease_given_pos = (p_pos_given_disease * p_disease) / p_pos
    
    print(f"P(disease) = {p_disease:.2%} (prior)")
    print(f"P(+ | disease) = {p_pos_given_disease:.2%}")
    print(f"P(+ | no disease) = {p_pos_given_no_disease:.2%}")
    print(f"\nP(disease | +) = {p_disease_given_pos:.2%} (posterior)")

bayes_medical_test()

Key Takeaways

  1. Law of total probability: Sum over partition cases
  2. Bayes' theorem: Update beliefs with evidence
  3. Applications: Diagnostics, spam filtering, ML

Next: Independence of events!