Chapter 24 of 42 · ~25 min read & lab+65 XP
Chapter 24 · Machine Learning

Probabilistic & Generative Classifiers: Naive Bayes, LDA & QDA

Generative vs. Discriminative modeling, Multinomial & Gaussian Naive Bayes, Laplace smoothing, log-sum-exp stability, and Linear vs. Quadratic Discriminant Analysis.

What Is It?

Generative classifiers (Naive Bayes, LDA, QDA) model how each class generates its features P(x|y) and apply Bayes' theorem to infer the class probability P(y|x).

Why Is It Required?

They train in milliseconds, shine on small datasets and high-dimensional text (spam/sentiment), and handle missing features gracefully.

Everyday Analogy: Identifying a mystery fruit by comparing its weight and color against your mental profile of apples vs. oranges, then weighing how common each fruit is.
Why ML Engineers & Data Scientists Actually Need This

Generative classifiers are blazingly fast, shine on tiny datasets, and teach the probabilistic backbone behind modern AI!

ML / AI Engineer

Multinomial Naive Bayes trains on millions of text documents in milliseconds with O(N·d) counting — making it the ultimate ultra-low-latency spam/intent baseline before spinning up a GPU transformer.

Data Scientist

Understanding Generative vs. Discriminative tradeoffs (Ng & Jordan 2002: Naive Bayes beats Logistic Regression at small N, Logistic Regression wins at large N) shows deep statistical maturity.

Interview & Debug Edge

Interviewers frequently ask: 'If features are correlated, why does Naive Bayes still achieve high classification accuracy even though its probabilities are badly calibrated?'

Step 0 · Test Your Gut Before Any Math!

In a spam filter using Naive Bayes WITHOUT smoothing (α = 0), an email contains 'FREE', 'WINNER', and one brand-new word 'CRYPTO2026' that never appeared in spam training data. What is the predicted P(Spam | email)?

What You Will Master in This Chapter
  • Distinguish Generative models P(X|y)P(y) from Discriminative models P(y|X)
  • Derive Naive Bayes under conditional independence and explain why it still ranks well despite 'naive' assumptions
  • Prevent zero-frequency collapse with Laplace smoothing (+α) and numeric underflow with log-probabilities
  • Compare Multinomial, Bernoulli, and Gaussian Naive Bayes for text vs. continuous data
  • Derive why shared covariance Σ in LDA produces a linear boundary while class-specific Σ_k in QDA produces a quadratic boundary
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 4
P(X|y)Say aloud:“Class-conditional likelihood”
Plain-English Meaning
How likely are these features given class y?
Everyday Example
Class-conditional likelihood
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Discriminative classifiers (like Logistic Regression) only learn the fence separating cats from dogs. Generative classifiers (like Naive Bayes, LDA, QDA) learn a full statistical blueprint of what a cat looks like P(X | cat) and what a dog looks like P(X | dog) — and then use Bayes' Rule to ask which blueprint best explains a new photo!

1. Generative vs. Discriminative Classifiers (Ng & Jordan Tradeoff)

Everyday Story First (Zero Math Yet!)

If you only have 40 training rows, Logistic Regression can easily overfit a crazy hyperplane. Naive Bayes makes a strong structural assumption (conditional independence), which gives it higher bias but much lower variance — so it converges in O(log⁡d)O(\log d) samples vs. O(d)O(d) for Logistic Regression!

Generative vs. Discriminative ClassifiersGenerative: Learn P(X | y) & P(y)Naive Bayes, LDA, QDA, GMMGreat with small N; uses Bayes' Rule!Discriminative: Learn P(y | X) DirectlyLogistic Regression, SVM, XGBoost, Neural NetsFewer assumptions; wins with large N!
Generative models (Naive Bayes, LDA) model P(X|y)P(y) and can sample data; Discriminative models (Logistic Regression) directly model P(y|X).

Bayes' Rule in Log-Space

y^=arg⁡max⁡y  log⁡P(y)⏟Prior+∑j=1dlog⁡P(xj∣y)⏟Conditional Independence\hat{y} = \arg\max_y \; \underbrace{\log P(y)}_{\text{Prior}} + \sum_{j=1}^d \underbrace{\log P(x_j \mid y)}_{\text{Conditional Independence}}

  • Why logs? Multiplying 500 small word probabilities (10−4)500=10−200010^{-4})^{500} = 10^{-2000} underflows IEEE-754 float64 to exact 0.0! Adding log-probabilities stays numerically rock-solid.

2. Naive Bayes Variants & Laplace Smoothing Live

Everyday Story First (Zero Math Yet!)

Pick the likelihood family matching your data: Multinomial NB for word counts/TF-IDF, Bernoulli NB for binary word presence, and Gaussian NB for continuous numeric features. Toggle words and flip α = 0 vs α = 1 below to see Laplace smoothing rescue an email!

Zero-Frequency Collapse vs. Laplace Smoothing (+α) & Log-ProbabilitiesWithout Smoothing (α = 0)P(FREE|S) · P(WIN|S) · P(crypto|S)0.80 × 0.70 × 0.00 = 0!One unseen word wipes out all evidence!With Laplace Smoothing (α = 1) + LogsP(w|y) = (count + α) / (N_y + α·|V|)log P(y) + Σ log P(wᵢ | y)Zero probability impossible + no underflow!
Zero-frequency collapse: one unseen word multiplies the entire Naive Bayes product by 0 unless Laplace smoothing (+α) adds pseudo-counts.

Laplace (Additive) Smoothing Formula

P(wj∣y)=count(wj,y)+α∑v∈Vcount(wv,y)+α∣V∣P(w_j \mid y) = \frac{\text{count}(w_j, y) + \alpha}{\sum_{v \in V} \text{count}(w_v, y) + \alpha |V|}

  • Why Naive Bayes still classifies well with correlated features: Even if two duplicate features double-count the log-odds (pushing predicted probabilities toward extreme 0.001 or 0.999 — poor calibration!), the argmax class often remains completely unchanged!
Interactive Mini-Lab • Naive Bayes + Laplace Smoothing

Toggle Email Words & Watch Unseen-Word Collapse Disappear

Posterior P(Spam | words):
60.6% → SPAM

3. Linear vs. Quadratic Discriminant Analysis (LDA vs. QDA)

Everyday Story First (Zero Math Yet!)

Gaussian Naive Bayes assumes features are uncorrelated (diagonal covariance matrix). What if features ARE correlated? Model each class as a Multivariate Gaussian N(μk,Σk)\mathcal{N}(\mu_k, \Sigma_k)! Share one Σ\Sigma across all classes → LDA (linear boundary). Give each class its own Σk\Sigma_k → QDA (curved quadratic boundary)!

LDA (Shared Σ → Linear Boundary) vs. QDA (Per-Class Σ_k → Curved Boundary)LDA: Σ₀ = Σ₁ = Σ (Low Variance)QDA: Σ₀ ≠ Σ₁ (More Flexible, More Params)
LDA shares one covariance matrix Σ across classes (linear boundary); QDA learns class-specific Σ_k (curved quadratic boundary).

Why the x² Term Cancels in LDA (Interview Favorite!)

Comparing log-posteriors of two Gaussians N(μ0,Σ0)\mathcal{N}(\mu_0, \Sigma_0) and N(μ1,Σ1)\mathcal{N}(\mu_1, \Sigma_1):

  • In LDA (Σ0=Σ1=Σ\Sigma_0 = \Sigma_1 = \Sigma): the quadratic term −12x⊤Σ−1x-\frac{1}{2} x^\top \Sigma^{-1} x appears identically in both classes and cancels out, leaving a purely linear decision boundary!
  • In QDA (Σ0≠Σ1\Sigma_0 \ne \Sigma_1): the x⊤Σk−1xx^\top \Sigma_k^{-1} x terms do NOT cancel, creating a parabola/ellipse/hyperbola boundary — at the cost of estimating K⋅d(d+1)2K \cdot \frac{d(d+1)}{2} covariance parameters (high variance when dd is large!).
“Wait, I'm Confused...” · Teacher Office Hours Q&A

The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.

Naive Bayes blindly multiplies that feature's likelihood 5 times, making its probabilities wildly overconfident! Regularized Logistic Regression simply splits the weight across the 5 copies (w/5 each) and stays well-calibrated.

Interactive Visual Lab
Lab Challenge: In the LDA vs. QDA Lab below, switch to QDA and drag Class 1 spread σ₁ up to 2.4 to watch a second decision crossing appear — something linear LDA can never capture!
Flagship Deep Lab • LDA vs. QDA Covariance Geometry

Shared Variance (LDA) vs. Class-Specific Variance (QDA)

Boundary x=4.3

LDA forces one pooled variance σ, so the x² terms cancel out and you ALWAYS get a single linear boundary!

Intuition Takeaway: Generative classifiers model P(X|y)P(y): use Laplace smoothing + log-space for Naive Bayes, and remember LDA's shared Σ yields a low-variance linear boundary while QDA's class-specific Σ_k yields a flexible quadratic boundary.
Where This Powers Real ML, Deep Learning & Generative AI

Ultra-Fast Text & Spam Filtering

Multinomial Naive Bayes + TF-IDF trains in milliseconds on 100k+ vocabulary features.

Small-Sample Medical Diagnostics

LDA excels when N is small and Gaussian class-conditionals roughly hold.

Real-Time Streaming Baselines

Naive Bayes supports exact online updates (partial_fit) by simply incrementing counts.

Production NumPy & PyTorch Code Patterns
from sklearn.naive_bayes import MultinomialNB, GaussianNB
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis, QuadraticDiscriminantAnalysis

# Text / count features with Laplace smoothing (alpha=1.0)
nb_text = MultinomialNB(alpha=1.0)

# Continuous correlated features: LDA (shared Sigma) vs QDA (separate Sigma_k)
lda = LinearDiscriminantAnalysis()
qda = QuadraticDiscriminantAnalysis(reg_param=0.05)  # mild shrinkage prevents singular Sigma_k
lda.fit(X_train, y_train)
qda.fit(X_train, y_train)
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Using Gaussian Naive Bayes on sparse bag-of-words text counts.
Best Practice: Use MultinomialNB (or ComplementNB for imbalanced text); GaussianNB assumes symmetric bell curves.
Trap #2: Trusting Naive Bayes probabilities directly for cost-sensitive bidding.
Best Practice: Conditional independence violations push NB probabilities toward 0 and 1; apply Platt or Isotonic calibration first!
Trap #3: Running QDA when d > n_k (more features than samples in a class).
Best Practice: Class covariance Σ_k becomes singular (non-invertible); use LDA or regularized QDA (reg_param > 0).
Chapter Mastery Check (+65 XP)
Score: 0 / 5
1What problem does Laplace smoothing (+α) solve in Multinomial Naive Bayes?
2Why do we sum log-probabilities instead of multiplying raw probabilities in Naive Bayes?
3When does Naive Bayes typically outperform Logistic Regression?
4How many covariance parameters does QDA estimate for K classes in d dimensions?
5Which assumption makes Naive Bayes 'naive'?

Apply What You Learned — Solve Matching Coding Problems