Notes
All notes

Deriving Naive Bayes (ML #10)

Your fraud model flags 4,000 transactions a day out of 200,000. Investigators clear 3,850 of them as false alarms. The team concludes the model is broken and proposes rebuilding it as gradient boosting over 90 engineered features.

Before that work starts, the question to ask is what “broken” means. Naive Bayes on this problem has a training cost of roughly zero and an inference cost of one pass. If it achieves comparable ranking, the 90 features are buying nothing. This chapter derives where that speed and that ranking quality come from, and — more useful — derives exactly when the independence assumption destroys it.

Bayes’ theorem from the definition

Start from the definition of conditional probability, which for events \(A, B\) with \(\Pr(B) > 0\) is

\[ \Pr(A \mid B) = \frac{\Pr(A \cap B)}{\Pr(B)} \]

Rearranging the symmetric form, \(\Pr(A \mid B)\Pr(B) = \Pr(A \cap B) = \Pr(B \mid A)\Pr(A)\), and dividing by \(\Pr(B)\):

\[ \boxed{\; \Pr(A \mid B) = \Pr(B \mid A)\,\frac{\Pr(A)}{\Pr(B)} = \text{likelihood} \times \text{prior} \times \frac{1}{\text{marginal}} \;} \]

Read the three pieces in words. \(\Pr(A)\) is how common \(A\) is on its own — the prior. \(\Pr(B \mid A)\) is how much more likely \(B\) is when \(A\) holds — the likelihood. \(\Pr(B)\) is how common \(B\) is overall — the evidence, and the only term you cannot compute without already seeing the answer.

The direction matters. \(\Pr(A \mid B)\) and \(\Pr(B \mid A)\) are completely different quantities, and the whole theorem is the machinery for moving between them. The classic medical example: the base rate of a rare disease is 1 in 10,000, and a test with 99% sensitivity has 1% false positives. Then

\[ \Pr(\text{disease} \mid +) = 0.0099 \times \frac{0.0001}{0.0001 \cdot 0.0099 + 0.9999 \cdot 0.01} \approx 0.0098 \]

— about 1%, not 99%. A near-perfect test on a rare condition yields mostly false positives, purely because the prior is small. This is Bayes’ theorem and it is why your classifier needs calibrated priors, a point Chapter 14 returns to.

The derivation of the classifier

For classification with features \(x = (x_1, \dots, x_d)\) and classes \(c\), Bayes’ rule gives the posterior directly:

\[ \Pr(c \mid x) = \Pr(x \mid c)\,\frac{\Pr(c)}{\Pr(x)} \]

Now the simplification that makes it fast. We predict \(\hat{c} = \arg\max_c \Pr(c \mid x)\). Two deletions follow:

What survives is the comparison \(\Pr(x \mid c)\Pr(c)\) across classes — and that is all we need to fit.

Bayes’ theorem as a picture

The one diagram worth drawing for this chapter, because it is where the intuition of “prior × likelihood ÷ evidence” comes from:

\begin{tikzpicture}[font=\rmfamily, >=stealth,
  b/.style={draw, thick, rounded corners=4pt, minimum width=2.15cm, minimum height=0.72cm, align=center, font=\rmfamily\small},
  a/.style={->, thick}]
  \node[b, fill=gray!12] (box) at (0,0) {population};
  \fill[blue!12] (-3.2,-1.2) rectangle (-0.5,-3.2);
  \fill[orange!16] (0.5,-1.2) rectangle (3.2,-3.2);
  \node[b, fill=blue!10, minimum width=2.3cm, minimum height=0.6cm] (c) at (-1.85,-1.55) {class $c$};
  \node[b, fill=orange!16, minimum width=2.3cm, minimum height=0.6cm] (d) at (1.85,-1.55) {not $c$};
  \foreach \x/\y in {-2.6/-2.5, -1.9/-2.9, -1.2/-2.4, -2.3/-2.0}
    \fill[blue!70!black] (\x,\y) circle (1.7pt);
  \foreach \x/\y in {1.1/-2.4, 1.8/-2.9, 2.5/-2.5, 1.4/-1.95}
    \fill[orange!90!black] (\x,\y) circle (1.7pt);
  \node[font=\rmfamily\scriptsize, align=center, text=black!65] at (-1.85,-3.55) {$\Pr(c)$ the prior};
  \node[font=\rmfamily\scriptsize, align=center, text=black!65] at (1.85,-3.55) {$1-\Pr(c)$};
  \draw[a] (d.south) -- ++(0,-0.35) node[right, font=\rmfamily\scriptsize] {evidence $\Pr(x)$} ++(2.4,0);
  \draw[a] (d.north) -- ++(0,0.5) node[right, font=\rmfamily\scriptsize] {likelihood $\Pr(x\mid\neg c)$};
  \node[font=\rmfamily\scriptsize, align=center, text=blue!60!black] at (-3.9,-2.2) {posterior\\$\Pr(c\mid x)$};
\end{tikzpicture}

The theorem is one statement about a rectangle: read the same area two ways. \(\Pr(c\mid x)\) is the width of the left band relative to the whole box; \(\Pr(x\mid c)\) is the height at which that band’s horizontal slice sits. Multiplying prior by likelihood and dividing by evidence converts one reading into the other. The medical-test example at the top is this picture with a very thin prior band — and a correspondingly thin posterior.

Which NB to use

variant features likelihood notes
Gaussian NB continuous \(p(x_j \mid c) = \mathcal{N}(\mu_{jc}, \sigma^2_{jc})\) fast closed form; shared \(\sigma\) ⟹ linear boundary (same as LDA)
Multinomial NB counts (word counts) \(\frac{n_{jc}!}{\prod_k n_{jck}!}\prod_k p_{jck}^{n_{jck}}\) the classic text classifier
Bernoulli NB binary presence (any term count > 0) \(\theta_{jc}^{x_j}(1-\theta_{jc})^{1-x_j}\) robust to repeated terms; complements multinomial
Complement NB any fits \(\Pr(\bar{c})\) instead of \(\Pr(c)\) corrects double-counting bias; a cheap default upgrade

Multinomial’s multinomial coefficient \(\frac{n_{jc}!}{\prod_k n_{jck}!}\) depends on the document, not the class — so it is identical for every class and drops out of the argmax, leaving the familiar \(\sum_j x_{jc}\log p_{jc}\) score. This is why implementations that ignore it still classify correctly.

The naive assumption, and its exact price

To factor the likelihood, assume the features are conditionally independent given the class:

\[ \Pr(x_1, \dots, x_d \mid c) = \prod_{j=1}^{d} \Pr(x_j \mid c) \]

This is where “naive” comes from, and it is almost always false. The assumption fails for correlated features, and the failure mode is precise: correlated features double-count their evidence.

Two correlated features are not two independent pieces of evidence — they are one piece observed twice. Naive Bayes multiplies both likelihoods anyway, so the log-posterior double-counts:

\[ \log \Pr(x \mid c) = \log \Pr(x_1 \mid c) + \log \Pr(x_2 \mid c) \quad\text{even when } x_1 \approx x_2 \]

A class that is mildly favoured by both features gets a boost proportional to the product of the ratios, not the evidence. The model becomes overconfident, and its decision boundary gets pulled toward whichever class benefits from the duplicated signal.

import numpy as np

def gauss_nb_fit_log(X, y):
    """Gaussian NB in log space, with shared variance (LDA-style)."""
    classes = np.unique(y)
    n, d = X.shape
    prior, mu, var = {}, {}, {}
    for c in classes:
        m = X[y == c]
        prior[c] = m.shape[0] / n
        mu[c] = m.mean(0)
        var[c] = m.var(0) + 1e-9          # variance floor: avoid log(0)
    # pooled (shared) covariance
    pooled = sum(prior[c] * var[c] for c in classes)
    return {"classes": classes, "prior": prior, "mu": mu, "var": var, "pooled": pooled}

def nb_log_posterior(model, X):
    """log P(c) + log P(x|c) for every class -- no products, no underflow."""
    L = []
    for c in model["classes"]:
        mu, var, pooled = model["mu"][c], model["var"][c], model["pooled"]
        # shared-variance form: the log-det term is constant in c, so omit it
        ll = -0.5 * (((X - mu) ** 2) / pooled).sum(axis=1)
        L.append(ll + np.log(model["prior"][c]))
    return np.array(L).T

Two deliberate choices. Shared variance across classes: the per-class term \(-\frac{d}{2}\log 2\pi\sigma_c^2\) is constant with respect to \(c\), so the argmax does not need it, and dropping it both simplifies the code and improves conditioning when a class is rare. Summing logs instead of multiplying probabilities — see the underflow section, this is not optional.

Underflow: why log-space is mandatory

Multiply many numbers in \((0,1)\) and the result collapses to zero. In IEEE 754 double precision the smallest positive normal is \(2^{-1022}\) and the smallest subnormal is about \(2^{-1074}\). So a product of feature probabilities underflows to exactly 0 once enough factors are involved:

\[ \left(\tfrac{1}{2}\right)^{1075} \approx 2^{-1075} \quad \longrightarrow \quad 0.0 \text{ in float64} \]

Concretely, with 1,200 features each contributing a probability of 0.5, the joint probability is \(\left(\frac{1}{2}\right)^{1200} \approx 10^{-361}\) — well below the smallest representable positive float, so a direct implementation returns 0 for every class, and the argmax is then arbitrary. This is not a rare edge case; it is what happens to any text classifier with more than about 1,000 features, which is most of them.

The fix is to work in log space, where the sum of many small numbers stays accurate:

\[ \log \prod_j p_j = \sum_j \log p_j \]

and then, when you genuinely need probabilities rather than a ranking, use log-sum-exp to exponentiate safely:

\[ \log\sum_i e^{z_i} = M + \log\sum_i e^{z_i - M}, \qquad M = \max_i z_i \]

Subtracting the max before exponentiating guarantees every argument is \(\le 0\), so no overflow; the arithmetic itself is stable. Note that for classification you never need the probability — only the argmax — and since \(\log\) is monotone, ranking log-posteriors is exactly ranking posteriors. That is the entire reason naive Bayes is fast: it is \(O(nd)\) arithmetic with no iteration and no convergence question.

Zero frequency and smoothing

Estimate each \(\Pr(x_j \mid c)\) as a frequency, \(\hat p = \text{count}(x_j, c)/\text{count}(c)\), and a feature value unseen in a class gives \(\hat p = 0\). Since the class score is a product, one zero annihilates the whole thing: a single word that never appeared in the spam training set makes spam score 0 forever, no matter how many other spam-indicating words appear.

Laplace (additive) smoothing fixes it by adding one pseudo-count per outcome:

\[ \hat p_j = \frac{\text{count}(x_j, c) + \alpha}{\text{count}(c) + \alpha V} \]

with \(\alpha = 1\) and \(V\) the number of possible values. The numerator and denominator both grow, so no probability can reach zero, and the estimate stays normalized. \(\alpha\) generalizes it: \(\alpha = 0\) reproduces the naive estimator, \(\alpha = 1\) is Laplace, and larger values trade calibration for robustness on sparse counts. Smoothing is not optional for count-based features and harmless for continuous ones (where you are estimating a density, not a frequency).

What Gaussian NB’s boundary looks like

Worth deriving because it explains an empirical regularity. With per-class Gaussians in \(d\) dimensions,

\[ \log \Pr(x \mid c) = -\tfrac{d}{2}\log 2\pi - \tfrac{d}{2}\log \sigma_c^2 - \frac{(x - \mu_c)^\top(x-\mu_c)}{2\sigma_c^2} \]

Expand the quadratic: it contributes \(\tfrac{1}{2\sigma_c^2}x^\top x\), a term in \(x\) with no \(c\) in it, so it cancels across classes. What remains per class is \(-\tfrac{1}{\sigma_c^2}\mu_c^\top x\), plus constants. So the score is affine in \(x\):

\[ \log \Pr(x \mid c) = \underbrace{\left(-\frac{1}{2\sigma_c^2}\mu_c^\top x + \text{const}\right)}_{\text{linear in } x} - \underbrace{\frac{\mu_c^\top\mu_c}{2\sigma_c^2}}_{\text{independent of } x} \]

The boundary is therefore linear when all classes share one covariance, and becomes quadratic only when variances differ per class or per feature. This is exactly the shared-variance result from linear discriminant analysis — Gaussian NB with pooled variance is LDA, and you can read its coefficients directly off the fitted means. Worth knowing when choosing between them: same accuracy, LDA has no extra parameters.

Bernoulli NB for text

For binary term presence, the per-feature likelihood is over two outcomes:

\[ \Pr(x_j \mid c) = \theta_{jc}^{x_j}(1-\theta_{jc})^{1-x_j}, \qquad \theta_{jc} = \Pr(x_j = 1 \mid c) \]

This is the model behind most textbook spam filters, and its log form is still a sum over features, so the underflow fix applies unchanged. For count data use multinomial NB; for correlated indicators, complement naive Bayes (fitting on the absence of each class) is the classic, nearly free improvement — it corrects the double-counting bias by construction rather than by apology.

Pitfalls

QQuestionSelf-check

Starting from \(\Pr(A\mid B) = \Pr(A\cap B)/\Pr(B)\), derive Bayes’ theorem and justify deleting \(\Pr(x)\) from the posterior when taking an argmax. Two of your twelve features are near-duplicates of each other. Explain, in terms of the log-posterior, precisely how naive Bayes mishandles this and what the symptom looks like in predictions. Why is summing logs sufficient for ranking but not for reporting probabilities, and what extra step does reporting require?

ASolution

From \(\Pr(A\mid B) = \Pr(A\cap B)/\Pr(B)\) and the symmetric form \(\Pr(A\cap B) = \Pr(B\mid A)\Pr(A)\), divide by \(\Pr(B)\) to get \(\Pr(A\mid B) = \Pr(B\mid A)\Pr(A)/\Pr(B)\). In the posterior \(\Pr(c\mid x) = \Pr(x\mid c)\Pr(c)/\Pr(x)\), the term \(\Pr(x)\) is constant across the classes being compared, so multiplying every candidate by the same positive constant does not change which is largest — hence dropping it preserves the argmax, provided \(\Pr(x) > 0\) so the cancellation is legal. For the duplicated features, the log-posterior contains \(\log\Pr(x_1\mid c) + \log\Pr(x_2\mid c)\) as separate additive terms, but \(x_1\) and \(x_2\) are one measurement seen twice, so the evidence is counted twice: the class’s log-odds are inflated by roughly one copy of the shared feature’s log-likelihood ratio, which over-sharpens the posterior and can flip borderline cases toward whichever class the duplicated feature favours. Symptom: overconfident probabilities (values near 0 and 1 far more often than the data warrants) and a validation AUC that does not match what the training probabilities suggest. Summing logs is enough for ranking because \(\log\) is strictly monotone, so ordering log-posteriors is identical to ordering posteriors; reporting probabilities additionally requires exponentiation, which needs the log-sum-exp shift by the maximum to avoid overflow, and — more importantly — a calibrated model, since NB’s raw posteriors are miscalibrated and must go through a calibration map first.

Next: Deriving k-Means (ML #11) — an identity that turns clustering into a variance-decomposition problem, and a guarantee of convergence that is weaker than it looks.