Naive Bayes

Dive into Deep Learning · §36.11

Naive Bayes and Generative vs. Discriminative Classifiers
generative vs. discriminative · conditional independence · Laplace smoothing · log-odds linearity · calibration & overconfidence

10^236 Binary Images, Only 60,000 Training Examples

Motivation & Combinatorial Explosion

In earlier chapters, we trained softmax regression on Fashion-MNIST by running gradient descent directly on the conditional label probability p(y \mid \mathbf{x}) (7{,}850 parameters, \approx 83\% accuracy). What if we instead model how each garment class generates its images p(\mathbf{x} \mid y) and invert it via Bayes’ rule?

  • The combinatorial wall: Even if each of the d = 28 \times 28 = 784 pixels is simplified to a single binary bit x_i \in \{0, 1\} (inked or blank), there are 2^{784} \approx 10^{236} distinct binary images.
  • Unrestricted lookup tables are impossible: Specifying an arbitrary distribution p(\mathbf{x} \mid y) requires 2^{784} - 1 free probabilities per class, whereas our entire training set has only 60{,}000 images (6{,}000 per class).
  • The naive Bayes shortcut: Assume that once the class y is known, the d features are conditionally independent—reducing training to counting single-pixel frequencies and prediction to adding log-odds.

Bayes’ Rule: Generative vs. Discriminative Routes

Two Families of Classifiers

\hat{y} = \mathop{\mathrm{argmax}}_{y \in \{1,\dots,K\}} p(y \mid \mathbf{x}) = \mathop{\mathrm{argmax}}_{y} p(\mathbf{x} \mid y)\,p(y)

  • Generative route (Naive Bayes): Fit p(\mathbf{x} \mid y) and p(y) separately for each class, then invert via the Bayes numerator p(y)\prod_i p(x_i \mid y).
  • Discriminative route (Softmax regression): Skip modeling p(\mathbf{x} \mid y) and optimize the decision boundary p(y \mid \mathbf{x}) directly by conditional NLL.

The Naive Conditional Independence Assumption

Factorizing the Class-Conditional Density

  • Forgetting feature histories: Naive Bayes assumes that given the class y, knowing one feature x_i tells us nothing further about any other feature x_j: p(\mathbf{x} \mid y) = \prod_{i=1}^d p(x_i \mid y)
  • Exponential parameter reduction: For d = 784 binary features and K = 10 classes, 2^{784} - 1 parameters per class collapse to 784 Bernoulli frequencies \theta_{iy} = p(x_i = 1 \mid y) (each estimated to standard error \le \frac{0.5}{\sqrt{6000}} \approx 0.0065).
  • Joint vs. pairwise independence: Pairwise uncorrelated features do not imply joint conditional independence (e.g., if x_1, x_2 are fair bits and x_3 = x_1 \oplus x_2, every pair is independent yet p(1,1,1) = 0 \neq \frac{1}{8}).
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Worked Example: A Two-Word Spam Filter by Hand

Multiplicative Likelihood Ratios

\frac{p(\text{spam} \mid \mathbf{x})}{p(\text{ordinary} \mid \mathbf{x})} = \frac{0.4}{0.6} \times \frac{3/4}{1/6} \times \frac{1}{2/6} = \frac{2}{3} \times 4.5 \times 3 = 9

  • Multiplying evidence: Prior odds (2/3), presence of "free" (\times 4.5), and absence of "meeting" (\times 3.0) multiply to posterior odds 9:1 (P = 0.90).
  • Additive log-odds: In log space, multiplying likelihood ratios becomes adding log-odds (-0.41 + 1.50 + 1.10 = +2.20 nats).

Maximum Likelihood Counting and Zero-Count Vetoes

Laplace Add-One Smoothing

Under conditional independence, the training set log-likelihood decouples into an independent coin-flip log-likelihood for each class y and feature i (where n_y is the class count and n_{iy} is the active feature count in class y):

\log P(\mathcal{D} \mid \boldsymbol{\theta}) = \sum_{y=1}^K n_y \log p(y) + \sum_{y=1}^K \sum_{i=1}^d \Bigl[n_{iy}\log\theta_{iy} + (n_y - n_{iy})\log(1 - \theta_{iy})\Bigr]

  • Zero-count pathology of the raw MLE (\hat{\theta}_{iy} = n_{iy}/n_y): Whenever n_{iy} = 0 (such as "meeting" in our 4 training spam emails), \hat{\theta}_{iy} = 0 and any future test example with x_i = 1 receives a Bayes numerator of 0 for class y, so one feature vetoes the entire class.
  • Laplace smoothing (Beta posterior mean): Appending one imaginary positive example and one imaginary negative example yields the posterior mean under a uniform \mathrm{Beta}(1,1) prior: \hat{\theta}_{iy} = \frac{n_{iy} + 1}{n_y + 2} \in (0, 1) With smoothing, an email containing both "free" and "meeting" receives spam probability 0.32 instead of 0.

Preventing Floating-Point Underflow in Log Space

Additive Class Scores

Multiplying d = 784 pixel probabilities \prod_{i=1}^{784} p(x_i \mid y) directly in floating-point arithmetic fails catastrophically: if each factor is 1/2, their product is 2^{-784} \approx 10^{-236}, far below the float32 minimum positive subnormal (1.4 \times 10^{-45}). Taking the logarithm converts the product into the additive class score:

s_y(\mathbf{x}) = \log p(y) + \sum_{i=1}^d \log p(x_i \mid y), \qquad \hat{y} = \mathop{\mathrm{argmax}}_{y} s_y(\mathbf{x})

Inspecting the decimal exponents \log_{10} = s_y(\mathbf{x}) / \log 10 on the 10{,}000 Fashion-MNIST test images confirms why log space is mandatory:

log10 of the numerators: largest -32, smallest -1002, median best -81
images whose best numerator underflows float32: 0.96
numerators below the smallest normal float64: 0.44, images whose best one is: 0.0003
accuracy of the raw float64 product: 0.7058

Theorem: Bernoulli Naive Bayes Is a Linear Classifier

Log-Odds Weight Matrix and Offset

For binary features x_i \in \{0, 1\}, we can write \log p(x_i \mid y) = x_i \log\theta_{iy} + (1 - x_i)\log(1 - \theta_{iy}). Collecting terms that multiply x_i and terms independent of x_i reveals that every class score is an affine function of \mathbf{x}:

s_y(\mathbf{x}) = \mathbf{w}_y^\top \mathbf{x} + b_y, \qquad w_{iy} = \log\frac{\theta_{iy}}{1 - \theta_{iy}}, \qquad b_y = \log p(y) + \sum_{i=1}^d \log(1 - \theta_{iy})

  • Identical architecture to softmax regression: Bernoulli naive Bayes stores a 10 \times 784 weight matrix \mathbf{W} (where w_{iy} is the log-odds that pixel i is inked in class y) and a 10-element bias vector \mathbf{b} (where b_y is the log-score of an all-blank image).
  • Binary equivalence to logistic regression: For K = 2 classes, p(y = 1 \mid \mathbf{x}) = \operatorname{sigmoid}\bigl((\mathbf{w}_1 - \mathbf{w}_0)^\top \mathbf{x} + b_1 - b_0\bigr).
  • Gaussian naive Bayes boundaries: For continuous x_i \mid y \sim \mathcal{N}(\mu_{iy}, \sigma_{iy}^2), shared variances (\sigma_{iy}^2 = \sigma_i^2) cancel the quadratic x_i^2 terms to produce a linear boundary, whereas class-specific variances yield a diagonal quadratic boundary without cross terms x_i x_j.

Geometry of Generative vs. Discriminative Hyperplanes

Why Correlated Features Tilt the Boundary

  • Same linear hypothesis class, different fits: Why do two linear classifiers in the exact same model family achieve different error rates?
  • Naive generative fit (left, 19\% error): When features x_1, x_2 are correlated within each class, the true clouds tilt diagonally. Gaussian naive Bayes fits axis-aligned ellipses (\operatorname{Cov} = \operatorname{diag}), and inverting those misspecified ellipses via Bayes’ rule places the hyperplane at the wrong angle.
  • Direct discriminative fit (right, 7\% error): Fitting p(y \mid \mathbf{x}) directly aligns the hyperplane with the correlation tilt, achieving the Bayes-optimal error rate.
image/svg+xml Matplotlib v3.11.2, https://matplotlib.org/

Training Naive Bayes on Fashion-MNIST in Four Lines

Single-Pass Counting in Code

After binarizing Fashion-MNIST (x_i = 1 wherever grayscale intensity > 0, giving an overall ink fraction of 0.50), fitting all 7{,}850 parameters requires a single counting pass with zero gradient steps:

n_y = np.bincount(Y, minlength=10)              # images per class
n_x = np.stack([X[Y == y].sum(axis=0) for y in range(10)])
P_y = n_y / n_y.sum()                           # prior p(y)
P_xy = (n_x + 1) / (n_y + 2)[:, None]           # smoothed theta_iy
print('prior:', P_y)
print('never-inked pixels per class:', (n_x == 0).sum(axis=1))
unseen = (X_test * (n_x[Y_test] == 0)).sum(axis=1) > 0
print('test images inking one of their class:', unseen.sum())
prior: [0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1 0.1]
never-inked pixels per class: [ 0 13  1  0  3  3  0 57  0  1]
test images inking one of their class: 5
  • Why Laplace smoothing is non-negotiable: Sneakers never ink 57 pixels near the top of the frame during training, and 5 test images ink a pixel their true class never inked in 6{,}000 training examples—without the +1 / +2 pseudo-counts, all 5 would receive score -\infty for their true class.

Learned Class Templates vs. Generated Pixel Samples

What the Generative Model Remembers and Forgets

Per-Pixel Class Templates (\hat{\theta}_{iy})

Independent Pixel-Coin Samples

  • Templates reflect data marginals: Each template on the left is the exact per-pixel average of 6{,}000 training images; any model matching the data marginals has the exact same templates.
  • Samples expose the independence fallacy: Flipping 784 independent coins with probabilities \hat{\theta}_{iy} (right) produces speckled, ragged edges because neighboring boundary pixels do not coordinate.

Quantifying the Independence Failure on Real Garments

Row Transitions and Pairwise Hem Correlations

We can measure the failure of conditional independence both globally (by counting ink-to-background switches along each horizontal scanline) and locally (on two adjacent pixels at row 26, columns 14 and 15 along the bottom hem of pullovers):

ink fraction: data 0.498, samples 0.498
switches per row, data:    [3.8 3.2 3.1 3.1 3.1 3.  3.3 1.5 3.1 2.6]
switches per row, samples: [5.1 4.1 4.8 4.7 4.8 8.2 5.3 4.  8.2 5.9]
data : P(i)=0.55  P(j)=0.55  P(i)P(j)=0.30  P(i,j)=0.54
model: P(i)=0.54  P(j)=0.55  P(i)P(j)=0.30  P(i,j)=0.31
  • Nearly one feature recorded twice: Each hem pixel is inked in 55\% of pullovers. Independence predicts both are inked together in 0.55^2 = 30\% of pullovers, whereas in the real data both are inked together in 54\% of pullovers.

Vectorized Inference and Bootstrap Error Bars

70.6% +/- 0.9% Test Accuracy

Using the affine form s_y(\mathbf{x}) = \mathbf{w}_y^\top \mathbf{x} + b_y, a single matrix multiplication X_test @ W.T + b classifies all 10{,}000 test images, and 1{,}000 bootstrap resamples verify the binomial standard error:

test accuracy 0.7059, training accuracy 0.7171
accuracy 0.7059, bootstrap 95% interval (0.698, 0.715)
binomial half-width 1.96 se = 0.0089
  • High bias, near-zero overfitting gap: Training accuracy (71.6\%) sits only 1.0 percentage point above test accuracy (70.6\% \pm 0.9\%). Collecting more training data cannot fix the remaining 29\% error—the bottleneck is the bias of the independence assumption.

Head-to-Head: Naive Bayes vs. Softmax Regression

Same Linear Family, Different Objective

Is 71\% the best any linear hyperplane classifier can do on binarized 28 \times 28 pixels? Training softmax regression on the exact same binary vectors \mathbf{X} by minimizing cross-entropy -\sum_i \log p(y_i \mid \mathbf{x}_i) settles the question:

accuracy: softmax regression 0.830, naive Bayes 0.706
pullover<->coat errors: softmax regression 312 naive Bayes 614
  • A 12 percentage-point jump within the same model family: Softmax regression reaches about 83\% accuracy and cuts pullover\leftrightarrowcoat confusions roughly in half (about 300 vs 614) because discriminative gradient descent adjusts weights jointly to avoid double-counting correlated pixel patches.

Analyzing the Confusion Matrix across Garment Groups

Where Counting Struggles Most

Extracting the six largest off-diagonal entries of the 10 \times 10 confusion matrix N_{ij} (where column j is the true class and row i is the predicted class) pinpoints where naive Bayes loses those 12 points:

coat->pullover 372, pullover->coat 242, sandal->sneaker 232
shirt->pullover 232, shirt->coat 222, shirt->T-shirt 218
per-class accuracy: [0.75 0.91 0.66 0.81 0.48 0.68 0.17 0.89 0.83 0.88]
  • Two major confusion clusters: The four long-sleeved/upper-body garments (coat, pullover, shirt, t-shirt) and the three footwear classes (sandal, sneaker, ankle boot) account for the vast majority of mistakes, with shirts recognized only 17\% of the time.
  • Distinct silhouettes remain easy: Classes with unique spatial footprints, such as trousers (91\%) and sneakers (89\%), are separated cleanly even by independent pixel counts.

Visualizing the Log-Odds Discriminant Weights

Interpreting w_pullover - w_coat

  • Linear log-odds difference (\mathbf{w}_{\text{pullover}} - \mathbf{w}_{\text{coat}}): When pixel i is inked (x_i = 1) rather than blank (x_i = 0), it shifts the log-odds between pullover and coat by w_{i,\text{pullover}} - w_{i,\text{coat}} nats.
  • Why the blue torso (-1 nat) does not vote for coat when inked: Torso pixels are inked in \approx 99.0\% of pullovers and \approx 99.6\% of coats, so seeing an inked torso pixel shifts the log-ratio by \log\frac{0.990}{0.996} \approx -0.006 nats. The -1 nat weight comes from -\log\frac{1-0.990}{1-0.996}: it is the penalty when a torso pixel is left blank.
  • Decisions happen along the red sides: Outer sleeve and shoulder pixels drive the actual separation on inked garments.

largest |weight| 3.1 nats at row 0, column 1: inked in 21 pullovers and 0 coats

Calibration Audit: 99.2% Confidence vs. 70.6% Accuracy

Expected Calibration Error (ECE)

Exponentiating and normalizing the class scores recovers the model’s posterior probabilities p(y \mid \mathbf{x}) = \frac{\exp s_y(\mathbf{x})}{\sum_{y'} \exp s_{y'}(\mathbf{x})}. Grouping the 10{,}000 test predictions into confidence bins exposes severe overconfidence:

mean confidence 0.992, accuracy 0.706
(0, 0.9]:   257 images, claimed 0.726, achieved 0.350
(0.9, 0.99]:   297 images, claimed 0.961, achieved 0.384
(0.99, 0.999]:   265 images, claimed 0.996, achieved 0.419
(0.999, 1]:  9181 images, claimed 1.000, achieved 0.735
ECE 0.29, median top-two score gap 61 nats

92% of test images claim \ge 99.9\% confidence (1.000): Across the test set, the median gap between the top two class scores is 60 nats (e^{-60} \approx 10^{-26}), producing an Expected Calibration Error of \mathrm{ECE} = 0.29 (compared with < 0.03 for softmax regression).

Why Correlated Features Cause Extreme Overconfidence

The Duplicated-Evidence Theorem

\log\frac{p_{\mathrm{NB}}(y=1 \mid \mathbf{x})}{p_{\mathrm{NB}}(y=0 \mid \mathbf{x})} = \log\frac{\pi_1}{\pi_0} + k\log r(x)

  • Duplication multiplies log-odds by k: When a clue with likelihood ratio r = 4 (80\% true accuracy) is copied k = 5 times, naive Bayes reports odds 4^5 = 1024 (99.9\% confidence).
  • Repair: Temperature scaling s_y(\mathbf{x})/T with T = k restores calibrated log-odds without altering class rankings under equal priors.

Post-Hoc Repair: Temperature Scaling and Label Shift

Fixing Probabilities Without Retraining

Two operational adjustments repair naive Bayes probabilities at test time without touching the 7{,}840 learned pixel frequencies \hat{\theta}_{iy}:

  • 1. Temperature Scaling (p_T(y \mid \mathbf{x}) = \operatorname{softmax}\bigl(s_y(\mathbf{x})/T\bigr)): Dividing every class score by a single scalar temperature T > 1 (fitted by minimizing NLL on a held-out validation split) shrinks the 60-nat score gaps back to calibrated log-odds without changing \operatorname{argmax}_y s_y(\mathbf{x}). For k duplicated features under equal priors, setting T = k recovers the exact posterior.
  • 2. Zero-Retraining Label-Shift Adaptation: If the deployment class prior p_T(y) differs from the training prior p_S(y) while p(\mathbf{x} \mid y) remains fixed (label shift), a generative classifier updates its offset in one line: s_y^{\mathrm{target}}(\mathbf{x}) = s_y^{\mathrm{source}}(\mathbf{x}) + \log\frac{p_T(y)}{p_S(y)} (Note that temperature scaling must be applied before adding the prior shift so the 60-nat feature sum does not drown out a 2.2-nat prior shift.)

Where Generative Classifiers Win: Missing Features

Exact Analytical Marginalization

p(\mathbf{x}_{\mathcal{V}} \mid y) = \Biggl[\prod_{i \in \mathcal{V}} p(x_i \mid y)\Biggr] \prod_{j \in \mathcal{U}} \underbrace{\sum_{x_j \in \{0,1\}} p(x_j \mid y)}_{=\,1} = \prod_{i \in \mathcal{V}} p(x_i \mid y)

  • Exact marginalization: Summing out occluded pixels j \in \mathcal{U} simply drops their factors from the score s_y(\mathbf{x}_{\mathcal{V}}) = \log p(y) + \sum_{i \in \mathcal{V}} \log p(x_i \mid y).
  • Zero-imputation pitfall: Setting x_j = 0 in \mathbf{w}_y^\top\mathbf{x} + b_y treats occluded pixels as observed blank background via b_y = \log p(y) + \sum_j \log(1-\theta_{jy}).

The Ng & Jordan (2002) Sample-Complexity Crossover

O(log d) vs. O(d) Learning Curves

  • Small n (naive Bayes can win): Because 1\text{D} pixel frequencies are decoupled, a union bound over 2d parameters needs only n = O(\log d) samples to reach its asymptotic floor (low variance, higher bias).
  • Large n (discriminative wins): Logistic/softmax regression fits d coupled weights and can need n = O(d) samples, but reaches a lower asymptotic error. On the full Fashion-MNIST training set: about 83\% vs. 71\% accuracy.
  • The curves are a schematic of the theorem. Whether and where they cross on Fashion-MNIST is left as an exercise.

Generative vs. Discriminative Classifiers Compared

Head-to-Head Synthesis

Dimension Bernoulli Naive Bayes (Generative) Logistic / Softmax Regression (Discriminative)
Probabilistic Objective Joint likelihood \prod_i p(\mathbf{x}_i \mid y_i)\,p(y_i) Conditional likelihood \prod_i p(y_i \mid \mathbf{x}_i)
Decision Score s_y(\mathbf{x}) Affine \mathbf{w}_y^\top \mathbf{x} + b_y (w_{iy} = \log\frac{\theta_{iy}}{1-\theta_{iy}}) Affine \mathbf{w}_y^\top \mathbf{x} + b_y (fitted directly by SGD)
Training Algorithm Single-pass closed-form counting (O(nd)) Iterative gradient optimization over epochs
Sample Complexity O(\log d) examples to reach asymptotic floor O(d) examples to reach asymptotic floor
Asymptotic Accuracy (n \gg d) Lower (70.6\% on Fashion-MNIST; high bias) Higher (\approx 83\% on Fashion-MNIST; low bias)
Probability Calibration Severely overconfident (\mathrm{ECE} = 0.29; double-counting) Well calibrated (\mathrm{ECE} < 0.03)
Missing Features at Test Time Exact closed-form marginalization (drop factors) No marginalization rule; requires imputation

Concept Check: Naive Bayes and Calibration

Check Your Understanding

  1. Can Bernoulli Naive Bayes learn XOR? Suppose y = x_1 \oplus x_2 on the four binary points (0,0), (0,1), (1,0), (1,1). Why can no choice of Bernoulli naive Bayes parameters \theta_{iy} \in (0, 1) classify all four points correctly?
  2. Duplicated clue against a strong prior: Two classes have prior odds \frac{\pi_1}{\pi_0} = \frac{1}{5}. A binary feature x=1 has likelihood ratio r = \frac{p(x=1\mid y=1)}{p(x=1\mid y=0)} = 4, and the pipeline duplicates x three times (k = 3). What class does the true posterior predict, and what class does naive Bayes predict?
  3. Why zero-filling is not marginalization: In the affine score s_y(\mathbf{x}) = \mathbf{w}_y^\top \mathbf{x} + b_y, why does setting an occluded pixel x_i = 0 fail to marginalize x_i out of p(\mathbf{x} \mid y)?

Concept Check: Naive Bayes and Calibration (cont.)

Check Your Understanding

Answers:

  1. Bernoulli naive Bayes produces an affine log-odds score (\mathbf{w}_1 - \mathbf{w}_0)^\top \mathbf{x} + (b_1 - b_0), whose decision boundary is a single straight hyperplane, whereas XOR is not linearly separable (and in fact each marginal frequency \hat{\theta}_{iy} = 1/2, making every weight w_{iy} = \log 1 = 0).
  2. The true posterior odds are \frac{1}{5} \times 4 = \frac{4}{5} < 1, predicting class 0 (p(y=1\mid x=1) = 4/9 \approx 44\%). Naive Bayes computes odds \frac{1}{5} \times 4^3 = \frac{64}{5} = 12.8 > 1, flipping the prediction to class 1 with 92.8\% claimed confidence.
  3. Because b_y = \log p(y) + \sum_{j=1}^d \log(1 - \theta_{jy}) already includes \log(1 - \theta_{iy}) for every pixel, setting x_i = 0 scores pixel i as observed blank background (p(x_i=0\mid y) = 1-\theta_{iy}) rather than dropping pixel i’s factor (1).

Summary: Naive Bayes and Generative Classification

Key Takeaways

Concept Mathematical Form Statistical & Deep Learning Role
Generative Bayes Rule \hat{y} = \operatorname{argmax}_y p(\mathbf{x} \mid y)\,p(y) Inverts a class-conditional data model into a classifier
Naive Factorization p(\mathbf{x} \mid y) = \prod_{i=1}^d p(x_i \mid y) Collapses 2^d - 1 table entries per class to d independent marginals
Laplace Smoothing \hat{\theta}_{iy} = \frac{n_{iy} + 1}{n_y + 2} (\mathrm{Beta}(1,1) mean) Prevents unseen feature-class combinations (n_{iy} = 0) from vetoing class y
Log-Odds Affine Score s_y(\mathbf{x}) = \mathbf{w}_y^\top \mathbf{x} + b_y, w_{iy} = \log\frac{\theta_{iy}}{1-\theta_{iy}} Proves Bernoulli naive Bayes is a linear classifier in the softmax family
Duplicated-Evidence Bias \log\text{odds}_{\mathrm{NB}} = \log\frac{\pi_1}{\pi_0} + k\log r(x) Correlated features multiply log-odds, inflating confidence (\mathrm{ECE} = 0.29)
Ng–Jordan Trade-Off Naive Bayes: O(\log d) samples; Logistic: O(d) Generative counting converges faster at small n; discriminative SGD wins at large n