Naive Bayes and generative vs discriminative models
Classify by modelling how the data were made
There are two ways to build a classifier: model the boundary between classes directly, or model how each class generates its data and invert with Bayes' rule. Naive Bayes is the simplest generative classifier — a few lines of counting that still competes on text — and the generative/discriminative distinction it introduces is the one behind the phrase "generative AI": a language model is a generative model of text (6.2 Classical NLP and n-gram language models, 7.6 Decoder-only: GPT and autoregressive generation).
You'll be able to
- State the Bayes classifier and explain why the evidence term can be ignored
- Explain the conditional-independence assumption, its parameter savings and why the argmax often survives its violation
- Fit Bernoulli, multinomial and Gaussian Naive Bayes by maximum likelihood with Laplace smoothing
- Compute class posteriors in log space and run a complete worked spam example
- Compare generative and discriminative models on sample efficiency, asymptotic accuracy and capabilities
- Connect Naive Bayes to n-gram language models and to what 'generative' means in generative AI
Key ideas
- Generative classifiers model p(x | y) and p(y) and apply Bayes' rule; discriminative ones model p(y | x) directly. The evidence p(x) cancels in the argmax.
- Naive Bayes assumes features are conditionally independent given the class, cutting parameters from exponential to linear in d; the ranking often survives the false assumption even when probabilities are over-confident.
- Multinomial NB for counts, Bernoulli for presence/absence, Gaussian for continuous features; all fit by counting (MLE).
Show 5 more key ideas
- Laplace smoothing θ̂ = (N_cj + α)/(N_c + αV) prevents a single unseen word from zeroing a class; compute in log space to avoid underflow.
- Log-score = log π_c + Σ x_j log θ̂_cj is linear in the features: Naive Bayes is a linear classifier whose weights are set by counting.
- Generative models need O(log d) examples to reach their (higher) asymptotic error, discriminative O(d) to reach a lower one — NB wins small data, logistic regression wins big data.
- Generative models can marginalize missing features, generate samples and score outliers; a language model is a generative model of text.
- Naive Bayes is the baseline a fancier text model must beat.
Suggested path through this lesson
Two routes to a classifier
A discriminative model learns — or just the boundary — directly from inputs to labels; logistic regression (3.3 Logistic regression and softmax classification) and every neural-network classifier are discriminative. A generative model learns how each class produces inputs, , plus how common each class is, , and classifies by Bayes' theorem (1.7 Probability II: Bayes, independence, MLE and MAP):
The denominator is the same for every class, so the ignores it; you only need it when you want the actual posterior probabilities. The prior is estimated by class frequencies. The hard part is : a joint distribution over all features, per class.
The naive assumption
With binary features, the exact class-conditional distribution has free parameters per class — for a 1,000-word vocabulary. Naive Bayes assumes the features are conditionally independent given the class:
reducing the count to parameters per class. The assumption is almost always false — "free" and "offer" co-occur in spam far more than independence predicts — yet the classifier often works, because it only needs the ranking of the classes to be right, not the probabilities. Dependencies tend to inflate the winning class's score and the losers' scores by similar factors, so the survives even when the posteriors are wildly over-confident (Domingos & Pazzani, 1997). This is also why Naive Bayes probabilities should never be read as calibrated (3.3 Logistic regression and softmax classification).
Three flavours
| variant | feature model | MLE estimate | typical use |
|---|---|---|---|
| Bernoulli | : | fraction of class- documents containing word | short texts, presence/absence features |
| Multinomial | word counts: | , the share of class- tokens that are word | document classification, spam, sentiment |
| Gaussian | per-class mean and variance of each feature | continuous features (sensor data, measurements) |
Multinomial Naive Bayes with word counts is the classic text classifier and the one we will compute by hand. Gaussian Naive Bayes is a diagonal-covariance special case of Gaussian discriminant analysis (GDA); with a shared covariance across classes, GDA's log-odds are linear in — the same functional form as logistic regression, reached by a different route.
Smoothing and logs
A word never seen in spam during training has , and one zero factor annihilates the whole product no matter how spammy the rest of the message is. Laplace (add-) smoothing pretends every word was seen extra times in every class:
with the vocabulary size and the default ( often works better; tune it by cross-validation, 3.5 Evaluating models: metrics, validation and the bias–variance trade-off). The same trick, under the name add- smoothing, rescues n-gram language models (6.2 Classical NLP and n-gram language models). Products of hundreds of probabilities underflow to zero in floating point, so compute everything in log space:
That expression is linear in the feature counts with weights and bias — Naive Bayes is a linear classifier whose weights are set by counting rather than by gradient descent (3.3 Logistic regression and softmax classification). To recover posteriors, exponentiate after subtracting the maximum log-score (the log-sum-exp trick of 2.2 NumPy and vectorized thinking).
Worked example: a five-word spam filter
Vocabulary : {free, win, meeting, report, the}. Training data: 5 spam documents with 10 tokens in total (free 4, win 3, the 3) and 5 ham documents with 10 tokens (meeting 4, report 3, the 3). Priors . With , every estimate is :
| word | ||
|---|---|---|
| free | ||
| win | ||
| meeting | ||
| report | ||
| the |
Classify the message "free win meeting":
Posterior . In log space: , ; the difference matches the 4:1 odds. Without smoothing, would have forced the spam score to zero and the message to ham on the strength of one word — the failure smoothing exists to prevent.
import numpy as np
class MultinomialNB:
def fit(self, X, y, alpha=1.0): # X: (n, V) counts, y: (n,) ints
self.classes = np.unique(y)
self.log_prior = np.log(np.array([(y == c).mean() for c in self.classes]))
counts = np.stack([X[y == c].sum(0) for c in self.classes]) # (C, V)
self.log_theta = np.log((counts + alpha) / (counts.sum(1, keepdims=True) + alpha * X.shape[1]))
return self
def predict_log_proba(self, X):
s = self.log_prior + X @ self.log_theta.T # (n, C) — linear in counts
return s - np.logaddexp.reduce(s, axis=1, keepdims=True) # normalize in log space
Generative versus discriminative, precisely
| generative (NB, GDA) | discriminative (logistic regression, nets) | |
|---|---|---|
| learns | and | or the boundary |
| assumptions | strong (independence, Gaussianity) | weak |
| data needed to reach its best error | examples | examples |
| best achievable error | higher (assumptions bite) | lower |
| extras | handles missing features by marginalizing, generates samples, scores outliers via , uses unlabelled data | usually more accurate with enough data; calibrated probabilities |
Ng and Jordan (2001) made the middle rows precise: Naive Bayes converges to its asymptotic error with a number of examples logarithmic in , logistic regression needs linearly many — so Naive Bayes often wins with little data and loses with a lot. The practical rule: a small labelled set with many features (early-stage text classification) favours Naive Bayes; abundant data favours discriminative models. Naive Bayes is also an excellent baseline: if a neural network cannot beat counting words, something is wrong with the pipeline (3.1 What is learning? ERM, generalization and the ML workflow).
Why "generative AI" is the same word
A language model is a generative model of text: it defines over token sequences and can sample from it (6.2 Classical NLP and n-gram language models, 7.6 Decoder-only: GPT and autoregressive generation). Naive Bayes, n-gram models and GPT are on one continuum of increasingly expressive : the multinomial model treats a document as a bag of independent draws, an n-gram model conditions each token on the previous , a transformer conditions on everything. Smoothing, log-space computation and perplexity all start here. And the generative route to classification survives at the frontier: zero-shot classification by comparing across candidate labels is Bayes' rule with a language model as the likelihood.
Where this shows up later
- Add- smoothing, log-space scoring and perplexity reappear for n-gram language models — 6.2 Classical NLP and n-gram language models; "generative model of text" is the definition of an LLM — 7.6 Decoder-only: GPT and autoregressive generation, 8.1 The LLM lifecycle and model landscape.
- Gaussian class-conditionals with shared covariance give linear boundaries — the same form as 3.3 Logistic regression and softmax classification — and relate to LDA, a cousin of PCA — 3.12 Dimensionality reduction: PCA, t-SNE and UMAP.
- Generative modelling of becomes VAEs, GANs and diffusion — 8.8 Generative models I: VAEs and GANs, 8.9 Generative models II: Diffusion and flow matching; the Bayesian classifier idea underlies classifier guidance in diffusion — 8.9 Generative models II: Diffusion and flow matching.
- Naive Bayes as a counting baseline is the first model to try in the tabular and text projects — 3.14 Project: end-to-end tabular ML with scikit-learn.
Common pitfalls (5)
- Reading Naive Bayes posteriors as calibrated probabilities; the independence assumption makes them extreme.
- Skipping smoothing, so one unseen word in a class forces that class's probability to zero.
- Multiplying raw probabilities instead of summing logs; products of hundreds of factors underflow to 0.
- Using Gaussian NB on features that are far from Gaussian (counts, heavy tails) without transforming them.
- Assuming the generative model's assumptions are harmless when data are plentiful — a discriminative model will usually be more accurate there.
Recap: all 8 key points
- Generative classifiers model p(x | y) and p(y) and apply Bayes' rule; discriminative ones model p(y | x) directly. The evidence p(x) cancels in the argmax.
- Naive Bayes assumes features are conditionally independent given the class, cutting parameters from exponential to linear in d; the ranking often survives the false assumption even when probabilities are over-confident.
- Multinomial NB for counts, Bernoulli for presence/absence, Gaussian for continuous features; all fit by counting (MLE).
- Laplace smoothing θ̂ = (N_cj + α)/(N_c + αV) prevents a single unseen word from zeroing a class; compute in log space to avoid underflow.
- Log-score = log π_c + Σ x_j log θ̂_cj is linear in the features: Naive Bayes is a linear classifier whose weights are set by counting.
- Generative models need O(log d) examples to reach their (higher) asymptotic error, discriminative O(d) to reach a lower one — NB wins small data, logistic regression wins big data.
- Generative models can marginalize missing features, generate samples and score outliers; a language model is a generative model of text.
- Naive Bayes is the baseline a fancier text model must beat.
Watch
Multinomial Naive Bayes on a spam example, including why smoothing is needed.
Read
Exercises
- Reproduce the spam example
Recompute the smoothed table and the scores for "free win meeting" by hand, in probability and in log space. Then classify "the report" and "free the the". Expected: posterior spam 0.8 for the first message; "the report" → ham (4:1), "free the the" → spam (5:1).
- From scratch vs scikit-learn
Vectorize a small text dataset (e.g., scikit-learn's 20 newsgroups, four categories) with
CountVectorizer, train theMultinomialNBclass above and scikit-learn's, and compare predictions and accuracy. Expected: identical predictions; accuracy well above the majority baseline within a second of training. - The two regimes
On the same data, train Naive Bayes and logistic regression on 50, 200, 1,000 and all training documents; plot test accuracy vs training size. Expected: Naive Bayes is ahead or equal at small sizes and logistic regression overtakes it as data grow.
- Smoothing matters
Sweep α over {0, 0.01, 0.1, 1, 10} and record accuracy and log loss. Expected: α = 0 produces −∞ log-likelihoods on test documents with unseen words; a small α (0.01–0.1) often beats α = 1 on accuracy.
Quiz
Flashcards
These cards are now in your spaced-repetition queue. Review all due cards →