Naive Bayes
Generative classification via the conditional-independence factorization — the Bayes-optimal classifier and its plug-in approximation, three classical variants (Gaussian, Multinomial, Bernoulli), Laplace smoothing as conjugate Bayesian update, the Ng–Jordan discriminative-vs-generative asymptotics that explain why naive Bayes wins at small n, calibration repair via Platt and isotonic, and structured extensions (TAN, AODE) that relax the independence assumption.
§1. From features to a class label: the generative recipe
§1.1 A spam-filter vignette
Suppose we receive an email whose body, after tokenization, reduces to the bag . Is it spam? A reasonable answer needs three ingredients: the prior probability that any email is spam ; the generative description of what tokens spam emails tend to contain ; the same for ham . Bayes’ rule assembles them into the posterior we actually want:
The decision rule that minimizes the expected number of misclassifications (we’ll see in §3 that this is the 0/1-loss-optimal rule) is just predict the class with the larger posterior. Bayes’ rule is the entire framework. The “naive” in naive Bayes refers to a structural assumption about the likelihood that makes the right-hand side estimable from data; before we get there, let’s see why it’s needed.
§1.2 Bayes’ rule for classification
Fix a finite label set . Given an observation (continuous, discrete, or mixed), Bayes’ rule writes the posterior in terms of the prior and the class-conditional likelihood:
where and the denominator is the marginal-evidence normalization. The proportionality is the form we’ll use everywhere — the denominator is the same across and drops out of any argmax.
Decision rule (Bayes classifier under 0/1 loss; see §3.1 for the derivation). Predict .
This is the cleanest classifier in all of statistics. The only obstacle is that we don’t know and from data — we have to estimate them. Estimating is easy (count class labels). Estimating is, in general, very hard, which brings us to the next subsection.
§1.3 Why is intractable in high dimensions
Suppose every feature is binary () and there are of them. A full joint distribution over given has free parameters per class. At — a tiny problem by modern standards — that’s already over parameters per class. Even with training examples, only a vanishing fraction of the joint configurations are ever observed; the empirical estimate of is zero almost everywhere.
The same issue afflicts continuous features. Estimating a -dimensional density nonparametrically — by KDE, say — requires sample size to keep variance under control, where is the bandwidth. The curse-of-dimensionality rate from kernel-regression §6 applies here too: density estimation is rate , which collapses to nothing past .
We need to break the high-dimensional density estimation problem into a sequence of tractable low-dimensional problems. The naive Bayes assumption is the simplest possible way to do this, and we’ll see in §3.4 / §8 / §10 that it’s also surprisingly effective for classification (not so much for calibrated probability estimation, but classification is what we asked for).
§1.4 The conditional-independence assumption
The naive Bayes assumption is that, given the class label, the features are independent:
Two things this is not. First, it’s not saying that the features are independent unconditionally — typically they aren’t, because they’re all driven by the class label. Second, it’s not saying that the features are actually conditionally independent in the data-generating distribution; in real applications they almost never are. The assumption is a modeling choice. We’re going to plug a structured, easy-to-estimate factorized likelihood into Bayes’ rule and see what happens.
The estimation problem now decomposes: instead of one -dimensional density per class, we have one-dimensional densities per class. For continuous features under a Gaussian per-coordinate model that’s parameters per class (mean and variance); for binary features under a Bernoulli per-coordinate model it’s parameters per class (rates). Total parameter count grows linearly in rather than exponentially. This is the central trade — accept structural bias from the wrong-independence assumption in exchange for tractable estimation at high .
§1.5 Roadmap
The rest of the notebook answers four questions about this classifier.
What does it look like? §2 formalizes the product-factorization estimator and the argmax-of-log decision rule, shows the directed-graphical-model picture, and locates naive Bayes in the generative-vs-discriminative taxonomy.
Is it any good? §3 develops Bayes-optimal classifier theory — the 0/1-loss decomposition, the Bayes risk floor, the excess-risk bound for plug-in classifiers, and the preview of why NB ranks classes well even when it calibrates poorly.
How do we fit it? §§4–5 work out MLE for three classical variants (Gaussian, Multinomial, Bernoulli) and the implementation tricks (log-sum-exp, var-smoothing, sparse-matrix multiplication). §6 adds Laplace smoothing as a Bayesian conjugate update.
When is it the right tool? §7 is the Ng–Jordan (2002) discriminative-vs-generative asymptotic comparison — the headline theoretical result on when NB wins (small ) and when logistic regression wins (large ). §8 covers calibration repair. §9 covers structure-learning extensions (TAN, AODE) that relax the strict-independence assumption. §10 closes with text-classification applications and forward pointers.
§2. The naive Bayes classifier
§2.1 The product factorization and the decision rule
Plugging the naive-Bayes factorization into the proportional Bayes rule from §1.2:
The decision rule predicts . We almost never compute the product directly — products of many small numbers underflow float64 quickly (already at for typical token-probability scales). We work in log-space throughout:
For probabilities (rather than just class labels) we use the log-sum-exp identity:
where and . The numerically-safe LSE subtracts the max first: .
§2.2 The naive Bayes classifier as a log-linear model
Substitute exponential-family per-feature likelihoods into the log-posterior:
The terms not depending on drop in the argmax. What remains is linear in the sufficient statistics with class-dependent weights . Naive Bayes is a log-linear classifier in the sufficient-statistic representation. This is the formal sense in which Gaussian NB shares a decision-rule family with linear discriminant analysis (LDA), and Multinomial NB shares one with multiclass logistic regression. The Ng–Jordan §7 comparison is meaningful precisely because the two classifiers occupy the same hypothesis class — the difference is in how the parameters are estimated, not in what functions the classifier can express.
§2.3 The naive Bayes directed graphical model
Naive Bayes corresponds to a particular directed acyclic graph (DAG): the label node is the parent of every feature node , and there are no edges between the features.
Y
/ | \
/ | \
X_1 X_2 ... X_d
The joint factorizes as , which is exactly the naive-Bayes assumption. The graph encodes a set of conditional independence statements: for all . (Unconditionally, the features are typically not independent — knowing tells you something about , which tells you something about .)
This graphical view makes the §9 extensions natural: relax the independence by adding edges between the . A tree over the features (with still the universal parent) is the Tree-Augmented Naive Bayes (TAN, Friedman–Geiger–Goldszmidt 1997). A complete graph would recover the full joint and lose the tractability gain.
§2.4 Generative vs discriminative
Naive Bayes is a generative model: it estimates the joint distribution and derives the conditional via Bayes’ rule. The competing approach — used by logistic regression, support vector machines, neural networks — is discriminative: estimate directly, never modeling at all.
Why does the distinction matter?
- Sample complexity. Generative models have more parameters to fit (they model too), so they typically need more data to reach their asymptotic accuracy if no shortcut is used. Naive Bayes is the shortcut: factorize the joint, restrict to parameters, get the small- advantage. §7 develops this carefully (Ng–Jordan 2002).
- Asymptotic bias. Discriminative methods are asymptotically optimal for prediction under the class of conditional models they can express. Generative methods may have lower asymptotic accuracy if the joint model is misspecified — but naive Bayes’ joint model is always misspecified on real data, so this asymptotic gap is the price of the small- advantage.
- What you get for free. Generative models give you as a byproduct — useful for anomaly detection, missing-feature imputation, and synthetic-example generation. Discriminative models don’t, by design.
The takeaway: NB and logistic regression occupy the same hypothesis class but estimate the parameters differently, and that difference produces the small- vs large- trade we’ll see in §7.
§3. Bayes-optimal classifier theory
§3.1 The 0/1-loss decomposition
For a classifier trained on data and evaluated on a fresh pair from the true joint distribution, the 0/1 risk is
The Bayes classifier minimizes this risk:
Theorem (Bayes-classifier optimality). for every measurable .
Proof.
Fix . Then . This sum picks out the single term — the prior-times-likelihood of the class named. The maximum over is therefore , attained by . Taking expectations over preserves the inequality.
∎The Bayes risk (or Bayes error rate, irreducible error) is
Any classifier — naive Bayes, logistic regression, the latest deep net — is at best . The gap is irreducible: it’s the inherent randomness in given , which no amount of data or model complexity can erase.
§3.2 The Bayes risk floor — what no classifier can beat
Let be the true posterior in a two-class problem. Then . The minimum picks the smaller of the two posterior probabilities — exactly the per-point misclassification rate of the Bayes classifier. When for all — labels are deterministic functions of features — the Bayes risk is zero. When — the label is independent of the features — the Bayes risk is .
Two facts to internalize. (1) Bayes risk is a property of the data distribution, not of any classifier. It quantifies how much information the features carry about the label. (2) It’s the right benchmark. Reporting “our classifier achieves 5% error” is uninformative without context; reporting “Bayes risk is 2%; our classifier achieves 5%, leaving 3% excess risk” tells you how much room there is to improve.
For naive Bayes specifically, the plug-in classifier approaches some asymptotic limit as , but it’s not generally because is biased (the factorization is wrong). The asymptotic NB-risk gap above Bayes risk is the bias term; the finite- gap above the asymptotic NB-risk is the variance term. §7 makes both terms precise for the Ng–Jordan setup.
§3.3 Plug-in classifiers and the excess-risk bound
The plug-in approach builds a classifier by estimating the posterior and thresholding at :
Naive Bayes, logistic regression, kernel-density-based classifiers — all are plug-in classifiers with different choices for .
Theorem (Devroye–Györfi–Lugosi 1996, Theorem 2.2; binary case). For any plug-in classifier,
Proof sketch. Condition on . The Bayes classifier misclassifies with probability . The plug-in classifier misclassifies with probability that equals the Bayes classifier’s unless and lie on opposite sides of . In that case, the excess is , which is bounded by . Taking expectations over gives the result. The factor of 2 is loose for most distributions but tight in the worst case.
The takeaway: excess risk is bounded by twice the error in posterior estimation. A classifier whose is uniformly within of has excess risk at most . Conversely, the only thing that matters for classification is getting the sign of right at each ; absolute calibration is secondary. This is the formal version of the Domingos–Pazzani thesis we’ll meet in §3.4 and develop fully in §8: a classifier can rank classes well without estimating posterior probabilities well.
§3.4 Why NB ranks well but calibrates poorly (preview)
Naive Bayes’ estimated posterior is systematically miscalibrated whenever the conditional-independence assumption is wrong. The intuition (formalized in §8.1): when features are positively correlated given the class, the product likelihood multiplies redundant evidence as if it were independent, amplifying the log-likelihood and pushing the posterior toward 0 or 1.
So is typically much closer to 0 or 1 than the true — that’s the “overconfidence” failure mode. But the sign of often matches the sign of . The plug-in classifier flips only when both posteriors lie strictly on the same side of but in different positions; the sign-match is robust to monotone-distorted probability estimates. This is why a model with terrible calibration can still classify almost as well as the Bayes classifier — Domingos and Pazzani (1997) prove this rigorously for an interesting class of misspecified naive-Bayes models, and we’ll re-derive their result in §8.1.
§4. Gaussian Naive Bayes
§4.1 The per-class Gaussian conditional-density assumption
For continuous features , the simplest naive-Bayes likelihood is per-class, per-coordinate Gaussian:
Combined with the independence factorization, the multivariate likelihood is
This is a multivariate Gaussian with diagonal covariance — features uncorrelated within each class. Per-class means may differ; per-class variance vectors may differ. Parameter count: , including the priors. Linear in , as advertised.
§4.2 MLE for , , and
Given iid pairs , the joint log-likelihood is
The two terms decouple — the priors depend only on the class labels, and the per-feature Gaussian parameters depend only on the corresponding feature values within each class. Set for the per-class counts. Maximizing each term separately:
Derivation of . The relevant piece of involving is . Differentiating with respect to and setting to zero: , which gives the sample mean. The same one-variable Gaussian-MLE argument as in formalstatistics’s maximum-likelihood topic.
Derivation of . The relevant piece is . Differentiating with respect to : , which gives the sample variance with denominator (the MLE; the unbiased estimator uses ).
Var-smoothing safeguard. Because can vanish if all in-class observations are identical, scikit-learn’s GaussianNB adds a small additive term to every variance estimate, with default . This avoids divide-by-zero in the log-density and is essentially harmless in practice.
§4.3 The decision boundary is a quadric
The Gaussian-NB log-posterior ratio between two classes and is
The right-hand side is a quadratic polynomial in (the squares expand into terms with class-dependent coefficients). Setting it to zero gives the decision boundary, which is therefore a quadric — generally an ellipse, hyperbola, or parabola in 2D; the multivariate version is a quadric hypersurface.
A useful special case: when the per-class variance vectors are equal ( across ), the terms cancel and the decision boundary becomes linear. This reduces GNB to a special case of LDA — diagonal LDA — and shows that the diagonal-covariance structure is the source of the quadric (not the per-class differences in ).
§4.4 LDA / QDA / GNB — three corners of one design space
| Model | Covariance structure | Free params per class | Decision boundary |
|---|---|---|---|
| LDA | Shared across classes | (mean only) | Linear |
| GNB | Per-class diagonal | Quadric | |
| QDA | Per-class general | Quadric |
All three model the within-class density as Gaussian. They differ in how much covariance structure they’re willing to estimate from data:
- LDA estimates one matrix shared across classes; ignores per-class anisotropy entirely but pools data efficiently. Best when classes have similar shapes and class separation is mainly in the mean.
- QDA estimates a separate matrix per class; captures the most structure but burns the most parameters. Best when classes differ in shape and enough data is available to fit matrices.
- GNB estimates one diagonal matrix per class; allows per-class shapes but ignores correlation between features within each class. Always wrong on real data (features are usually correlated), but cheap to fit and surprisingly competitive at small — the §7 Ng–Jordan story.
In an even more degenerate corner: diagonal LDA shares a single diagonal covariance across all classes — most heavily restricted of all, linear decision boundary, often the strongest small- baseline for high-dimensional classification.
§4.5 Implementation: scikit-learn GaussianNB and var-smoothing
A few practical notes:
var_smoothingparameter. Default . Adds to every variance estimate. Increase to if predictions are unstable (zero-variance features), tune via cross-validation if necessary.- Numerical safety. Use
scipy.special.logsumexpfor posterior normalization, nevernp.log(np.sum(np.exp(...))). - Partial fit.
GaussianNB.partial_fitsupports online learning via Welford’s running-mean / running-variance update — useful for streaming data where the entire training set doesn’t fit in memory. - Multi-class. All MLE formulas apply with — the only change is that the prediction is a -way argmax over log-posteriors.
- Inverse-Wishart prior. A full Bayesian GNB would place an inverse-Wishart prior on each vector. The posterior-mean variance is then for a particular hyperparameter — equivalent to var-smoothing for an appropriate choice. (We’ll see the analogous conjugate-update story for categorical features in §6, where the calculation is cleaner.)
§5. Multinomial and Bernoulli Naive Bayes
§5.1 Multinomial NB: the bag-of-words generative story
For text classification, the canonical feature representation is the bag of words: count how many times each vocabulary token appears in a document, ignoring word order. A document is a vector where is the vocabulary size and is the count of token .
Generative model. Given a class label , generate the document by repeatedly sampling tokens from a categorical distribution with class-specific probabilities where . If the document has total length :
The multinomial coefficient doesn’t depend on — drops out of any argmax — so the relevant log-likelihood is
This is linear in the feature vector with class-dependent weights . The full log-posterior is the dot-product form a discriminative linear classifier would use; the difference is in how is estimated.
The “naive” assumption here is the within-class part: tokens within a single document are assumed iid from , ignoring the fact that real text has strong sequential and topic-coherence dependencies. McCallum and Nigam (1998) is the canonical reference for the Multinomial vs Bernoulli choice — the latter is the next subsection.
§5.2 MLE for token probabilities and the zero-count crisis
The MLE for is the empirical token frequency within class :
where is the total count of token in class training documents and . Derivation: maximize subject to via a Lagrange multiplier . First-order conditions: for all , so and normalization gives the above.
The zero-count crisis. Suppose token never appears in any class- training document, so and . Now a test document containing token has — class is categorically ruled out, even if the test document overwhelmingly looks like a class- document otherwise. This is the zero-frequency problem (Lewis 1998), and it makes raw MLE multinomial NB unusable in practice. The fix is Laplace smoothing — replace counts with for some — which we’ll derive as a conjugate-Bayesian update in §6.
| pitcher | inning | hit | team | season | patient | doctor | drug | health | clinic | |
|---|---|---|---|---|---|---|---|---|---|---|
| baseball | ||||||||||
| medicine |
- baseball: pitcher, hit, inning, team, season
- medicine: drug, patient, clinic, doctor, health
§5.3 Bernoulli NB: binary-feature variant for short documents
When documents are short (single sentences, social-media posts) or the question is presence/absence rather than count, Bernoulli NB is a more natural model:
- Features are binary: — token either appears in the document or not.
- Per-class likelihood is a product of Bernoullis: .
- Importantly, the absence of a token is informative — the factor explicitly penalizes class when a token typical of class is missing. Multinomial NB, by contrast, simply gives that factor a probability of 1 (the token contributes nothing if its count is 0).
MLE: . Same zero-count crisis when a token never appears in some class; same Laplace smoothing fix.
When does Bernoulli win? Short documents (one or two sentences) where token presence is more informative than token count; very small vocabularies where the multinomial-coefficient correction matters less; situations where a token’s absence is diagnostically important (negation, missing keyword). McCallum and Nigam (1998) report Bernoulli NB winning on small-vocabulary subsets and Multinomial winning on full-vocabulary, longer-document benchmarks.
§5.4 Complement Naive Bayes (Rennie et al. 2003)
Rennie, Shih, Teevan, and Karger (2003) identified a systematic flaw in vanilla Multinomial NB: when class proportions are very unequal, the larger-class likelihood estimates dominate the smaller-class estimates simply because more counts are aggregated. They proposed Complement Naive Bayes, which estimates from the complement of class — all documents not belonging to class — and inverts the decision rule:
The argmin (rather than argmax) implements “the class least like the data” — flipping the standard rule. Rennie et al. also add log-count weighting (log(1 + x_j) instead of raw counts) and per-document length normalization. These TF-IDF-like preprocessing steps improve Multinomial NB even without the complement trick.
Scikit-learn implements both: MultinomialNB(alpha=1.0) and ComplementNB(alpha=1.0, norm=True). The complement variant is the recommended default for text classification on imbalanced data.
§5.5 Implementation: log-sum-exp, sparse matrices, vectorized prediction
Text-classification matrices are very sparse — a vocabulary of 30,000 tokens with average document length 200 gives a density of . scikit-learn uses scipy.sparse.csr_matrix throughout, and the implementation of MultinomialNB.predict_log_proba is essentially one sparse matrix product:
log_posterior = X @ log_theta.T + log_class_priors
where log_theta is (K, V) and X is (n, V) sparse — total cost rather than . Normalization via log-sum-exp is then a single broadcast operation along the class axis.
The same trick works for Bernoulli NB; the only difference is that “presence” must be extracted from the count matrix first (X.binarize() in scikit-learn). Gaussian NB does not benefit from sparsity in the same way because the Gaussian log-density involves squared differences from the mean — a dense operation.
§6. Smoothing as conjugate Bayesian update
§6.1 Laplace add-one smoothing as a uniform Dirichlet prior
Recall the MLE zero-count crisis from §5.2: ruins the log-likelihood whenever an unseen token appears in a test document. The standard fix adds a fictitious pseudo-count to every cell:
When , this is Laplace add-one smoothing (Laplace 1812 — yes, that Laplace). When , Krichevsky–Trofimov smoothing. When , the smoothing is light; when , the estimate converges to the uniform regardless of data.
The Bayesian interpretation: is the posterior mean under a symmetric Dirichlet prior . We make this precise in the next subsection.
§6.2 The Dirichlet–multinomial conjugate pair
The Dirichlet distribution over the -simplex has density
Conjugacy theorem. If and , then .
Proof.
Bayes’ rule: the posterior density is proportional to (prior) × (likelihood),
∎which is the Dirichlet density up to a normalizing constant — i.e., . The multinomial coefficient depends only on , contributes to the normalizer but not the posterior shape.
Posterior mean. . Component-wise, .
Symmetric special case. With , the posterior mean is exactly the Laplace formula . The (uniform Dirichlet) corresponds to add-one smoothing; to Jeffreys’ prior (Krichevsky–Trofimov).
This is the cleanest way to think about smoothing. It’s not a heuristic regularizer — it’s the closed-form Bayesian posterior under a particular weakly-informative prior. The parameter controls how much weight to put on the prior vs the data, and the choice of (uniform) is the smallest amount of smoothing that still makes the estimator well-defined.
§6.3 Add- smoothing and cross-validation
In practice, is a hyperparameter and the right value depends on the dataset. Common heuristics:
- (Laplace add-one). The default in scikit-learn. Works well on medium-sized vocabularies where most tokens are observed in most classes.
- or (light smoothing). For very large vocabularies and rich training data — the prior should be down-weighted relative to the data.
- or higher (heavy smoothing). For very small training sets where the empirical token frequencies are noisy.
- Cross-validation. The principled choice. Tune on a held-out fold to minimize log-loss or maximize accuracy.
The §6 fixture below sweeps on the 20-Newsgroups subset and shows the test-accuracy plateau in the middle.
§6.4 Posterior-predictive vs MAP
For a fully Bayesian NB, predicting a new token given the training counts uses the posterior-predictive:
which is exactly the Laplace formula. For the Dirichlet–multinomial pair, the posterior-predictive equals the posterior mean. This is a happy coincidence of the conjugacy — it doesn’t hold in general (for Gaussian–Gaussian, the posterior-predictive has wider variance than a plug-in normal at the posterior mean).
So the Laplace-smoothed plug-in classifier we’ve been using is the proper Bayesian posterior-predictive classifier — no integration over needed. This is one reason naive Bayes with Laplace smoothing is so widely used: it’s both empirically simple and theoretically defensible.
MAP vs posterior-mean. The MAP estimator is — same as the posterior mean but with in the numerator (the additional comes from the Dirichlet density’s exponent). When , the MAP can be negative or undefined; the posterior mean is always well-defined and gives the more standard “add-” formula. We use posterior-mean throughout.
§6.5 Empirical Bayes choice of
When cross-validation is too expensive (very large datasets, online learning), one can choose by empirical Bayes — maximize the marginal likelihood over :
(closed form by Dirichlet–multinomial conjugacy). Maximize the log-marginal-likelihood numerically — it’s smooth and one-dimensional, so any scalar optimizer works. Minka (2000) gives fixed-point iteration formulas that are faster than gradient descent.
For typical text-classification problems, empirical Bayes and cross-validated agree to within a factor of 2 on the optimal value. The main reason to prefer cross-validation is that it directly targets the loss you care about (accuracy, log-loss), whereas empirical Bayes targets marginal likelihood — which is a sensible proxy but not identical.
§7. The discriminative-vs-generative asymptotics
§7.1 The Ng–Jordan (2002) setup
Ng and Jordan (2002) compare a generative classifier (Gaussian NB) with its discriminative counterpart (logistic regression) on a shared model class. The setup is essentially the cleanest possible:
- Two equiprobable classes , .
- Features with class-conditional Gaussian: , for some unit-norm . Identity covariance, equal magnitudes — both the generative model (GNB with shared diagonal ) and the discriminative model (logistic regression with linear decision boundary) are correctly specified.
- The Bayes-optimal classifier is the linear classifier .
GNB and logistic regression in this setup both converge to the Bayes-optimal classifier as . The interesting question is how fast.
The Ng–Jordan headline result: GNB converges at rate while logistic regression converges at rate . For excess error, that’s vs . At small and large , GNB wins by a substantial margin; at large , the discriminative classifier wins because it’s asymptotically optimal in a broader sense (correctly classifies even when the Gaussian-likelihood assumption fails).
§7.2 Logistic regression’s rate
Logistic regression maximizes the conditional log-likelihood:
where is the sigmoid. Standard MLE asymptotics: where is the Fisher information. For the Ng–Jordan setup, the Fisher information matrix is , which scales like at the truth. So , and the excess 0/1 risk is also to leading order (the constant depends on the marginal-density gap at the decision boundary).
Sample complexity: to reach excess error, logistic regression needs samples.
§7.3 Gaussian NB’s rate — the union-bound argument
Gaussian NB with shared diagonal covariance estimates the per-coordinate class means and a shared per-coordinate variance. Under the Ng–Jordan setup the variance is known to be 1, so the only parameters are and . The classifier output reduces to the sign of .
The estimate error decomposes per coordinate: is Gaussian with variance (since with high probability by Hoeffding). By a sub-Gaussian union bound, the max-coordinate error is
This instead of is what makes GNB’s rate dimension-light: errors at the coordinates are averaged (via the dot product in the decision rule), not summed in . By Cauchy–Schwarz and the union-bound max-coordinate control, the excess 0/1 risk is .
Sample complexity: to reach excess error, GNB needs samples.
Caveat — when this works and when it doesn’t. The Ng–Jordan rate assumes the GNB model is correctly specified (true class-conditional is Gaussian with the assumed covariance structure). On real data the assumption is wrong, and GNB inherits a model-misspecification bias term that does not vanish with . The rate refers only to the variance term; the asymptotic gap to the Bayes risk is the bias term. So at large , logistic regression beats GNB because the misspecification bias dominates the variance — that’s the “crossover.”
§7.4 The crossover phenomenon — empirical verification
We run the Ng–Jordan §3 simulation: vary from 20 to 5000, fix (a regime where is much smaller than ), and plot test error for Gaussian NB and unregularized logistic regression across 15 replicates per sample size. The two rates predict that GNB approaches its asymptotic error faster than logistic regression — its learning curve should be steeper at small-to-moderate while logistic regression catches up only once is large.
That’s what the empirical curve shows. Between and — the sweet spot where the rate is favorable but is still pessimistic — GNB pulls ahead by about five percentage points (test error ≈ 0.22 vs ≈ 0.27 at ). Both methods converge to the Bayes-error floor near once .
At very small (here to ), logistic regression edges out GNB by a thin margin. The theoretical asymptotics don’t pin down constants, and at sample sizes barely larger than the feature count, the precise behavior depends on which estimator’s per-coordinate variance bites first. The clean “NB wins at small ” story emerges most clearly at higher — toggle the viz to to see the small- GNB-wins region widen substantially, exactly as the rate inequality predicts.
§7.5 Caveats: misspecification, regularization, and “no free lunch”
Three caveats on the §7.4 verification.
Correct specification matters. The simulation is GNB-optimal: features are independent given the class, true covariance is . On real data the model is misspecified and GNB’s asymptotic bias may dominate the small- variance advantage entirely. The Ng–Jordan paper itself reports mixed results on UCI datasets — GNB sometimes wins, sometimes loses, with no clean rate-prediction.
Regularization changes the story. -regularized logistic regression effectively reduces via shrinkage, narrowing the gap to GNB at small . -regularized logistic (the lasso from high-dimensional-regression §11.1) is even more competitive: sample complexity becomes where is the true sparsity, matching GNB’s dimension-light rate when . So the §7.4 GNB-wins region narrows when both methods are tuned via cross-validation.
No free lunch. Generative classifiers win when their generative model is approximately right. When it’s badly wrong, they lose. There’s no universal classifier — the right answer depends on what you know about the data-generating process.
§8. Calibration and class-probability estimation
§8.1 Why naive Bayes is miscalibrated
A classifier is calibrated if, among the test examples for which it predicts , the fraction with is approximately . NB is rarely calibrated — its predicted probabilities cluster near 0 and 1 while the true posterior takes intermediate values for most inputs. The phenomenon is called overconfidence.
The mechanism (Domingos–Pazzani 1997): the conditional-independence assumption multiplies log-likelihoods that aren’t really independent, so correlated evidence is counted multiple times. Suppose two features are perfectly correlated within each class — the second feature carries no new information beyond the first — but NB treats them as independent. NB’s log-likelihood ratio includes the same evidence twice, doubling its magnitude. Posteriors are pushed twice as far from as they should be: a true posterior of becomes an NB-estimated posterior of .
But the sign of the log-likelihood ratio is preserved. Overconfidence doesn’t flip classifications; it just exaggerates them. That’s why NB classifies well (rank-preserving) but calibrates poorly (magnitude-distorted). Theorem 3 of Domingos and Pazzani (1997) makes this precise for a class of correlated-feature NB models.
§8.2 Platt scaling — fit a sigmoid on the scores
Platt (1999) proposed fitting a one-dimensional logistic regression on the raw classifier scores to recover calibration:
where is the raw classifier output (for NB, the log-posterior-odds), and are fit by MLE on a held-out calibration set (never the training set!). Two parameters only, so the fit is robust to small calibration sets.
When to use Platt scaling: classifier scores are already monotone in the true posterior (NB satisfies this in practice) and the transformation is approximately sigmoid-shaped. Works well for SVMs and naive Bayes in the “moderate-sample-but-overconfident” regime.
Critical detail. The held-out set must be separate from both training and final testing. Fitting Platt on the training set and evaluating on the same set produces in-sample-perfect calibration that’s meaningless out-of-sample. The recipe: split data 50/50 into train/calibration, fit the classifier on train, fit Platt on calibration. Re-split if data is precious.
§8.3 Isotonic regression — nonparametric monotone fit
Zadrozny and Elkan (2002) proposed isotonic regression as a nonparametric alternative to Platt scaling. The idea: fit a monotone-nondecreasing function that minimizes over .
Closed-form solution via the pool-adjacent-violators (PAV) algorithm: walk through the sorted-by-score data, replacing any violation with their average, repeat until monotone. time, no hyperparameters.
When isotonic wins over Platt: large held-out sets (PAV becomes a smooth nonparametric estimator), or when the score-to-posterior map is not approximately sigmoid. When Platt wins: small held-out sets (isotonic overfits the calibration set when is small).
The §8.3 fixture compares both on the 20-Newsgroups task — see the next code cell.
§8.4 Calibration metrics: Brier, log-loss, ECE
Three standard metrics for evaluating calibration quality.
Brier score. Mean squared error between predicted probability and binary label:
Decomposes (Murphy 1973) into reliability + resolution − uncertainty: low Brier requires both calibration and discrimination. Range , lower is better.
Log-loss (cross-entropy). . Strictly proper scoring rule — only minimized when exactly. Penalizes overconfident wrong predictions much more harshly than Brier (logarithmic vs quadratic blow-up near or ).
Expected Calibration Error (ECE). Bin predictions into bins, compare per-bin mean predicted probability to per-bin frequency of positives:
Hand-tunable via ; sensitive to binning strategy. Guo et al. (2017) recommend ECE for reporting calibration on classification tasks.
Which loss for which task? Use log-loss to train (it’s the proper-scoring-rule MLE); use Brier or ECE to report (more interpretable). For ranking-only tasks (search relevance, anomaly detection) where calibration doesn’t matter, AUC is the right metric instead.
§9. Beyond strict independence: structure-learning extensions
§9.1 Tree-Augmented Naive Bayes (TAN) via Chow–Liu
The simplest principled relaxation of the strict-independence assumption: allow each feature to have one additional parent in the DAG (besides ). The resulting graph is a tree over the features rooted at . The joint factorizes as
where is the feature-parent of (or for the tree root).
How do you pick the tree? Chow and Liu (1968) — twenty years before Friedman–Geiger–Goldszmidt 1997 brought it to classification — proved that the maximum-likelihood tree is the maximum-mutual-information spanning tree of the complete weighted graph on the features. Edge weights are conditional mutual informations , computed from the training data. Run Kruskal’s or Prim’s algorithm. to compute MIs, for the MST. Choose any feature as the root; the choice doesn’t affect classification accuracy (the joint factorization is the same).
Why TAN often beats NB. TAN captures the dominant feature dependencies (those with the largest pairwise MI), reducing the “double-counting redundant evidence” failure mode of strict NB. On most UCI benchmarks, TAN classifies better than NB and produces better-calibrated probabilities, at the cost of parameters (vs for NB).
§9.2 Averaged One-Dependence Estimators (AODE)
Webb, Boughton, and Wang (2005) proposed AODE as an ensemble alternative to TAN. Instead of picking one spanning tree, AODE averages over all classifiers that have each single feature as a “super-parent” (every other feature depends on and on ).
where (often 30) is a frequency threshold to avoid unreliable conditional estimates.
Advantages over TAN. No structure search (deterministic ensemble), more robust against any single dependency choice being wrong, often beats TAN on benchmarks. Disadvantage. Storage: parameters — substantial at large vocabulary. Suitable for moderate-feature-count tabular tasks; not ideal for text.
Other Bayesian-network extensions. Selective NB (Langley & Sage 1994) selects a feature subset before fitting. K-dependence Bayesian classifier (Sahami 1996) generalizes TAN to up to parents per feature. Hidden NB (Jiang–Zhang–Cai 2009) introduces a latent hidden parent. All sit on the spectrum between NB and the full joint, trading parameters for expressiveness.
§9.3 Hidden Naive Bayes
Jiang, Zhang, and Cai (2009) introduced Hidden Naive Bayes (HNB) as another structural extension: each feature depends on and on a hidden parent that is a weighted combination of all other features. The weights are computed from mutual information; the hidden-parent effect aggregates structure across all features rather than picking just one.
HNB’s joint is
where and is the normalized conditional mutual information .
Reported results: HNB beats NB and is competitive with TAN/AODE while being computationally cheaper than AODE (no count tables). Practical use is more limited than TAN, but for low-to-moderate dimensional tabular classification it’s another option.
§9.4 Connection to latent Dirichlet allocation
The Multinomial NB story — one per class, documents drawn from the corresponding multinomial — is a special case of Latent Dirichlet Allocation (LDA, Blei–Ng–Jordan 2003). LDA extends NB by allowing each document to be a mixture of class-like “topics” rather than belonging to a single class:
Each document has a topic distribution , each word in the document is drawn from a topic-specific vocabulary distribution . NB recovers as the special case where each document’s topic distribution is a one-hot vector (i.e., the class label).
Why this matters for NB. It positions NB as the simplest, most degenerate member of a much larger family of latent-variable text models — LDA, hierarchical Dirichlet processes, dynamic topic models. Each adds structural flexibility (mixed topics, topic-document correlations, time evolution) at the cost of harder inference (variational methods, MCMC). NB is the limit case where the latent variable degenerates to an observed class label and inference becomes one MLE.
§9.5 Naive Bayes in the broader graphical-models family
The structural progression — NB, TAN, AODE, full Bayesian network — sits at one end of a spectrum that the graphical-models topic on formalstatistics (when shipped) will treat in full generality:
- Naive Bayes = star graph rooted at (this topic, §1–§8).
- TAN = tree over features rooted at (this topic, §9.1).
- AODE = ensemble of star-graphs with each feature as a super-parent (this topic, §9.2).
- General Bayesian network classifier = arbitrary DAG with as a vertex.
- Latent Dirichlet allocation = NB lifted to mixture-of-multinomials with latent topics (§9.4).
- Markov random fields / conditional random fields = undirected analogs; CRF is the discriminative undirected counterpart to MRF.
Naive Bayes is the limit of simplicity on this spectrum. Many tasks that look like they need more structure turn out to be fine with NB; many that look amenable to NB turn out to need more structure. The diagnostic question is “do feature dependencies, after conditioning on , materially affect classification?” — if yes, move to TAN or beyond; if no, NB is plenty.
§10. Connections, applications, and limits
§10.1 Text classification as the canonical success story
Wang and Manning (2012) revisited naive Bayes vs SVMs vs logistic regression on a battery of text-classification tasks (sentiment, topic, news categorization). They found that a properly tuned Multinomial NB (with log-count features and bigram extension) is competitive with or beats much more complex methods on most benchmarks, especially with limited training data.
Their preferred variant — NB-SVM — combines NB log-likelihood-ratio features with an SVM linear classifier, getting the best of both: NB’s small- advantage and SVM’s large- asymptotic optimality. On 10 of 11 benchmark datasets, NB-SVM beats every published baseline through 2012 — including ones with elaborate feature engineering.
The Wang–Manning takeaway: for text classification, start with NB before reaching for anything more complex. It’s fast, it’s interpretable, it’s competitive, and any model you reach for next should beat NB on a held-out test set before being worth the additional complexity.
§10.2 The ranking-vs-calibration thesis
Domingos and Pazzani’s 1997 paper had a more general thesis than just “NB works on text” — they argued that classifiers that estimate posterior probabilities poorly can still rank classes correctly, and many real-world classification tasks need only the ranking. Hand (2006) develops this further: most “improvements” in classifier accuracy reported in the ML literature are within the noise of the within-classifier variance from random data splits.
For tasks where ranking is what matters (search relevance, anomaly scores, top-K prediction), NB is competitive with much more complex methods. For tasks where calibrated probabilities matter (medical risk scores, financial forecasts, downstream Bayesian updates), NB’s overconfidence is a real liability — fix it with Platt scaling or isotonic regression (§8), or use a discriminative method.
The §3.3 plug-in excess-risk bound formalizes this: classification accuracy is sensitive to the sign of at each , not to the magnitude. NB’s miscalibration mostly preserves signs (overconfidence in the same direction as truth), hence the ranking-vs-calibration separation.
§10.3 Where naive Bayes breaks down
Three failure modes worth flagging.
Strongly correlated features. Duplicate or near-duplicate features amplify NB’s overconfidence (§8.1) and can cause the sign of the log-likelihood ratio to be wrong, not just the magnitude. Mitigations: TAN/AODE structure (§9), feature selection (Yang–Pedersen 1997) to remove redundancy, or simply switch to logistic regression.
Calibrated-probability requirements. Medical risk scores, financial probabilities, anything fed into a downstream Bayesian update — NB’s raw probabilities are not trustworthy. Always Platt-scale or isotonic-regress on a held-out set, or use a discriminative method with proper-loss training (cross-entropy).
Long-range dependencies. Text classification with token-order-sensitive structure (sentiment of “not good”), images with spatial structure, time series — NB’s bag-of-features representation ignores order. Use sequence models (RNN, Transformer), structured-output models (CRF), or convolutional architectures instead. NB is for the bag-of-features regime; outside it, it’s not the right tool.
§10.4 Forward pointers in formalML
NB connects forward to several formalML topics.
conformal-prediction(T4) — NB is a natural base classifier for split-conformal classification. Compute raw NB class-probability scores, calibrate on a held-out set via quantile-thresholding, output a prediction set with marginal coverage. The §8 calibration framework developed here is what makes NB suitable: raw NB probabilities are too overconfident to be conformal scores directly, but Platt-scaled or isotonic-regressed scores work well. See conformal-prediction §3.6 for the implementation.bayesian-neural-networks(T5) — At the other end of the generative-classifier spectrum from NB. BNNs treat the network weights as random variables with priors; the classifier output is a posterior over class labels rather than a point estimate. NB is the simplest generative classifier (one weight per feature per class); BNNs are the most complex (millions of weights with Bayesian posteriors). The §7 generative-vs-discriminative trade-offs apply throughout.high-dimensional-regression(T2 sibling) — The §7 discriminative-vs-generative comparison maps onto §11.1’s logistic-lasso vs NB comparison. When sparsity is the dominant structure, sparse logistic regression beats NB. When the small- regime dominates, NB beats sparse logistic regression. The crossover depends on , , , and the true generative structure.prediction-intervals(T4) — Calibrated NB probabilities give natural Bayesian prediction intervals on the per-class probability scale. See prediction-intervals §4 for the construction.
§10.5 Closing thesis
Naive Bayes endures, despite being theoretically suspect, because it occupies a specific niche extremely well: the small-, large-, ranking-dominated regime. In that niche, the dimension-light sample complexity () dominates the misspecification bias, the ranking-preserving nature of overconfidence preserves classification quality, and the simple log-linear structure makes training and prediction fast enough to deploy at any scale.
Outside that niche — when is large enough for discriminative methods to converge, when calibrated probabilities are required for downstream decisions, when feature dependencies dominate the classification signal — naive Bayes is the wrong tool. But the right answer is rarely to ignore it. The Wang–Manning advice is reasonable: always start with NB and compare to it. A more complex method that doesn’t beat NB on a held-out set is not worth its additional cost.
The mathematical interest of NB extends beyond practical engineering. It’s the simplest member of a much richer family — directed graphical models — and the cleanest setting in which to develop the generative-vs-discriminative classifier theory that pervades modern ML. The §7 Ng–Jordan asymptotic comparison applies, with modifications, to any pair of generative + discriminative classifiers fit on the same hypothesis class. The §8 calibration framework applies to any miscalibrated classifier, not just NB. The §3 plug-in excess-risk bound is the canonical formalization of “good ranking with bad calibration.” Naive Bayes is a 60-year-old method, and its pedagogical value remains as strong as ever.
Connections and Further Reading
Internal formalML topics this builds on:
concentration-inequalities— direct prerequisite for the §7 union-bound rate proofs.kl-divergenceandshannon-entropy— drive the §9.1 Chow–Liu mutual-information construction.pac-learning— rigorous sample-complexity vocabulary for §7.high-dimensional-regression— §7 comparison with logistic regression (§11.1 sparse logistic).
Internal formalML topics this informs:
conformal-prediction— calibrated NB scores feed split-conformal classification.bayesian-neural-networks— the deep generative-classifier extension of NB.prediction-intervals— Bayesian NB posterior-predictive gives natural class-probability intervals.
Sister-site links (cross-site frontmatter):
formalstatistics/discrete-distributions— Bernoulli / Multinomial / Categorical foundations for §5.formalstatistics/bayesian-foundations-and-prior-selection— Dirichlet–multinomial conjugacy for §6.formalstatistics/maximum-likelihood— MLE machinery for §§4–5.formalstatistics/exponential-families— the log-linear structure of §2.2.formalstatistics/multivariate-distributions— multivariate Gaussian background for §4.formalcalculus/multiple-integrals— Dirichlet simplex and Gaussian integrals.formalcalculus/derivative— MLE first-order conditions.
External references appear in the brief and the MDX frontmatter. The foundational triad to read first: Domingos & Pazzani (1997) for the why-NB-works-despite-being-wrong analysis, Ng & Jordan (2002) for the discriminative-vs-generative asymptotic comparison, McCallum & Nigam (1998) for the canonical Multinomial-vs-Bernoulli study on text. For a contemporary survey: Murphy (2012) Chapter 3 (NB as the simplest probabilistic classifier) and Chapter 4 (the Gaussian-NB / LDA / QDA family).
Connections
- Direct prerequisite for the §7.3 GNB asymptotic-error bound. The Ng–Jordan O(log d / n) sample complexity proof uses a union bound over d Gaussian MLE deviations together with sub-Gaussian concentration; the high-dimensional-regression-style maximal inequality machinery is the substrate. Cross-link via Markdown, do not re-derive. concentration-inequalities
- The §9.1 Chow–Liu tree-augmented naive Bayes construction selects the tree that minimizes KL divergence between the true joint and the product-of-pairwise-marginals approximation — equivalently, the maximum-mutual-information spanning tree. The §10.2 'ranking-vs-calibration' discussion also invokes KL divergence between true and NB-estimated posteriors. kl-divergence
- Mutual information drives the §9.1 Chow–Liu edge selection. The §3.2 Bayes-risk decomposition also leans on the Shannon-entropy framing of the class-label uncertainty: H(Y) - H(Y | X) is the maximum information any classifier can extract. shannon-entropy
- The §7 Ng–Jordan asymptotic comparison is fundamentally a sample-complexity statement: how many examples does each classifier need to reach error ε of its asymptotic-best? The PAC-learning framework (VC dimension, growth function, Rademacher complexity) provides the rigorous machinery for this kind of comparison; the §7 brief uses PAC concepts and forward-points to the pac-learning topic for the rigorous foundations. pac-learning
- The §7 discriminative-vs-generative comparison contrasts Gaussian NB (generative) with logistic regression (discriminative); the high-dim-regression topic develops the §11.1 logistic lasso as the high-dimensional discriminative classifier. The §10.3 correlated-features failure mode echoes high-dim-regression's §6.2 irrepresentable-condition discussion. NB is the small-n generative alternative when sparsity assumptions in high-dim-regression don't hold. high-dimensional-regression
- NB is a natural base classifier for split-conformal classification: produce class-probability scores, calibrate by quantile-thresholding on a held-out set, output a prediction set with marginal coverage. The §8 calibration framework developed here is what makes NB suitable as a conformal base classifier (raw NB probabilities are typically too overconfident). conformal-prediction
- NB is the simplest generative classifier in the same hierarchy that BNNs occupy at the deep end. The §10.4 forward pointer relates NB's Dirichlet–multinomial conjugacy to the prior-over-weights stance BNNs take, and the §10.3 correlated-features failure of NB is exactly the kind of problem BNNs were designed to handle through richer parameterizations. bayesian-neural-networks
References & Further Reading
- paper Automatic indexing: an experimental inquiry — Maron, M. E. (1961)
- book Pattern Classification and Scene Analysis — Duda, R. O. & Hart, P. E. (1973)
- paper Naive (Bayes) at forty: the independence assumption in information retrieval — Lewis, D. D. (1998)
- paper On the optimality of the simple Bayesian classifier under zero-one loss — Domingos, P. & Pazzani, M. (1997)
- paper Bayesian network classifiers — Friedman, N., Geiger, D. & Goldszmidt, M. (1997)
- paper A comparison of event models for naive Bayes text classification — McCallum, A. & Nigam, K. (1998)
- paper Probabilistic outputs for support vector machines and comparisons to regularized likelihood methods — Platt, J. C. (1999)
- paper On bias, variance, 0/1-loss, and the curse-of-dimensionality — Friedman, J. H. (1997)
- paper Transforming classifier scores into accurate multiclass probability estimates — Zadrozny, B. & Elkan, C. (2002)
- paper On discriminative vs. generative classifiers: a comparison of logistic regression and naive Bayes — Ng, A. Y. & Jordan, M. I. (2002)
- paper Tackling the poor assumptions of naive Bayes text classifiers — Rennie, J. D. M., Shih, L., Teevan, J. & Karger, D. R. (2003)
- paper Idiot's Bayes — not so stupid after all? — Hand, D. J. & Yu, K. (2001)
- paper Not so naive Bayes: aggregating one-dependence estimators — Webb, G. I., Boughton, J. R. & Wang, Z. (2005)
- paper Predicting good probabilities with supervised learning — Niculescu-Mizil, A. & Caruana, R. (2005)
- paper Approximating discrete probability distributions with dependence trees — Chow, C. K. & Liu, C. N. (1968)
- paper A novel Bayes model: hidden naive Bayes — Jiang, L., Zhang, H. & Cai, Z. (2009)
- paper Baselines and bigrams: simple, good sentiment and topic classification — Wang, S. I. & Manning, C. D. (2012)
- book A Probabilistic Theory of Pattern Recognition — Devroye, L., Györfi, L. & Lugosi, G. (1996)
- book Pattern Recognition and Machine Learning — Bishop, C. M. (2006)
- book Machine Learning: A Probabilistic Perspective — Murphy, K. P. (2012)
- book The Elements of Statistical Learning — Hastie, T., Tibshirani, R. & Friedman, J. (2009)
- book Introduction to Information Retrieval — Manning, C. D., Raghavan, P. & Schütze, H. (2008)
- book Probabilistic Graphical Models: Principles and Techniques — Koller, D. & Friedman, N. (2009)
- paper Latent Dirichlet allocation — Blei, D. M., Ng, A. Y. & Jordan, M. I. (2003)
- paper Classifier technology and the illusion of progress — Hand, D. J. (2006)
- paper A comparative study on feature selection in text categorization — Yang, Y. & Pedersen, J. O. (1997)
- paper On calibration of modern neural networks — Guo, C., Pleiss, G., Sun, Y. & Weinberger, K. Q. (2017)
- paper Naive Bayes classifiers that perform well with continuous variables — Bouckaert, R. R. (2004)