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.
What runs in CodeSplash
- Naive Bayes (Gaussian) Verified in Python and R
- Discriminant analysis (LDA / QDA) Verified in Python and R
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
Model the classes, then flip
ReadInstead of drawing a boundary directly, describe what each class looks like. Then use Bayes' rule for a new row:
All three learners here model as Gaussian. They differ only in the covariance they allow:
| Learner | Covariance | Boundary |
|---|---|---|
| Naive BayesNaive BayesClassifies with Bayes' rule, treating features as independent within each class. | Diagonal, per class | Curved |
| LDADiscriminant analysisModels each class as a Gaussian. LDA shares one covariance, for straight boundaries. QDA has one per class, for curves. | One shared, full | Straight |
| QDA | One full per class | Curved |
Who wins on penguins?
PredictPredict 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?
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.
Count the parameters
ReadWith features and classes, what must be estimated?
- Naive Bayes: means and variances for each feature, so .
- LDA: the means, plus one covariance matrix of entries.
- QDA: the means, plus matrices.
With and , 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.
See the boundaries
ExploreNaive 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?
Data
Model
k for neighbors, depth for trees, γ × 2 for the kernel, hidden units for the network.
Commit your prediction above to see the result
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.
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.
Check your understanding
CheckpointCheck 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 features and classes, how many distinct covariance entries does QDA estimate in total?
Show the answer
Answer: 165
Each matrix has 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.
Train all three
In the appIn 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.
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))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))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