Bayes' Rule and Independence

One line of algebra

Write the product rule both ways: \(P(a \wedge b) = P(a \mid b)P(b) = P(b \mid a)P(a)\). Divide by \(P(b)\):

$$ \boxed{\;P(\text{cause} \mid \text{effect}) = \frac{P(\text{effect} \mid \text{cause})\; P(\text{cause})}{P(\text{effect})}\;} $$

Each piece has a name:

  • \(P(\text{cause})\) is the prior: what you believed before the evidence.
  • \(P(\text{effect} \mid \text{cause})\) is the likelihood: how well the cause explains the evidence.
  • \(P(\text{effect})\) is the evidence (normalizer): \(= \sum_{c} P(\text{effect}\mid c)P(c)\), by marginalization.
  • \(P(\text{cause} \mid \text{effect})\) is the posterior: what you should believe now.
Why it matters

Knowledge usually comes in the causal direction: "a pothole triggers the bump sensor 90% of the time." That's a property of the sensor, and it's stable. But decisions need the diagnostic direction: "the sensor fired, so is there a pothole?" That depends on how common potholes are, which changes from road to road. Bayes' rule converts stable causal knowledge plus a local prior into the diagnosis you need. Doctors, spam filters, robot localization and courtrooms all run on this one line.

The example everyone gets wrong

A disease affects 1% of people. A test detects it 90% of the time (sensitivity), and gives a false positive in 9% of healthy people. You test positive. What's the chance you have the disease?

Most people (including, in studies, most doctors) say about 90%. Let's compute it:

$$ P(D \mid +) = \frac{P(+\mid D)P(D)}{P(+\mid D)P(D) + P(+\mid \neg D)P(\neg D)} = \frac{0.9 \times 0.01}{0.9\times 0.01 + 0.09 \times 0.99} = \frac{0.009}{0.009 + 0.0891} \approx 0.092 $$

About 9%, not 90%. Look at it with 1,000 people. 10 are sick, and 9 of them test positive. 990 are healthy, and about 89 of them test positive too. So of the 98 positives, only 9 are sick. The false positives from the huge healthy group swamp the true positives from the tiny sick group. Ignoring the prior like this is called the base-rate fallacy.

Play with it. Drop the base rate to 0.1% and even a 99%-sensitive test is nearly useless on its own. Raise it to 30% (testing only people with symptoms) and the same test becomes very informative. The prior matters as much as the test.

Bolt's pothole sensor

Potholes occur on 2% of path segments. Bolt's bump sensor fires on 95% of potholes, but also on 10% of smooth segments (speed bumps, a dropped water bottle). The sensor fires. Then

$$ P(pothole \mid fire) = \frac{0.95 \times 0.02}{0.95 \times 0.02 + 0.10 \times 0.98} = \frac{0.019}{0.117} \approx 0.16. $$

Only 16%! Should Bolt slam the brakes? That depends on the costs of each mistake, which needs utility (§4.3) and decision theory (§5.1). Probability tells you what to believe, and utility tells you what to do about it.

Sequential updating: today's posterior is tomorrow's prior

After a positive test, your belief is 9.2%. Take a second, independent test, and use 9.2% as the new prior:

def posterior(prior, p_pos_given_h, p_pos_given_not_h):
    """P(H | positive test) by Bayes' rule."""
    evidence = p_pos_given_h * prior + p_pos_given_not_h * (1 - prior)
    return p_pos_given_h * prior / evidence

p = 0.01                                     # 1% of people have the disease
for test in range(1, 4):                     # the same test, repeated (independent errors)
    p = posterior(p, 0.90, 0.09)
    print(f"after positive test #{test}: P(disease) = {p:.3f}")
after positive test #1: P(disease) = 0.092
after positive test #2: P(disease) = 0.503
after positive test #3: P(disease) = 0.910

Evidence accumulates: 1% → 9% → 50% → 91%. This is exactly how Bolt will track its position with a noisy sensor in §5.5 (POMDPs): predict, observe, apply Bayes' rule, repeat.

The odds form (fast mental math)

Odds = \(P/(1-P)\). Bayes' rule in odds form is just a multiplication:

$$ \underbrace{\frac{P(H\mid e)}{P(\neg H \mid e)}}_{\text{posterior odds}} = \underbrace{\frac{P(e \mid H)}{P(e \mid \neg H)}}_{\text{likelihood ratio}} \times \underbrace{\frac{P(H)}{P(\neg H)}}_{\text{prior odds}} $$

For the disease test the likelihood ratio is \(0.9/0.09 = 10\). Prior odds \(1:99\) become posterior odds \(10:99\), so \(P = 10/109 \approx 0.092\). ✓ A second test makes it \(100:99\), about 50%. ✓

Independence

\(A\) and \(B\) are independent (\(A \perp B\)) if learning one tells you nothing about the other:

$$ P(A \mid B) = P(A) \iff P(A, B) = P(A)\,P(B). $$

Independence is what makes probability tractable. If Bolt's 30 variables were all independent, the joint would need only 30 numbers instead of \(2^{30}\). Unfortunately, full independence is rare in interesting problems. Rain and Late are certainly not independent.

Conditional independence: the workhorse

Much more common: two things are dependent, but become independent once you know a third thing.

$$ A \perp B \mid C \iff P(A, B \mid C) = P(A \mid C)\,P(B \mid C). $$

Example: two hostel residents, John and Mary, both call security when they hear Bolt's anti-theft alarm. Whether John calls and whether Mary calls are dependent: if John called, the alarm probably went off, so Mary probably called too. But given that the alarm went off, John's call tells you nothing more about Mary's. Each one only reacts to the alarm. So \(John \perp Mary \mid Alarm\). This exact example is the heart of Chapter 7.

Naive Bayes: Bayes' rule + conditional independence

Suppose we want \(P(\text{Class} \mid x_1, \dots, x_n)\) and we assume every feature is conditionally independent of the others given the class:

$$ P(\text{Class} \mid x_1,\dots,x_n) = \alpha\, P(\text{Class}) \prod_{i=1}^n P(x_i \mid \text{Class}). $$

The assumption is "naive" because it's usually false, but the classifier works surprisingly well (spam filters were built on it). Each \(P(x_i \mid \text{Class})\) is just a count from data. Here it is on the tennis dataset you'll meet again in Chapter 6. Should we play tennis on a sunny, cool, high-humidity, strong-wind day?

from collections import Counter

# Mitchell's PlayTennis data: (Outlook, Temp, Humidity, Wind) -> Play
data = [("Sunny","Hot","High","Weak","No"), ("Sunny","Hot","High","Strong","No"),
        ("Overcast","Hot","High","Weak","Yes"), ("Rain","Mild","High","Weak","Yes"),
        ("Rain","Cool","Normal","Weak","Yes"), ("Rain","Cool","Normal","Strong","No"),
        ("Overcast","Cool","Normal","Strong","Yes"), ("Sunny","Mild","High","Weak","No"),
        ("Sunny","Cool","Normal","Weak","Yes"), ("Rain","Mild","Normal","Weak","Yes"),
        ("Sunny","Mild","Normal","Strong","Yes"), ("Overcast","Mild","High","Strong","Yes"),
        ("Overcast","Hot","Normal","Weak","Yes"), ("Rain","Mild","High","Strong","No")]

def naive_bayes(x):
    labels = Counter(row[-1] for row in data)
    scores = {}
    for y, n_y in labels.items():
        score = n_y / len(data)                                   # prior P(y)
        for i, value in enumerate(x):                             # times P(x_i | y) for each feature
            score *= sum(1 for row in data if row[-1] == y and row[i] == value) / n_y
        scores[y] = score
    z = sum(scores.values())
    return {y: round(s, 4) for y, s in scores.items()}, {y: round(s / z, 3) for y, s in scores.items()}

print(naive_bayes(("Sunny", "Cool", "High", "Strong")))
({'No': 0.0206, 'Yes': 0.0053}, {'No': 0.795, 'Yes': 0.205})

By hand: \(P(\text{Yes}) \cdot P(\text{sunny}|\text{Yes}) \cdots = \frac{9}{14}\cdot\frac29\cdot\frac39\cdot\frac39\cdot\frac39 \approx 0.0053\) and \(P(\text{No}) \cdots = \frac{5}{14}\cdot\frac35\cdot\frac15\cdot\frac45\cdot\frac35 \approx 0.0206\). Normalizing gives P(No) ≈ 0.795, so don't play. This is a classic exam computation.

The zero-count problem

If some feature value never appears with a class in training (e.g. "Overcast" never occurs with "No"), then \(P(\text{Overcast}\mid\text{No}) = 0\), and that single zero wipes out the whole product. The fix is Laplace (add-one) smoothing: \(P(x_i = v \mid y) = \frac{\text{count}+1}{n_y + |\text{values}|}\). This is regularization again (§2.4): a prior belief that no event is impossible, which protects against overfitting to small counts.

Connections
  • Naive Bayes is the simplest Bayesian network: a class node with an arrow to every feature (Ch 7).
  • Bayes' rule with a sequence of observations is the belief update of POMDPs (§5.5).
  • Regularization as a prior (§2.4) is Bayes' rule applied to model weights: posterior ∝ likelihood × prior.