Simple Algorithm
Machine Learning · Convergence · 28 min

Generative vs Discriminative Classifiers

LDA, naive Bayes and when modeling p(x | y) pays off.

A classifier can model the boundary between the classes, p(y∣x)p(y \mid \mathbf x), or it can model each class, p(x∣y)p(\mathbf x \mid y), and let Bayes' rule draw the boundary. The second road leads to discriminant analysis and naive Bayes, among the oldest and fastest classifiers there are. This lesson derives them, shows that linear discriminant analysis secretly produces a logistic regression, and asks when modeling more than you need pays off.

What you’ll learn

  • Distinguish generative from discriminative classifiers, and classify by Bayes' rule from class-conditional models.
  • Derive the posterior of Gaussian discriminant analysis, logistic with a shared covariance and quadratic without it, and connect it to Fisher's discriminant.
  • Derive naive Bayes for Gaussian, Bernoulli and multinomial features, show that its log-odds are linear in suitable features, and explain why it can classify well although its independence assumption is false.
  • Summarize what theory says about the trade-off: Efron's efficiency result, Ng & Jordan's two regimes and their critics, and the high-dimensional case.

Two ways to build a classifier

A generative classifier models the class proportions πk=p(y=k)\pi_k = p(y = k) and the class-conditional densities p(x∣y=k)p(\mathbf x \mid y = k), then applies Bayes' rule:

p(y=k∣x)=πk p(x∣y=k)∑jπj p(x∣y=j),y^(x)=arg max⁡k πk p(x∣y=k).p(y = k \mid \mathbf x) = \frac{\pi_k\,p(\mathbf x \mid y = k)}{\sum_j\pi_j\,p(\mathbf x \mid y = j)}, \qquad \hat y(\mathbf x) = \argmax_k\ \pi_k\,p(\mathbf x \mid y = k).

If the model is right, this is the Bayes-optimal classifier. A discriminative classifier, such as logistic regression or an SVM, models p(y∣x)p(y \mid \mathbf x) or the boundary directly and never says how the inputs themselves are distributed. For two classes every generative model has a logistic form:

log⁡p(y=1∣x)p(y=0∣x)=log⁡p(x∣y=1)p(x∣y=0)+log⁡π1π0.\log\frac{p(y = 1 \mid \mathbf x)}{p(y = 0 \mid \mathbf x)} = \log\frac{p(\mathbf x \mid y = 1)}{p(\mathbf x \mid y = 0)} + \log\frac{\pi_1}{\pi_0}.

Everything depends on what function of x\mathbf x the log-likelihood ratio turns out to be.

QuestionGenerativeDiscriminative
What is modeled?p(x∣y)p(\mathbf x \mid y) and p(y)p(y)p(y∣x)p(y \mid \mathbf x) or the boundary only
Fittingoften closed form: counts, means, covariancesiterative optimization
Missing features at test timemarginalize them out of p(x∣y)p(\mathbf x \mid y)needs imputation or a separate model
Unlabeled datausable, e.g. through the EM algorithmnot directly
Class proportions changereplace πk\pi_k, keep the restshift the intercepts by the log prior ratio
Model wrong in p(x∣y)p(\mathbf x \mid y)the boundary inherits the errorunaffected, if the boundary family is right

Gaussian discriminant analysis: LDA and QDA

DerivationA shared covariance gives a logistic posterior
  1. log⁡p(x∣y=k)=−12(x−μk)⊤Σk−1(x−μk)−12log⁡det⁡(2πΣk)\log p(\mathbf x \mid y = k) = -\tfrac12(\mathbf x - \boldsymbol\mu_k)^\top\Sigma_k^{-1}(\mathbf x - \boldsymbol\mu_k) - \tfrac12\log\det(2\pi\Sigma_k)

    Let each class be Gaussian, x∣y=k∼N(μk,Σk)\mathbf x \mid y = k \sim \mathcal N(\boldsymbol\mu_k, \Sigma_k), so that

  2. log⁡p(x∣1)p(x∣0)=(μ1−μ0)⊤Σ−1x−12(μ1⊤Σ−1μ1−μ0⊤Σ−1μ0)\log\frac{p(\mathbf x \mid 1)}{p(\mathbf x \mid 0)} = (\boldsymbol\mu_1 - \boldsymbol\mu_0)^\top\Sigma^{-1}\mathbf x - \tfrac12\big(\boldsymbol\mu_1^\top\Sigma^{-1}\boldsymbol\mu_1 - \boldsymbol\mu_0^\top\Sigma^{-1}\boldsymbol\mu_0\big)

    With a shared covariance Σ0=Σ1=Σ\Sigma_0 = \Sigma_1 = \Sigma, the quadratic term x⊤Σ−1x\mathbf x^\top\Sigma^{-1}\mathbf x and the determinants cancel in the log-likelihood ratio, leaving a linear function of x\mathbf x:

  3. p(y=1∣x)=σ(w⊤x+b),w=Σ−1(μ1−μ0),b=−12(μ1⊤Σ−1μ1−μ0⊤Σ−1μ0)+log⁡π1π0p(y = 1 \mid \mathbf x) = \sigma(\mathbf w^\top\mathbf x + b), \qquad \mathbf w = \Sigma^{-1}(\boldsymbol\mu_1 - \boldsymbol\mu_0), \qquad b = -\tfrac12\big(\boldsymbol\mu_1^\top\Sigma^{-1}\boldsymbol\mu_1 - \boldsymbol\mu_0^\top\Sigma^{-1}\boldsymbol\mu_0\big) + \log\frac{\pi_1}{\pi_0}

    Add the log prior ratio: the posterior is exactly a logistic regression, with a linear boundary. This is linear discriminant analysis (LDA):

  4. log⁡p(y=1∣x)p(y=0∣x)=−12x⊤(Σ1−1−Σ0−1)x+(Σ1−1μ1−Σ0−1μ0)⊤x+c\log\frac{p(y = 1 \mid \mathbf x)}{p(y = 0 \mid \mathbf x)} = -\tfrac12\mathbf x^\top\big(\Sigma_1^{-1} - \Sigma_0^{-1}\big)\mathbf x + \big(\Sigma_1^{-1}\boldsymbol\mu_1 - \Sigma_0^{-1}\boldsymbol\mu_0\big)^\top\mathbf x + c

    With separate covariances nothing cancels, and the log-odds are quadratic in x\mathbf x: quadratic discriminant analysis (QDA), whose boundaries are conic sections in the plane.

Fitting is closed form. The maximum-likelihood estimates are the class frequencies π^k=nk/n\hat\pi_k = n_k/n, the class means μ^k\hat{\boldsymbol\mu}_k, and for LDA the pooled within-class covariance Σ^=1n∑k∑i: yi=k(xi−μ^k)(xi−μ^k)⊤\hat\Sigma = \frac1n\sum_k\sum_{i:\,y_i = k}(\mathbf x_i - \hat{\boldsymbol\mu}_k)(\mathbf x_i - \hat{\boldsymbol\mu}_k)^\top (divide by n−Kn - K instead for an unbiased estimate). One pass over the data, no iterations. The catch is the parameter count: a covariance in dd dimensions has d(d+1)/2d(d+1)/2 entries, 5,050 for d=100d = 100; QDA needs one per class, and both need Σ^\hat\Sigma to be invertible, which fails when d≥nd \ge n. Regularized discriminant analysis (Friedman, 1989) shrinks the class covariances toward the pooled one and toward a multiple of the identity.

Fisher's view. Fisher (1936), working with measurements of iris flowers, asked a question without any distributional assumption: which projection w⊤x\mathbf w^\top\mathbf x separates the class means most, relative to the spread within the classes? Maximizing J(w)=(w⊤(m1−m0))2/w⊤SWwJ(\mathbf w) = \big(\mathbf w^\top(\mathbf m_1 - \mathbf m_0)\big)^2/\mathbf w^\top S_W\mathbf w, with SWS_W the within-class scatter matrix, gives w∝SW−1(m1−m0)\mathbf w \propto S_W^{-1}(\mathbf m_1 - \mathbf m_0) by the Cauchy–Schwarz inequality: the same direction as LDA. With two classes, it is also proportional to the least-squares coefficient vector for regressing a numerically coded label on x\mathbf x.

Predict before you look

Two equally likely Gaussian classes share a covariance, and their Mahalanobis distance is Δ=(μ1−μ0)⊤Σ−1(μ1−μ0)=2\Delta = \sqrt{(\boldsymbol\mu_1 - \boldsymbol\mu_0)^\top\Sigma^{-1}(\boldsymbol\mu_1 - \boldsymbol\mu_0)} = 2. What is the Bayes error rate?

Show the answer

15.9 %

Projected onto the LDA direction, the classes become two unit-variance Gaussians Δ\Delta apart, and the optimal threshold sits halfway, Δ/2\Delta/2 from each mean. The error is Φ(−Δ/2)=Φ(−1)≈15.9%\Phi(-\Delta/2) = \Phi(-1) \approx 15.9\%. At Δ=1\Delta = 1 it is about 30.9%, at Δ=3\Delta = 3 about 6.7%: only the Mahalanobis distance matters, whatever the dimension.

Naive Bayes

Naive Bayes makes one sweeping assumption: the features are independent given the class, p(x∣y=k)=∏j=1dp(xj∣y=k)p(\mathbf x \mid y = k) = \prod_{j=1}^d p(x_j \mid y = k). Each factor is estimated on its own, so the model needs only O(Kd)\order{Kd} parameters, trains in one pass, copes with d≫nd \gg n, handles mixed feature types, and ignores a missing feature by simply dropping its factor.

VariantModel for xj∣y=kx_j \mid y = kLog-odds (two classes)
GaussianN(μkj,σkj2)\mathcal N(\mu_{kj}, \sigma_{kj}^2)a sum of one-variable quadratics, ∑j(ajxj2+bjxj)+c\sum_j(a_jx_j^2 + b_jx_j) + c; linear if each σkj\sigma_{kj} is shared across classes
Bernoulli (word present or not)xj∈{0,1}x_j \in \{0, 1\} with Pr⁡(xj=1)=θkj\Pr(x_j = 1) = \theta_{kj}∑j[xjlog⁡θ1jθ0j+(1−xj)log⁡1−θ1j1−θ0j]+log⁡π1π0\sum_j\big[x_j\log\frac{\theta_{1j}}{\theta_{0j}} + (1 - x_j)\log\frac{1 - \theta_{1j}}{1 - \theta_{0j}}\big] + \log\frac{\pi_1}{\pi_0}: linear in x\mathbf x
Multinomial (word counts)p(x∣k)∝∏jθkjxjp(\mathbf x \mid k) \propto \prod_j\theta_{kj}^{x_j}, with ∑jθkj=1\sum_j\theta_{kj} = 1∑jxjlog⁡θ1jθ0j+log⁡π1π0\sum_j x_j\log\frac{\theta_{1j}}{\theta_{0j}} + \log\frac{\pi_1}{\pi_0}: linear in the counts
Estimate θkj\theta_{kj} with additive smoothing, e.g. (count + 1+\,1)/(total ++ vocabulary size) for the multinomial, or a single unseen word would veto a class by contributing log⁡0\log 0. For text, McCallum & Nigam (1998) found the multinomial model generally more accurate than the Bernoulli one at large vocabulary sizes.

In the discrete cases, naive Bayes is a linear classifier in the same features that logistic regression would use. The two differ only in how they choose the weights: naive Bayes maximizes the joint likelihood p(x,y)p(\mathbf x, y) under the independence model, feature by feature; logistic regression maximizes the conditional likelihood p(y∣x)p(y \mid \mathbf x), all weights together. That makes them a natural generative–discriminative pair.

Why does it work so often? The independence assumption is nearly always false, yet naive Bayes is often a strong classifier. Domingos & Pazzani (1997) showed that it is optimal under 0–1 loss in a far larger region than the one where independence holds: a classifier only has to rank the right class first, and the errors in the estimated probabilities often leave the ranking intact. The probabilities themselves are another matter: correlated features count the same evidence several times, which drives them toward 0 and 1, so naive Bayes is typically overconfident and needs recalibration if its probabilities are to be used.

Think first You accidentally include every feature twice in a naive Bayes model. With equal class priors, what happens to its predicted classes, and to its predicted probabilities?

Each log-likelihood ratio is now counted twice, so the log-odds become 2∑jlog⁡p(xj∣1)p(xj∣0)2\sum_j\log\frac{p(x_j \mid 1)}{p(x_j \mid 0)} instead of ∑jlog⁡p(xj∣1)p(xj∣0)\sum_j\log\frac{p(x_j \mid 1)}{p(x_j \mid 0)}. The sign, and so every predicted class, is unchanged, but the posterior odds are squared: a 3-to-1 call becomes 9-to-1. That is overconfidence from double counting in its purest form. With unequal priors the decisions can change too, because the prior term is no longer doubled.

Which is better? What the theory says

When the generative model is right, it is more efficient. If the classes really are Gaussian with a shared covariance, LDA is the full maximum-likelihood estimator, while logistic regression conditions on x\mathbf x and discards the information in its distribution. Efron (1975) computed the asymptotic relative efficiency: for statistically interesting values of the parameters, logistic regression is "between one half and two thirds as effective as normal discrimination," so it needs roughly 1.5 to 2 times as many examples to match LDA's expected error rate.

When it is wrong, the discriminative model is safer. LDA assumes Gaussian classes; logistic regression assumes only that the log-odds are linear. That holds far more widely: any exponential family p(x∣y=k)∝h(x)exp⁡(θk⊤T(x))p(\mathbf x \mid y = k) \propto h(\mathbf x)\exp(\boldsymbol\theta_k^\top T(\mathbf x)) with a common base measure hh gives log-odds linear in the sufficient statistics T(x)T(\mathbf x). Outliers, skewed classes or binary features can distort LDA's means and covariance without touching the logistic form.

Two regimes. Ng & Jordan (2002) compared naive Bayes with logistic regression as a generative–discriminative pair and found that "while discriminative learning has lower asymptotic error, a generative classifier may also approach its (higher) asymptotic error much faster." In their analysis, naive Bayes needs a number of examples logarithmic in the number of features dd to get close to its asymptotic error, against a number linear in dd for logistic regression, so naive Bayes can win with little data and lose with a lot. Xue & Titterington (2008) cautioned that their own simulations and experiments did not support two distinct regimes in general, and that conclusions about one pair need not carry over to other generative–discriminative pairs.

Very high dimensions. When dd grows faster than nn, the sample covariance is singular and noisy, and Bickel & Levina (2004) showed that the naive Bayes independence rule can greatly outperform Fisher's discriminant, despite ignoring every correlation. Estimating fewer things badly can beat estimating more things very badly.

Check your understanding

You must classify emails with only 30 labeled examples and a 5,000-word vocabulary. Which first choice is most defensible?

  1. Unregularized logistic regression on word counts, because discriminative models have lower asymptotic error
  2. Quadratic discriminant analysis, because it is the most flexible Gaussian model
  3. Multinomial naive Bayes with smoothing: few, separately estimated parameters that approach their limit quickly
  4. Linear discriminant analysis with the sample covariance
Show the answer

C. Multinomial naive Bayes with smoothing: few, separately estimated parameters that approach their limit quickly

With d=5000≫n=30d = 5000 \gg n = 30, the data are almost surely linearly separable, so unregularized logistic regression has no maximum-likelihood estimate, and the sample covariance needed by LDA and QDA is singular. Naive Bayes estimates each word's class rates on its own, a small-sample-friendly design, exactly the regime where generative models tend to win. A strongly regularized logistic regression would be the natural second candidate.

Key takeaways

  • Generative classifiers model p(x∣y)p(\mathbf x \mid y) and p(y)p(y) and classify by Bayes' rule; discriminative ones model p(y∣x)p(y \mid \mathbf x) directly. For two classes the posterior log-odds equal the log-likelihood ratio plus the log prior ratio.
  • Gaussian classes with a shared covariance give exactly a logistic posterior with w=Σ−1(μ1−μ0)\mathbf w = \Sigma^{-1}(\boldsymbol\mu_1 - \boldsymbol\mu_0) (LDA, the direction of Fisher's discriminant); separate covariances give quadratic boundaries (QDA). The Bayes error is Φ(−Δ/2)\Phi(-\Delta/2) in the Mahalanobis distance Δ\Delta.
  • Naive Bayes assumes conditional independence; its Bernoulli and multinomial versions are linear classifiers in the features. It is often accurate under 0–1 loss despite a false assumption (Domingos & Pazzani), but its probabilities are overconfident.
  • When the generative model is right it is more efficient (Efron: logistic regression is one half to two thirds as efficient as LDA); when it is wrong the discriminative model is safer. Naive Bayes can win with little data (Ng & Jordan), a pattern later shown not to be universal, and the independence rule beats Fisher's discriminant when d≫nd \gg n (Bickel & Levina).

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Two classes are Gaussian with means μ0,μ1\boldsymbol\mu_0, \boldsymbol\mu_1 and a shared covariance Σ\Sigma. What is the form of p(y=1∣x)p(y = 1 \mid \mathbf x)?

  1. A Gaussian density in x\mathbf x
  2. σ(w⊤x+b)\sigma(\mathbf w^\top\mathbf x + b) with w=Σ−1(μ1−μ0)\mathbf w = \Sigma^{-1}(\boldsymbol\mu_1 - \boldsymbol\mu_0): a logistic regression
  3. A quadratic function of x\mathbf x passed through the sigmoid
  4. A step function at the midpoint of the means, whatever Σ\Sigma is
Show the answer

B. σ(w⊤x+b)\sigma(\mathbf w^\top\mathbf x + b) with w=Σ−1(μ1−μ0)\mathbf w = \Sigma^{-1}(\boldsymbol\mu_1 - \boldsymbol\mu_0): a logistic regression

With a shared covariance the quadratic terms and determinants cancel in the log-likelihood ratio, leaving log-odds linear in x\mathbf x. LDA and logistic regression share a functional form; they differ in how they estimate w\mathbf w and bb.

Question 2

Naive Bayes often classifies well even though its features are clearly dependent. What is the best explanation?

  1. Dependence between features cannot affect a classifier
  2. Naive Bayes detects and removes dependent features automatically
  3. Its probability estimates are accurate whenever its classifications are
  4. Under 0–1 loss only the ranking of the classes matters, and biased probability estimates often preserve it
Show the answer

D. Under 0–1 loss only the ranking of the classes matters, and biased probability estimates often preserve it

Domingos & Pazzani (1997) showed that naive Bayes is optimal under 0–1 loss far beyond the independence region, because classification only needs the most probable class on top. Its probabilities are usually overconfident, so the explanation covers decisions, not probabilities.

Question 3

With d=100d = 100 features and K=3K = 3 classes, how many covariance parameters must QDA estimate?

  1. 300
  2. 5,050
  3. 15,150
  4. 30,000
Show the answer

C. 15,150

A symmetric 100×100100\times100 covariance has d(d+1)/2=5,050d(d+1)/2 = 5{,}050 free entries, and QDA needs one per class: 3×5,050=15,1503\times5{,}050 = 15{,}150. LDA shares one covariance (5,050), and Gaussian naive Bayes needs only the 3×100=3003\times100 = 300 variances.

Question 4

What did Ng & Jordan (2002) conclude about naive Bayes versus logistic regression?

  1. Logistic regression has lower asymptotic error, but naive Bayes can approach its own higher asymptotic error much faster, so it may win with little data
  2. Logistic regression is better at every training-set size
  3. Naive Bayes is better at every training-set size
  4. They always reach the same asymptotic error
Show the answer

A. Logistic regression has lower asymptotic error, but naive Bayes can approach its own higher asymptotic error much faster, so it may win with little data

Two regimes: with few examples naive Bayes (about log⁡d\log d samples to approach its limit, in their analysis) can beat logistic regression (about dd), and with many examples logistic regression's lower asymptotic error wins. Later work cautioned that the pattern is not universal.

Further reading

  • R. A. Fisher, "The use of multiple measurements in taxonomic problems," Annals of Eugenics 7(2), 179–188 (1936).
  • B. Efron, "The efficiency of logistic regression compared to normal discriminant analysis," Journal of the American Statistical Association 70(352), 892–898 (1975).
  • P. Domingos & M. Pazzani, "On the optimality of the simple Bayesian classifier under zero-one loss," Machine Learning 29, 103–130 (1997).
  • A. Y. Ng & M. I. Jordan, "On discriminative vs. generative classifiers: a comparison of logistic regression and naive Bayes," Advances in Neural Information Processing Systems 14 (NIPS 2001; MIT Press, 2002), 841–848.
  • P. J. Bickel & E. Levina, "Some theory for Fisher's linear discriminant function, 'naive Bayes', and some alternatives when there are many more variables than observations," Bernoulli 10(6), 989–1010 (2004).