Naive Bayes, LDA, and QDA Classifiers
A probabilistic discriminative classifier such as logistic regression models \(p(y\mid x)\) directly; other discriminative methods learn a decision rule without estimating that probability. A generative classifier models the class-conditional distribution \(p(x\mid y)\) and class prior \(p(y)\), then combines them using Bayes’ theorem. For class \(k\), the posterior is \(p(y=k\mid x)=\pi_k p(x\mid y=k)/\sum_\ell\pi_\ell p(x\mid y=\ell)\), where \(\pi_k=p(y=k)\). The denominator normalizes the class scores to sum to one. For continuous features the likelihood term is a density. The choice of model affects assumptions, estimation, and predictions; parameter count alone does not determine which classifier wins. Run the Python blocks in order; later body code builds on the earlier imports.
Naive Bayes and the assumption in its name
An unrestricted joint distribution for \(p\) features can be difficult to estimate. Gaussian, Bernoulli, and categorical Naive Bayes simplify it by assuming conditional independence: \(p(x\mid y)=\prod_j p(x_j\mid y)\). Each feature’s distribution can then be estimated separately within a class. Conditional independence is different from marginal independence: mixing classes can create correlations, and conditioning on a class can also introduce them. The assumption must concern the within-class distribution; it is not generally a weaker version of independence.
| Variant | Feature type | Per-class parameters |
|---|---|---|
| Gaussian NB | continuous | a mean and variance per feature |
| Multinomial NB | counts | a probability per vocabulary item |
| Bernoulli NB | binary presence | a probability per feature |
| Categorical NB | unordered levels | a probability per level per feature |
Multinomial NB uses a related bag-of-words model: conditional on the class and document length, token draws share a class-specific vocabulary distribution. Its class likelihood is proportional to \(\prod_j\theta_{kj}^{x_j}\), with \(x_j\) the word count. The count coordinates themselves are not independent when their sum is fixed. Each vocabulary probability vector sums to one, so a vocabulary of size \(V\) has \(V-1\) free probabilities per class; class priors are additional to the parameters in the table.
Multinomial NB counts repeated occurrences, while Bernoulli NB records presence or absence once per vocabulary item and includes the likelihood of absent words. Document length, vocabulary design, and how informative repetition or absence is can affect their relative performance. Neither model universally wins on short or long documents.
Zero counts and smoothing
In a multinomial likelihood, a zero estimated probability for an observed word makes that class’s document score zero. If every class assigns zero score, Bayes normalization has a zero denominator. The example uses four vocabulary items and equal class priors, \(\pi_0=\pi_1=0.5\). Token totals do not supply document-class priors. It reports log scores with the multinomial combinatorial factor omitted because that factor is the same for both classes. Zero-count terms are omitted by convention; literal floating-point \(0\log0\) would not be a valid calculation.
import numpy as np
counts = np.array([[3., 1., 0., 0.], # class 0 word counts
[0., 0., 2., 4.]]) # class 1
test = np.array([1., 0., 0., 1.]) # this document uses word 0 and word 3
present = test > 0 # omit zero-count terms by the likelihood convention
for alpha in (0.0, 0.01, 1.0):
theta = (counts + alpha) / (counts.sum(1, keepdims=True) + alpha * counts.shape[1])
with np.errstate(divide="ignore"):
logscore = (test[present] * np.log(theta[:, present])).sum(1)
logjoint = logscore + np.log([0.5, 0.5])
if np.all(np.isneginf(logjoint)):
p1 = np.nan
else:
shifted = logjoint - logjoint.max()
p1 = np.exp(shifted[1]) / np.exp(shifted).sum()
print(f"alpha {alpha:5.2f} theta_class0 {np.round(theta[0], 4)}"
f" logscore {np.round(logscore, 4)} P(class1 | x) {p1:.4f}")
# alpha 0.00 theta_class0 [0.75 0.25 0. 0. ] logscore [-inf -inf] P(class1 | x) nan
# alpha 0.01 theta_class0 [0.745 0.25 0.0025 0.0025] logscore [-6.2957 -6.8132] P(class1 | x) 0.3734
# alpha 1.00 theta_class0 [0.5 0.25 0.125 0.125] logscore [-2.7726 -2.9957] P(class1 | x) 0.4444
Here word 3 has never appeared in class 0 and word 0 has never appeared in class 1, so both unsmoothed class scores are zero. The code returns nan to mark the undefined posterior. A program could still emit a fallback label, but it would not come from a normalized posterior under these estimates. Zero counts can matter in sparse vocabularies; positive smoothing is one way to handle them. Continuous Gaussian densities with positive variances do not have this particular zero-count problem.
Additive smoothing estimates \(\theta_{kj}=(N_{kj}+\alpha)/(N_k+V\alpha)\), where \(N_{kj}\) is the class’s count for word \(j\), \(N_k\) its total token count, and \(V\) the vocabulary size. The special case \(\alpha=1\) is Laplace smoothing; other positive values are often called Lidstone smoothing. The estimate is the posterior mean under a symmetric Dirichlet prior, used here as a plug-in vocabulary distribution. At \(\alpha=1\), class 0 assigns an unseen word \(1/(4+4)=0.125\).
For the test document at \(\alpha=1\), the two likelihood scores are \(0.5\times0.125=0.0625\) and \(0.1\times0.5=0.05\). Equal priors cancel, giving \(0.05/(0.0625+0.05)=0.4444\) for class 1. Positive \(\alpha\) makes the observed-word scores nonzero and pulls each class’s vocabulary probabilities toward uniformity. That need not move every document’s posterior monotonically toward 0.5; priors and word counts matter. Select smoothing strength using validation data when its effect is material.
LDA and QDA
LDA models each class as Gaussian with its own mean and a shared covariance matrix \(\Sigma\). The diagonal entries are feature variances; off-diagonal entries describe within-class co-variation. QDA estimates a separate covariance for each class, allowing different spreads and orientations. With a positive-definite shared covariance, the term \(-\tfrac12 x^\top\Sigma^{-1}x\) is the same in every class score and cancels when scores are compared. The remaining pairwise boundary is linear. Different class covariances generally leave quadratic terms.
import numpy as np
from sklearn.discriminant_analysis import (LinearDiscriminantAnalysis as LDA,
QuadraticDiscriminantAnalysis as QDA)
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import cross_val_score
rng = np.random.default_rng(0)
n = 400
def make(equal_cov):
a = rng.multivariate_normal([0, 0], [[1, 0], [0, 1]], n)
cov_b = [[1, 0], [0, 1]] if equal_cov else [[6, 0], [0, 0.2]]
b = rng.multivariate_normal([2, 0], cov_b, n)
return np.vstack([a, b]), np.r_[np.zeros(n), np.ones(n)]
for equal, label in ((True, "equal covariance"), (False, "unequal covariance")):
X, y = make(equal)
print(f"{label:20s} LDA {cross_val_score(LDA(), X, y, cv=5).mean():.4f}"
f" QDA {cross_val_score(QDA(), X, y, cv=5).mean():.4f}"
f" logistic {cross_val_score(LogisticRegression(), X, y, cv=5).mean():.4f}")
# equal covariance LDA 0.8488 QDA 0.8488 logistic 0.8500
# unequal covariance LDA 0.7387 QDA 0.7937 logistic 0.7425
In the equal-covariance population, the optimal boundary is linear. The fitted models have similar CV accuracy here, but matching accuracy does not imply matching predictions or boundaries: finite-sample QDA estimates two different covariances and generally retains a quadratic boundary. On the unequal-covariance example, QDA scores 0.7937 against LDA’s 0.7387 and logistic regression’s 0.7425, gains of about 5.5 and 5.1 percentage points. The constructed Gaussian distributions have a quadratic optimal boundary, which matches QDA’s model family; one comparison does not establish a general advantage whenever covariances differ.
For \(K\) classes and \(p\) features, LDA estimates \(p(p+1)/2\) covariance entries and QDA estimates \(Kp(p+1)/2\). Both also need \(Kp\) means and, when estimated, \(K-1\) free class priors. At \(p=50,K=5\), QDA has 6,375 covariance entries. A centered class sample with \(m\leq p\) rows has a singular sample covariance; even \(m>p\) does not ensure good conditioning or full rank when features are redundant.
Regularization can stabilize covariance estimates. Shrinking class covariances toward a pooled estimate and shrinking toward an identity-based target are distinct choices, and can be combined in regularized discriminant analysis. Their effect depends on the target, strength, and solver; they do not simply remove the need to assess data support.
The relationship to logistic regression
Under shared-covariance Gaussian class distributions, Bayes’ rule yields linear log-odds, the same functional form used by logistic regression. LDA estimates class means, covariance, and priors from a joint model; logistic regression fits conditional probabilities, usually with regularization in software. The two methods need not estimate the same boundary on a finite dataset. Logistic regression does not specify the marginal distribution of the features, but it still assumes a form for the conditional log-odds.
A correct joint model can improve statistical efficiency by imposing useful structure. That does not guarantee higher finite-sample classification accuracy, especially when estimating covariance is difficult. If Gaussian assumptions fail, logistic regression may still be misspecified as well, depending on the actual conditional relationship. Ng and Jordan’s comparison in the references concerns particular generative and discriminative models; it is not a universal sample-size ranking for LDA, NB, and logistic regression.
References
- Ng, A. Y., & Jordan, M. I. (2001). On Discriminative vs. Generative Classifiers: A comparison of logistic regression and naive Bayes. NIPS.
- Friedman, J. H. (1989). Regularized Discriminant Analysis. Journal of the American Statistical Association.
- scikit-learn documentation. sklearn.discriminant_analysis.QuadraticDiscriminantAnalysis
Discover more from Insightful Data Lab
Subscribe to get the latest posts sent to your email.
