By the end of this lecture, you should be able to:
obtain class probabilities from class densities and prior probabilities;
explain why a shared covariance matrix gives LDA a linear boundary;
estimate class means, priors, and pooled covariance from training data;
explain how QDA changes the boundary and the amount of data needed; and
distinguish training accuracy from test accuracy.
Classification basics
In Week 6, we separated estimating a class probability from making a class decision. Logistic regression models the probability of given . We then compare that probability with a cutoff to produce a class label. Discriminant analysis approaches the same classification problem by modeling the distribution of within each class.
Recall that a classifier is a decision rule
Here contains the predictor values. Under 0-1 loss, an incorrect decision costs one and a correct decision costs zero:
The risk is the expected loss on a new observation:
Write . To minimize the probability of an error, choose the more likely class. This gives the Bayes rule
When , either decision has an error probability of . The risk of this optimal rule is the Bayes risk. As we saw in Week 6, even the best decision can make mistakes because the class distributions overlap.
The Bayes rule
The idea of discriminant analysis is to estimate the density of the predictors within each class, then compare those densities at a target . How does this give the class probability we need?
Let and be the prior probabilities. Let and be the conditional densities of in the two classes. Bayesβ rule gives
The denominators are the same. Therefore, is equivalent to , and
Both the prior and the density matter. A common class can still be unlikely at a particular predictor value. For continuous predictors, is a density, not the probability of observing exactly .
This suggests a different route to classification: model given , then use Bayesβ rule to obtain given .
Example: linear discriminant analysis (LDA)
We start with two normal distributions that have the same covariance matrix. For this example, label the classes 1 and 2:
where
The class priors are and . We generate 400 observations from class 1 and 600 from class 2. Before fitting a rule, notice the similar shapes and different centers of the two clouds.
The R and Python simulations use the same model and settings, with different random draws. Run the code blocks in your chosen language in order. The real-data examples later in the lecture use the same supplied observations in both languages.
The overlapping observations remind us that a decision boundary cannot separate the classes perfectly. LDA will estimate one center per class and one covariance matrix shared by the classes.
Linear discriminant analysis
Now allow classes, labeled . Bayesβ rule becomes
The best decision under 0-1 loss chooses the largest posterior probability. Because the denominator is common to all classes, this is
Linear discriminant analysis (LDA) models the class densities as multivariate normal distributions with different means and a common covariance matrix:
Thus
Taking a logarithm preserves the ordering of positive quantities. After dropping a term that is the same for every class, the maximum a posteriori (MAP) decision compares
The first term favors a class whose center is close to , after accounting for covariance. The second favors a class with a larger prior probability. These are comparison scores, not probabilities. We can also normalize the fitted values to obtain posterior probabilities, just as in Bayesβ rule above.
Estimating parameters in LDA
From the training data, estimate the following quantities:
Prior probabilities: , where is the number of observations in class .
Class means:
Pooled covariance:
Pooling combines the variation within each class. Center each class at its own mean before combining the residuals. Otherwise, the separation between class means would become part of the covariance estimate.
Letβs estimate these quantities from the simulated data. The 300 points called X_grid are new predictor locations for displaying the fitted decisions. They have no outcomes, so this plot does not estimate test error.
fig, ax = plt.subplots(figsize=(7, 6))for label, color in [(1, "darkorange"), (2, "deepskyblue")]: rows = decision == label ax.scatter(X_grid[rows, 0], X_grid[rows, 1], s=22, color=color, label=f"Predict class {label}")ax.set(xlim=(-4, 4), ylim=(-4, 4), xlabel=r"$x_1$", ylabel=r"$x_2$", title="Decisions from the distance scores")ax.legend(frameon=False)fig.tight_layout()plt.show()
The fitted decisions appear to be separated by a straight line. Why does comparing two quadratic distance expressions produce a linear boundary?
The linear decision rule
The expression is the squared Mahalanobis distance from to the class center. It accounts for predictor scale and correlation. With equal priors, LDA chooses the closest center in this distance. When , it reduces to squared Euclidean distance, connecting LDA to the distance comparisons used by KNN.
Expand the score:
The first term does not depend on , so it cancels when we compare classes. Write the remaining linear discriminant score as
For two classes and , equal scores give the boundary
This is a line with two predictors and a hyperplane with more predictors. Changing the priors changes the intercepts, so it can move the boundary even when the means and covariance remain fixed.
There is also a connection to logistic regression. Under the two-class LDA model, the difference between the scores is the log posterior odds:
Both LDA and logistic regression give linear log odds. LDA estimates them through the class means, shared covariance, and priors; logistic regression fits the conditional probabilities directly. Their fitted probabilities need not be the same. Equal LDA scores correspond to a posterior probability of . As in Week 6, we can use other cutoffs on the fitted probability of the positive class and evaluate the resulting decisions with a confusion matrix or ROC curve.
The next figure returns to the true means, covariance, and priors of our simulation. Each contour joins points with the same weighted density, . The black boundary shows where the two weighted densities are equal.
The density contours are curved, but the class boundary is straight. It is the difference between the two log scores that becomes linear when the covariance matrices are shared.
The same weighted densities appear below as rotatable 3D surfaces. Where they overlap, the higher surface is visible. The change from orange to blue shows the decision boundary.
LDA example continued
We can calculate the fitted and directly. This must give the same decisions as the distance calculation. We reuse the same X_grid points so that only the formula changes.
The two formulas agree. The linear form is convenient for prediction, while the distance form explains why class means, covariance, and priors all enter the rule.
Example: quadratic discriminant analysis (QDA)
What changes when each class has its own covariance matrix? Keep the same true means and priors, but change the second covariance to
The two clouds now tilt in different directions. Quadratic discriminant analysis (QDA) allows this by modeling . Its comparison score is
The quadratic terms need not cancel across classes, so the boundary can curve. The determinant term must also be kept because covariance matrices can have different volumes. In this particular example the two determinants happen to be equal; the different covariance directions are enough to produce a curved boundary.
The 3D view shows how changing the second class covariance changes the shape of its density surface. The color transition now curves.
The means and priors have not changed. The curved boundary comes from allowing the covariance matrices to differ. To fit QDA, replace the pooled covariance with a sample covariance calculated separately in each class:
This flexibility comes with more quantities to estimate. It may reduce bias when the class shapes differ, but it can increase variance when there are few observations in each class. We will see an extreme case in the digit example.
Example: South African heart data
We use the South Africa heart disease data from ElemStatLearn. The response chd has two classes, 0 and 1. The other nine variables are predictors. famhist records whether a family history is present; we code it as a single indicator, with Absent as the reference level.
Download the course copy of saheart.csv into data/classification. Run the code from the folder containing data. Both language versions use the same rows and variables.
First fit LDA and inspect its training confusion matrix and accuracy. As in Week 6, rows show observed classes and columns show predicted classes.
These are in-sample accuracies: the same observations were used to estimate the model and evaluate its decisions. They describe the fitted classifications, but do not establish which method predicts better on new observations. That comparison requires validation or test data, just as it did for KNN and logistic regression.1
Practice question
The iris data contain three classes, setosa, versicolor, and virginica, and four flower measurements. Use all four measurements to fit QDA. What is the in-sample accuracy? Which classes are confused with one another?
Use the supplied iris.csv, which contains the original R dataset, in both languages.
Return to the ZIP digit data from the KNN lectures. Each image has pixel values, and the first column contains its digit label. The files already have separate training and test observations.
We use 100 randomly selected images per digit from each split, giving 1,000 training and 1,000 test images. The supplied sample indices give R and Python exactly the same samples. row_id counts rows starting at 1 within the corresponding data file.
The original training data and test data have no column headers. Keep them in data/knn and the sample indices in data/discriminant-analysis. We use the supplied pixel values without standardization.
Unlike the heart and iris calculations, this is a test error. The test labels were not used to estimate the class means, priors, or covariance. Inspect the confusion matrix to see which digits account for the mistakes.
Practice question
Would ordinary QDA work with these training data? Each class contains 100 images, but each image has 256 predictors. What does this imply about the rank of a class covariance matrix?
After subtracting the class mean, the rank is at most . A class covariance matrix is therefore singular and has no inverse. Ordinary QDA cannot estimate an invertible covariance matrix for these data. Depending on the software version, fitting may fail or produce a warning and a result based on its treatment of singular directions.
LDA pools information from all 1,000 training images. Its covariance matrix has rank at most . There are enough within-class degrees of freedom for it to have full rank, so the same dimension argument does not force it to be singular. This example makes the cost of QDAβs extra flexibility concrete: estimating a separate covariance requires enough information within each class.
Check your understanding
Why do both the class prior and the class density enter the Bayes decision?
Which term cancels when LDA compares two classes, and why does it fail to cancel in QDA?
Why must the pooled covariance be calculated after centering within each class?
Why can LDA fit the digit example when ordinary QDA has singular covariance estimates?
Key ideas
Discriminant analysis models the predictors within each class and uses Bayesβ rule to classify new observations.
LDA shares a covariance matrix. Its quadratic terms cancel in class comparisons, giving linear boundaries.
QDA estimates a covariance matrix for each class, allowing curved boundaries but requiring more data.
A fitted log score is not a posterior probability. The scores give the same class ordering; exponentiating and then normalizing the log scores gives posterior probabilities.
Training accuracy describes the fitted sample. Separate test observations are needed to assess prediction on new data.