holehouse.org Blog Machine learning notes

05: Probability and Bayes' Rule

A note on this chapter

The vocabulary

P(A,B)=P(AB)P(B) The product rule: "both" is "one of them" times "the other, given the first". Chaining it across a whole sequence is exactly how chapter 22 factorises a sentence.
P(B)=AP(BA)P(A) The sum rule (marginalization): the total probability of B is its probability under each scenario A, weighted by how likely each scenario is.

Bayes' rule

P(AB)=P(BA)P(A)P(B) Bayes' rule. Read as a machine for reversing conditionals: from "how likely is the evidence, given the hypothesis" to "how likely is the hypothesis, given the evidence" — which is the direction you actually want, and the direction experiments don't give you.

A worked example: the rare disease

p_disease = 0.005          # the prior - chapter 11's 0.5% prevalence
sens = 0.99                # P(positive | disease)   - the likelihood
spec = 0.95                # P(negative | healthy)

# the sum rule: total probability of a positive test
p_pos = sens * p_disease + (1 - spec) * (1 - p_disease)   # 0.0547

# Bayes' rule
sens * p_disease / p_pos   # 0.0905 - about 9%, not 99%

A 99%-sensitive test and the posterior is still only 9% — because the 5% false-positive rate acting on the enormous healthy majority swamps the true cases. The prior does most of the work when classes are skewed.

Maximum likelihood and MAP

θ^=arg maxθi=1mlogp(y(i)x(i);θ) Log because products of many probabilities underflow and sums don't — and because maximising a log maximises the original. This single line is where two of the notes' cost functions come from: model y as Bernoulli and you get chapter 06's cross-entropy; model the residuals as Gaussian and you get chapter 02's squared error. Neither cost was an aesthetic choice — both are MLE under a stated noise model.
θ^=arg maxθ[i=1mlogp(y(i)x(i);θ)+logp(θ)] One extra term. Now choose a Gaussian prior for the parameters — θj ∼ N(0, τ²), "parameters are probably small" — and log p(θ) is a constant minus Σθj²/2τ². That is chapter 07's regularization penalty, derived rather than bolted on: L2 regularization is MAP estimation with a Gaussian prior, and λ is just the noise-to-prior variance ratio. Chapter 07 said "prefer small parameters" as an instinct; this is the instinct as a theorem.

Generative vs discriminative classifiers

P(yx)P(xy)P(y) Generative classification in one line: score each class by "how typical is this x of the class" times "how common is the class", and normalize. The rare-disease example above is exactly this with two classes.

Naive Bayes

P(xy)=j=1nP(xjy) One number per word per class — "how often does discount appear in spam" — instead of a distribution over every possible email. 20,000 parameters instead of 210,000. The assumption is false (words travel in packs), which is why it's called naive; it works anyway because classification only needs the scores ordered correctly, not calibrated. Chapter 15 made the identical assumption when it multiplied per-feature Gaussians.
import numpy as np

vocab = ["andrew", "buy", "deal", "discount", "now"]   # chapter 11's vocabulary

X = np.array([[0,1,1,1,1],      # emails as chapter 11's bitmaps -
              [0,1,0,1,1],      # four spam:  buy/deal/discount/now
              [0,1,1,0,1],
              [0,1,1,1,0],
              [1,0,0,0,1],      # four ham: andrew, sometimes buy/deal/now
              [1,0,1,0,0],
              [1,0,0,0,0],
              [1,1,0,0,1]])
y = np.array([1,1,1,1, 0,0,0,0])

phi_y    = y.mean()                                    # P(spam) = 0.5
phi_spam = (X[y==1].sum(0) + 1) / ((y==1).sum() + 2)   # per-word rates,
phi_ham  = (X[y==0].sum(0) + 1) / ((y==0).sum() + 2)   # Laplace-smoothed

def p_spam(x):                     # Bayes' rule, in logs
    ls = np.log(phi_y)   + (x*np.log(phi_spam) + (1-x)*np.log(1-phi_spam)).sum()
    lh = np.log(1-phi_y) + (x*np.log(phi_ham)  + (1-x)*np.log(1-phi_ham)).sum()
    return 1 / (1 + np.exp(lh - ls))

p_spam(np.array([0,1,0,1,1]))   # 0.971 - "buy discount now": spam
p_spam(np.array([1,0,0,0,1]))   # 0.013 - "andrew ... now": not spam

A complete spam classifier: count, smooth, apply Bayes' rule in log space. Note the last line — converting a log-odds difference to a probability is chapter 06's sigmoid, which is no coincidence (next section). Real systems differ only in vocabulary size.

Naive Bayes and logistic regression

Where Bayes lives in these notes

Summary