Linear discriminant analysis
| Problem | Find the projection that best separates labelled classes, maximising between-class scatter relative to within-class scatter; classify in that projection |
| Devised by | Ronald Fisher (1936), the linear discriminant; C. R. Rao (1948), several classes |
| Accuracy | The Bayes-optimal classifier when the classes are Gaussian with a shared covariance |
| Cost | : two scatter matrices, a Cholesky factorisation and a symmetric eigenproblem |
| Read first | Principal component analysis and kernel PCA |
| API | Lda (new(components), with_shrinkage, fit_labelled, transform, directions, eigenvalues); implements Classifier |
Overview
PCA looks for directions of large variance, but the variance may have nothing to do with the classes. Linear discriminant analysis (LDA) is the supervised counterpart. It looks for directions along which the class means are far apart relative to the spread within each class. With classes there are at most such directions, so LDA reduces the data to a few dimensions chosen for classification. The same model is a classifier: a Gaussian model with one covariance shared by all classes, whose decision boundaries are hyperplanes. It sits in this chapter as a dimensionality reduction method, though, unlike the others here, it needs labels.
Where it is used
Linear discriminant analysis finds the direction that best separates labelled classes.
- Classification and face recognition. Fisherfaces project face images onto the most discriminating directions.
- Dimensionality reduction for supervised problems. Unlike PCA, it uses the labels, so the few directions kept are the ones that matter for classification.
- Medicine and chemistry. Separating healthy from diseased samples, or compounds, from spectra.
History
Ronald Fisher (1936) introduced the linear discriminant to distinguish three species of iris from four measurements of their flowers, a data set still used as a first example. His aim was the linear combination of measurements that best separated two species. C. R. Rao (1948) extended it to several classes. The method became standard in statistics and pattern recognition, for example as “Fisherfaces” for face recognition (Peter Belhumeur, João Hespanha and David Kriegman, 1997).
The idea
Fisher’s criterion
For classes with points, means and overall mean , define the within-class and between-class scatter
Projected onto , the classes have between-class variance and within-class variance . Fisher maximised the ratio
whose stationary points satisfy the generalised eigenproblem . The eigenvalue measures how well the direction separates the classes. is a sum of rank-one terms whose weighted vectors sum to zero, so its rank is at most , and so is the number of useful directions. For two classes the solution is explicit: .
PCA against LDA
Two elongated classes lie side by side, offset across their long axis:
Figure 12.11. PCA and LDA directions.
The direction of greatest variance runs along both classes, and projecting onto it mixes them completely. LDA’s direction runs across them, where they differ, and separates them with little overlap. A method that discards labels can discard exactly the information a classifier needs.
Solving the generalised eigenproblem
The library reduces to an ordinary symmetric eigenproblem. Factor by Cholesky and substitute :
This whitens the within-class scatter: in coordinates , every class has identity within-class covariance, and LDA becomes PCA of the class
means. The directions are then normalised to unit length. When features are nearly collinear or there are more features than samples,
is singular, so a ridge (with_shrinkage, a fraction of the mean diagonal, by default) is added before factorising.
LDA as a classifier
If each class is Gaussian with mean and a covariance shared by all classes, Bayes’ rule gives the score
where is the prior probability of class . The quadratic terms in cancel between classes, so the boundaries are linear. With all directions kept, this is the same as choosing the nearest class mean in the projected space, measured in within-class standard deviations, with a log-prior adjustment. The library classifies this way, using the directions it keeps. On three overlapping classes in four dimensions:
Table 12.13. LDA as a classifier against other classifiers.
| classifier (450 training, 900 test points) | test accuracy |
|---|---|
| LDA classifier (2 discriminants) | 0.912 |
| LDA classifier (1 discriminant) | 0.850 |
| Gaussian naive Bayes | 0.911 |
| logistic regression | 0.914 |
LDA matches logistic regression here, as expected: the data are Gaussian with a shared covariance. Keeping only the first discriminant costs six points of accuracy.
Algorithm
Fit.
- Scatter matrices. Compute the mean of each class and the overall mean, and from them and . Add the ridge to the diagonal of .
- Whiten. Compute the Cholesky factor . Form by two sets of triangular solves, and replace by to remove the slight asymmetry that rounding introduces.
- Eigenvectors. Compute the eigenvectors of belonging to its largest eigenvalues, at most of them.
- Map back. Solve for each discriminant direction, normalise it to unit length, and fix its sign so that its largest entry is positive.
- Prepare the classifier. Store the projections of the class means onto the directions, the logarithms of the class priors, and the within-class variance along each direction.
Transform a point: take its dot product with each direction.
Classify a point: project it; for each class, compute the squared distance from the projected class mean, with each direction divided by its within-class variance; subtract twice the log prior; return the class with the smallest result.
Implementation
// Whiten: Sw = L Lᵀ, M = L⁻¹ Sb L⁻ᵀ (symmetric), directions w = L⁻ᵀ v.
let l = sw.cholesky(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("The within-class scatter is not positive definite (try more shrinkage)."))?;
let left = l.solve_triangular(UPLO::Lower, Diag::NonUnit, &sb).map_err(|_| ErrorsJSL::RuntimeError("Whitening failed."))?;
let m = l.solve_triangular(UPLO::Lower, Diag::NonUnit, &left.t().to_owned()).map_err(|_| ErrorsJSL::RuntimeError("Whitening failed."))?;
let m = (&m + &m.t()) * 0.5;
let (vals, vecs) = m.eigh(UPLO::Lower).map_err(|_| ErrorsJSL::RuntimeError("The eigendecomposition failed."))?;
let order: Vec<usize> = (0..p).rev().take(self.components).collect();
let lt = l.t().to_owned();
self.eigenvalues = order.iter().map(|&i| vals[i].max(0.0)).collect();
let mut dirs = R2D::zeros((p, self.components));
for (c, &i) in order.iter().enumerate() {
let v = vecs.column(i).to_owned();
let w = lt.solve_triangular(UPLO::Upper, Diag::NonUnit, &v).map_err(|_| ErrorsJSL::RuntimeError("Back-substitution failed."))?;
let norm = w.dot(&w).sqrt().max(1e-300);
let big = w.iter().copied().fold(0.0f64, |m, x| if x.abs() > m.abs() { x } else { m });
dirs.column_mut(c).assign(&(w * (big.signum() / norm)));
}
- The projected within-class covariance is diagonal by construction ( for ), so per-direction variances are enough for the classifier.
Ldalives with the reduction methods but implementsClassifier, so it can be used wherever a classifier is expected.
In practice
//! Linear discriminant analysis as a projection and as a classifier.
use lib_jsl_machine_learning::common::Classifier;
use lib_jsl_machine_learning::datasets::make_classification;
use lib_jsl_machine_learning::metrics::accuracy;
use lib_jsl_machine_learning::unsupervised::reduction::Lda;
fn main() {
let (x, labels) = make_classification(150, 2);
let (test, test_labels) = make_classification(300, 3);
let mut lda = Lda::new(2);
lda.fit(x.view(), &labels).unwrap();
println!("Fisher ratios {:.3?}", lda.eigenvalues());
println!("directions (columns):\n{:.3}", lda.directions());
let z = lda.transform(test.view()).unwrap();
println!("projected test data: {:?}", z.dim());
println!("test accuracy {:.3}", accuracy(&test_labels, &lda.predict(test.view()).unwrap()).unwrap());
}
Fisher ratios [4.255, 0.838]
directions (columns):
[[0.806, 0.061],
[-0.180, 0.978],
[-0.475, 0.140],
[0.303, -0.142]]
projected test data: (900, 2)
test accuracy 0.912
Strengths
- Supervised reduction to at most dimensions, chosen for separating the classes.
- A fast, closed-form classifier, optimal for Gaussian classes with a shared covariance, and robust with little data.
Weaknesses
- Linear boundaries only; classes with different covariances need quadratic discriminant analysis.
- Class means that coincide give no direction, even if the classes differ in spread.
- Needs shrinkage when features outnumber samples.
Exercises
- Show that the maximiser of for two classes is .
- Show that .
- Show that the eigenvectors of the generalised problem satisfy for .
- Derive the linear discriminant scores from Gaussian class densities with a shared covariance, and show that the boundaries are hyperplanes.
- For two classes, show that the LDA direction is proportional to the least-squares regression coefficients for a ±1 class indicator.
Hints and answers
- Maximise with : setting the gradient to zero gives .
- is a sum of rank-one terms whose weighted mean vectors satisfy , so the rank is at most .
- : multiplying by and by , and using the symmetry of both matrices, gives .
- For Gaussian densities with shared , the log density difference between classes is : linear in , so boundaries are hyperplanes.
- The normal equations for regressing a indicator on the centred features reduce to , whose solution is proportional to .
Further reading
- R. A. Fisher, “The use of multiple measurements in taxonomic problems”, Annals of Eugenics 7 (1936) 179–188.
- T. Hastie, R. Tibshirani and J. Friedman, The Elements of Statistical Learning, 2nd ed., Springer, 2009, section 4.3.
- P. N. Belhumeur, J. P. Hespanha and D. J. Kriegman, “Eigenfaces vs. Fisherfaces: recognition using class specific linear projection”, IEEE Transactions on Pattern Analysis and Machine Intelligence 19 (1997) 711–720.