Skip to content

Naive Bayes, LDA and QDA

Model each class as a distribution, then apply Bayes' rule. Three strong baselines that differ in one assumption, about how features vary within a class.

Applied ~11 min8 steps

What runs in CodeSplash

You will be able to

  • Explain classifying by class-conditional distributions and Bayes' rule
  • Tell naive Bayes, LDA and QDA apart by their covariance assumption
  • Choose among them from the number of rows and features

Read first

01

Model the classes, then flip

Read

Instead of drawing a boundary directly, describe what each class looks like. Then use Bayes' rule for a new row:

P(c∣x)∝P(c) p(x∣c)P(c \mid x) \propto P(c)\,p(x \mid c)

All three learners here model p(x∣c)p(x \mid c) as Gaussian. They differ only in the covariance they allow:

LearnerCovarianceBoundary
Naive BayesNaive BayesClassifies with Bayes' rule, treating features as independent within each class.Diagonal, per classCurved
LDADiscriminant analysisModels each class as a Gaussian. LDA shares one covariance, for straight boundaries. QDA has one per class, for curves.One shared, fullStraight
QDAOne full per classCurved
02

Who wins on penguins?

Predict

Predict first

Three species, with body measurements that are roughly Gaussian within each species. Compare cross-validated log loss for a random forest, a decision tree and LDA. Lower is better. Which wins?

Random forestDecision treeLinear discriminant analysis
Reveal

LDA, by a distance: 0.0242, against 0.0833 for the forest and 0.429 for the tree. When the data looks like the model's assumption, a simple model with few parameters is hard to beat.

03

Count the parameters

Read

With pp features and KK classes, what must be estimated?

  • Naive Bayes: KK means and variances for each feature, so 2pK2pK.
  • LDA: the means, plus one covariance matrix of p(p+1)/2p(p+1)/2 entries.
  • QDA: the means, plus KK matrices.

With p=20p = 20 and K=3K = 3, QDA estimates 630 covariance entries, LDA 210 and naive Bayes 60 variances. That's why QDA's flexibility needs rows, and Covariance shrinkage or Regularization can rescue it.

04

See the boundaries

Explore

Naive Bayes draws curved boundaries, even though it assumes features are independent within a class. Try it on Two blobs, then on Checkerboard (XOR). Why does the checkerboard defeat it?

DExplorable · Decision boundary zoo

What shapes of boundary can each kind of model draw?

Which model will score highest on new data from this shape?

How sure?

Data

Model

5

k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.

0.20
150
Simulating…

Commit your prediction above to see the result

Make your prediction first; the figure appears when you commit.

Make your prediction to see the result.

In a checkerboard, each class's marginal looks the same on both axes. Without modeling how the axes relate, there's nothing to see.

05

Wrong but useful

Read

"Features are independent within a class" is rarely true. Naive Bayes still often ranks well: on Pima its AUC is 0.845. LDA with shrinkage reaches 0.859, and QDA on three features 0.828.

The ranking survives, but the probabilities don't: naive Bayes counts correlated evidence twice, so its probabilities pile up near 0 and 1. Check calibration before using them as probabilities.

06

Check your understanding

Checkpoint

Check yourself

What does the "naive" in naive Bayes assume?

Show the answer

Answer: b

Given the class, one feature tells you nothing about another. That's what makes it so fast and so frugal with rows.

Check yourself

A naive Bayes model has a good AUC, but its predicted probabilities are often near 0 or 1. Why?

Show the answer

Answer: b

Ranking and calibration are separate properties. A recalibration step can fix the probabilities without changing the order.

Check yourself

With p=10p = 10 features and K=3K = 3 classes, how many distinct covariance entries does QDA estimate in total?

Show the answer

Answer: 165

Each matrix has p(p+1)/2=55p(p+1)/2 = 55 entries. Three of them make 165, where LDA needs only 55.

Check yourself

You have 60 rows, 40 features and 2 classes. Which is the most reasonable to try first?

Show the answer

Answer: a

With so few rows per feature, the full covariance can't be estimated. Diagonal or shrunk covariances can.

07

Train all three

In the app

In the Learners step, select Naive Bayes (Gaussian) and Discriminant analysis (LDA / QDA). Method switches between LDA and QDA, and Class priors can use the data's shares or equal priors. Both run the same computation in Python and R, so their posteriors agree exactly.

Python
import pandas as pd
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis as QDA
from sklearn.model_selection import StratifiedKFold, cross_val_score
from sklearn.naive_bayes import GaussianNB

df = pd.read_csv("penguins.csv").dropna(subset=["bill_len", "bill_dep", "flipper_len", "body_mass"])
X, y = df[["bill_len", "bill_dep", "flipper_len", "body_mass"]], df["species"]
cv = StratifiedKFold(5, shuffle=True, random_state=1)
for name, m in [("nb", GaussianNB()), ("lda", LDA()), ("qda", QDA())]:
    print(name, -cross_val_score(m, X, y, cv=cv, scoring="neg_log_loss").mean().round(3))
R
df <- na.omit(read.csv("penguins.csv")[, c("species", "bill_len", "bill_dep", "flipper_len", "body_mass")])
df$species <- factor(df$species)
logloss <- function(p, y) -mean(log(pmax(p[cbind(seq_along(y), as.integer(y))], 1e-15)))
set.seed(1)
fold <- sample(rep(1:5, length.out = nrow(df)))
cv <- function(fit_fn) mean(sapply(1:5, function(k) {
  logloss(fit_fn(df[fold != k, ], df[fold == k, ]), df$species[fold == k])
}))
c(nb = cv(function(tr, te) predict(e1071::naiveBayes(species ~ ., tr), te, type = "raw")),
  lda = cv(function(tr, te) predict(MASS::lda(species ~ ., tr), te)$posterior),
  qda = cv(function(tr, te) predict(MASS::qda(species ~ ., tr), te)$posterior))
08

Recap

Recap
  • These learners model each class, then use Bayes' rule.
  • They differ in covariance: diagonal, shared or per class. Rows decide how much you can afford.
  • They can rank well on wrong assumptions, but check the probabilities.

Concepts in this lesson