Gaussian discriminant analysis and naive Bayes

Gaussian naive Bayes, LDA and QDA learned one sample at a time: class ellipses, posteriors, linear and quadratic boundaries, and 3D probability hills, matching scikit-learn.

Updated

  • Generative versus discriminative models
  • Bayes' rule
  • Shared versus per-class covariance
  • Why naive Bayes is naive
  • Linear and quadratic boundaries
n = 9n = 15n = 30n = 60n = 120n = 180P(c | x) ∝ P(c)·N(x; μ, Σ)
Preparing the lab…

Intuition

First describe what each class looks like

Discriminative methods (logistic regression, SVMs) learn the boundary directly. Generative methods work the other way round: first describe what each class looks like — where it sits and what shape it spreads into — then ask which class a new point resembles most. Described by a normal distribution, each class is an ellipse: its centre is the mean, its shape and orientation come from the covariance.

The three small labs below add training samples one at a time and update each class's estimates online. The background is the posterior (class colours blended by posterior), solid ellipses are at Mahalanobis distance 1 and dashed ones at 2.

Three classes, QDAPreparing…
Nested, LDAPreparing…
Nested, QDAPreparing…

In the first, the three classes each have their own orientation; QDA draws each its own ellipse and reaches 97.2% training accuracy.

The second and third use "nested" data: one class huddles tightly in the middle, the other spreads widely around it, and both have the same centre. LDA forces the two classes to share a covariance, so it gets two identical ellipses — and with coinciding centres it can hardly tell them apart: 53.3%, little better than guessing. QDA gives the outer class a large ellipse and the inner class a small one, the boundary becomes a ring, and accuracy is 87.2%.

Math

Bayes' rule

P(c∣x)=P(c) p(x∣c)∑c′P(c′) p(x∣c′),p(x∣c)=N(x; μc,Σc)P(c \mid x) = \frac{P(c)\,p(x \mid c)}{\sum_{c'} P(c')\,p(x \mid c')}, \qquad p(x \mid c) = \mathcal N(x;\,\mu_c, \Sigma_c)

Taking logs, compare for each class

log⁡P(c)−12(x−μc)⊤Σc−1(x−μc)−12log⁡∣Σc∣+const\log P(c) - \tfrac12 (x-\mu_c)^\top\Sigma_c^{-1}(x-\mu_c) - \tfrac12\log|\Sigma_c| + \text{const}

The second term is the squared Mahalanobis distance: distance measured in the shape of that class. In practice the maximum is subtracted before the softmax to avoid exponential underflow.

Three estimates

ncn_c is the number of samples in class cc, Sc=∑i∈c(xi−μc)(xi−μc)⊤S_c = \sum_{i\in c}(x_i - \mu_c)(x_i - \mu_c)^\top its scatter matrix, and the prior is P(c)=nc/nP(c) = n_c/n:

ModelCovarianceBoundaryParameters per class (2D)
Naive Bayesdiag(Sc)/nc+ε\mathrm{diag}(S_c)/n_c + \varepsilonQuadratic (axis-aligned)2 variances
LDAΣ=∑cSc/n\Sigma = \sum_c S_c / n (shared)Straight line3 shared
QDAΣc=Sc/nc\Sigma_c = S_c / n_cQuadratic3

LDA's boundaries are straight because the quadratic term x⊤Σ−1xx^\top\Sigma^{-1}x is the same for every class and cancels in the comparison.

Online estimation

Each lab step adds one sample, and Welford's algorithm updates the mean and scatter matrix:

μ←μ+x−μn,S←S+(x−μold)(x−μnew)⊤\mu \leftarrow \mu + \frac{x - \mu}{n}, \qquad S \leftarrow S + (x - \mu_{\text{old}})(x - \mu_{\text{new}})^\top

This is far more stable numerically than "sum of squares minus the square of the mean". QDA needs at least 3 samples per class before its covariances have full rank: with the default data there is no model for the first 8 samples and there is one from the 9th; after only 20 samples the accuracy is already 94.4%.

Beyond accuracy: are the probabilities right?

On the "Correlated" data all three models reach 100% training accuracy, but their log loss differs widely:

ModelAccuracyLog loss
Naive Bayes100%0.136
LDA100%0.0016
QDA100%0.0036

With two strongly correlated features, naive Bayes counts them as two independent pieces of evidence, and its ellipses can only follow the axes, so its probabilities are off — the classifications are right but the confidence is wrong.

How it is computed, with real numbers

Once the lab above has loaded, this panel works through the same formulas with its current numbers.

Experiment

Follow the lesson

Course

Lesson 1: three assumptions for generative classification

5 steps · each one: set up and run → look → answer

  1. 1. Samples arrive one by one

    Default three classes with QDA; add just 20 samples.

    Why is there no model for the first few steps?
  2. 2. Add them all

    Add all 180 samples and open the "Likelihoods" tab.

    Why do the classes' ellipses point in different directions?
  3. 3. A shared covariance

    Switch to LDA.

    Why have all the boundaries become straight lines?
  4. 4. Nested data

    Switch to "Nested", still with LDA.

    Why only 53.3%?
  5. 5. The price of naivety

    "Correlated" data with naive Bayes. Look at the log loss on the right.

    Accuracy is 100%, so why is the log loss more than 80 times LDA's?

Try these settings

Naive Bayes also reaches 87.2% on the nested data: both classes are circular (no correlation), so the independence assumption happens to hold and it behaves almost exactly like QDA.

Exercises

Exercises

Exercise 1: separate inside from outside

LDA gets only 53.3% on the nested data. Change the model and, after adding every sample, reach at least 87% accuracy.

Hint

QDA and naive Bayes both give 87.2%: the classes differ in their variances, so each needs its own covariance.

  • Training accuracy ≥ 87.0%

Exercise 2: give trustworthy probabilities

On the correlated data naive Bayes is 100% accurate but its log loss is 0.136. Change the model to bring the log loss to 0.01 or below.

Hint

LDA gives 0.0016 and QDA 0.0036 — both estimate the off-diagonal covariance terms.

  • Log loss ≤ 0.010

Quiz

Why are LDA's decision boundaries straight lines?
What is “naive” about naive Bayes?
With 2D data and 3 classes, how many covariance parameters does QDA estimate?

Further reading

Frequently asked questions

What is the difference between LDA and QDA?

LDA assumes all classes share one covariance matrix, so its decision boundaries are straight lines (hyperplanes); QDA gives each class its own covariance, so its boundaries are quadratic curves. QDA is more flexible but has many more parameters (d(d+1)/2 per class), so with few samples LDA is often more stable.

How is Gaussian naive Bayes related to LDA and QDA?

All three are Gaussian generative models. Naive Bayes is QDA restricted to diagonal covariances: each class has its own variances, but correlations between features are ignored.

What is the difference between generative and discriminative models?

Generative models (the three on this page) model p(x | c) and P(c), then use Bayes' rule for the posterior; discriminative models (logistic regression, SVMs) learn P(c | x) or the boundary directly. When their assumptions hold, generative models are sample-efficient and can also generate samples or handle missing values; when they fail (LDA on nested data, for instance) they can do very badly.

Is LDA also a dimensionality-reduction method?

Yes. Linear discriminant analysis also names the projection onto K − 1 dimensions that maximises between-class spread relative to within-class spread (Fisher's discriminant); the classifier and the reduction use the same discriminant directions.

Can I use it if the data are not normally distributed?

Yes, but the probabilities may be off. In practice LDA and naive Bayes often still work well on non-normal data; when a class is multimodal, model each class with a Gaussian mixture instead.

Further reading