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.
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}).
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):
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:
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}:
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.
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 classn_x = np.stack([X[Y == y].sum(axis=0) for y inrange(10)])P_y = n_y / n_y.sum() # prior p(y)P_xy = (n_x +1) / (n_y +2)[:, None] # smoothed theta_iyprint('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) >0print('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):
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:
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:
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:
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:
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
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 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
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?
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?
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:
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).
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.
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