Linear and Quadratic Discriminant Analysis › Formula
Machine Learning from ScratchAll chapters Linear and Quadratic Discriminant Analysis › FormulaSection view · Sections in this chapter4 / 10 ↓
Reading tools Definitions, links & notes
Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.
Article links
Make inline references clickable
We first combine Gaussian class densities with Bayes' rule, then examine which score terms cancel under a shared covariance. This separates the population decision rule from the covariance estimates and numerical calculations used to fit it.
Gaussian class models and Bayes decision rules
A discriminant classifier begins with a generative thought experiment. Imagine that nature first chooses a class according to its prior probability, and then draws a feature vector from a probability density that belongs to that class. To classify a new observation, we reverse the order of that story: instead of asking "what does class tend to look like?", we ask "how plausible is this particular under each class, after accounting for how common each class is?" That reversal is Bayes' rule, and the entire geometry of LDA and QDA follows from the density we choose.
The first modeling decision is therefore to describe each class by a full density rather than by a single prototype. An ordinary Euclidean nearest-centroid rule scores a point by its Euclidean distance from a class mean, so equal-length displacements have equal distance scores regardless of direction. A class density can instead describe one direction as tightly concentrated and another as broad or tilted. The multivariate Gaussian is the canonical choice for this job. It is specified by a center and a covariance, its level sets are ellipsoids, and its log-density is quadratic, which is exactly what makes the later decision rules tractable. We assume
where denotes the multivariate normal density
where:
- : the mean vector of the Gaussian, which locates the center of the ellipsoidal cloud
- : the covariance matrix, which sets the shape and orientation of the cloud
- : the covariance determinant; its square root is proportional to the volume of an ellipsoid with fixed Mahalanobis radius
- : the squared Mahalanobis distance from to
- : the number of feature dimensions
The mean locates the center of a class cloud, and the covariance determines its shape and orientation. For ellipsoids with the same Mahalanobis radius, volume is proportional to . A larger determinant therefore means a larger such ellipsoid and a lower Gaussian peak density. The quadratic form is the squared Mahalanobis distance. It measures distance relative to the class covariance, so a large Euclidean displacement along a broad direction can still have a small standardized distance. The density decreases continuously with this distance. There is no single hard neighborhood boundary built into the Gaussian model.
A density alone is not yet a classifier, because classes may occur with different frequencies. Bayes' rule combines the class-conditional density with the prior:
where:
- : the posterior probability that the observation belongs to class
- : the class-conditional density of given class
- : the prior probability of class
- : the marginal density of under the generative model, shared by all classes and normalizing the posteriors to sum to one
The denominator is the same for every class, so it cannot change which class has the largest posterior probability. The rule "predict the class with the largest posterior probability" is therefore equivalent to "predict the class with the largest ." This is a small algebraic observation with a large practical consequence: we never need to compute the marginal density in order to classify.
Comparing products of densities is awkward, and in high dimensions the products can underflow. Taking logarithms preserves the argmax because the logarithm is monotonic. So
where:
- : the feature vector being classified
- : the mean vector of class
- : the covariance matrix of class
- : the prior probability of class
- : the number of features
- : the determinant of the class covariance
The first term is identical for every and drops out of any comparison. Dropping it, we obtain the discriminant function
where:
- : the discriminant score for class at point
- : the feature vector
- : the mean vector of class
- : the covariance matrix of class
- : the prior probability of class
- : the squared Mahalanobis distance from to class 's mean, in units of class 's own covariance
- : the determinant of the class covariance, penalizing diffuse class clouds
The Bayes decision rule is then .
Each term has a clear interpretation, and it is worth reading them as a sequence of questions. The first term rewards closeness to the class mean, measured in the class's own Mahalanobis metric: does fall inside the class's ellipsoidal neighborhood? The second term is a normalization penalty: at a fixed feature dimension, a larger covariance determinant lowers the Gaussian peak. The density at a particular point also depends on its Mahalanobis distance from the class mean. The third term rewards frequently observed classes, pulling the decision toward a prior that may be strong. Classification is thus a balance between geometric fit, concentration, and prior belief.
Two facts about this derivation are useful. First, adding the same quantity to every class score, even a quantity depending on , does not change the predicted class. Second, the difference between two class scores is exactly the corresponding log-posterior ratio, because all common terms cancel:
where:
- : the two classes being compared
- : the discriminant scores for classes and at point , each defined up to the same additive constant
- : the posterior probabilities of classes and given
The right-hand side is a score difference, and its zero set is the pairwise tie locus. With two classes, a change in the winning label can occur only at a tie; a degenerate tie need not separate two open decision regions. With more than two classes, a tie between and contributes to their shared decision boundary only where their common score is at least as large as every other class score. We now examine how the covariance assumptions determine these score differences.
Shared covariance and linear discriminants
The LDA assumption is that all classes share the same covariance matrix: for all . The shared-covariance condition is a model assumption about the data-generating process. It says that all class clouds have the same shape, orientation, and volume, and differ only in where they are centered and how common they are. Under that assumption, the Gaussian ellipsoids are translated copies of one another. The discriminant simplifies because the term is the same for all classes and drops out:
where:
- : the discriminant score for class at point
- : the feature vector being classified
- : the mean vector of class
- : the shared covariance matrix common to all classes
- : the prior probability of class
- : the squared Mahalanobis distance from to class 's mean in the shared metric
We now expand the quadratic form. In matrix notation,
After multiplying the expansion by , the term is identical for every class and can be dropped. The other terms retain their signs and coefficients; multiplying an entire score by a negative number would reverse its ranking. The shared quadratic term is the cancellation that removes curvature from the score differences. What remains is
This is a linear function of . Define
where:
- : the covariance-adjusted weight vector for class
- : the class- bias (intercept), combining the mean-quadratic term and the log prior
- : the shared covariance, class- mean, and class- prior, as defined earlier
so that is a linear score. For two classes, the decision boundary between them is , or
with
where:
- : the covariance-adjusted normal to the boundary, pointing toward increasing class-0-versus-class-1 score
- : the bias term that shifts the boundary based on the class means and priors
- : the shared covariance, class means, and class priors, as defined earlier
The sign convention matters: equals , so a positive value favors class 0 after accounting for the priors. In general, is not parallel to . If the means differ and the priors are equal, the boundary is the hyperplane through their midpoint on which their Mahalanobis distances are equal. Increasing the prior of one class expands its winning region and moves this hyperplane toward the other class. If the means are identical, the normal is zero and the priors alone decide, or every point is tied when the priors are also equal.
Fisher's original formulation sought a linear combination maximizing the ratio of between-class to within-class variance. In the two-class case with nonsingular within-class covariance, the between-class scatter of the projected values is and the within-class scatter is , so the ratio is
where:
- : the direction onto which the data are projected
- : the difference between the class means, setting the between-class separation
- : the shared (within-class) covariance, setting the within-class spread
When the class means differ, a maximizing nonzero direction is proportional to . Its sign and nonzero scale do not change the variance ratio. If the means coincide, for every nonzero direction, so this criterion does not select an informative direction. Under the shared-covariance Gaussian model with distinct means, the maximizing direction gives the generative classifier when paired with its prior-dependent threshold. The direction alone does not specify that threshold.
LDA has mean parameters and shared symmetric-covariance parameters. Estimating the class priors adds free parameters under , giving in total. For fixed , the covariance term grows quadratically in , while the mean term grows linearly. In the multiclass setting, LDA needs at most discriminant directions. The centered class means have at most independent directions, and applying an invertible covariance adjustment does not change this rank. The posterior-relevant directions in the original feature coordinates are the span of , where is one chosen reference-class mean. Projecting onto these directions retains the Gaussian LDA score differences; projecting onto the raw means need not.
Class-specific covariance and quadratic discriminants
QDA relaxes the shared-covariance assumption: each class has its own . This can describe one class that is narrow and another that is broad or differently oriented. The shared-covariance cancellation is no longer available in general. Some terms can still coincide for particular parameter choices, but the general score must retain the full form
where:
- : the discriminant score for class at point
- : the feature vector being classified
- : the mean vector of class
- : the class-specific covariance matrix for class
- : the prior probability of class
- : the squared Mahalanobis distance from to class 's mean, in class 's own metric
- : the determinant of the class covariance, penalizing diffuse class clouds
When varies with , the contribution is class dependent and must be retained. The log-determinant penalty must likewise be retained whenever the covariance determinants differ; different covariance matrices can still have the same determinant. The general discriminant is quadratic in , with linear and second-order terms in its coordinates. Class-specific covariance therefore permits boundaries beyond a single flat cut, while particular parameter choices can still produce simpler or degenerate boundaries.
For two classes ( and ), the boundary is
which is the equation written with the class-0 terms leading.
where:
- : the feature vector at which the boundary is evaluated
- : the covariance matrices of classes 0 and 1 (both assumed invertible)
- : the mean vectors of classes 0 and 1
- : the constant term, defined explicitly below
The constant collects the terms that do not depend on . Writing out in full (the form matching the displayed boundary equation) and keeping only the terms without gives
where:
- : the feature vector
- : the covariance matrices of classes 0 and 1
- : the class mean vectors
- : the class prior probabilities
- : the constant term collecting all contributions that do not depend on (the mean-quadratic and log-determinant terms plus the log prior ratio)
The boundary equation has the form of a general quadratic in : the symmetric matrix coefficient of the second-order term is , the linear coefficient is , and is the scalar constant.
In two dimensions, a quadratic tie equation can describe conic sections such as ellipses, hyperbolas, and parabolas; in higher dimensions, the corresponding objects are quadrics. The eigenstructure of controls the quadratic curvature, but the linear and constant terms also matter. Together they determine the boundary's location, whether it is degenerate, and whether it exists at all. Some QDA models produce bounded class regions, with a narrow class winning near its center and a broad class winning in the tails. QDA can also reduce to a linear rule when the quadratic difference vanishes.
To see where the constants come from, write term by term, consistent with the sign convention used above. The -independent contribution is
matching above, while the -dependent part yields the quadratic and linear coefficients already stated.
The number of free parameters in QDA is (means) plus (priors) plus (covariances), so its covariance term grows times larger than LDA's. For independent Gaussian samples with a truly common covariance, the pooled covariance has lower entrywise sampling variance than an unbiased class estimate when that class has at least two observations and the other classes add residual degrees of freedom. Whether their flexibility improves held-out prediction depends on the population covariances and the available samples; parameter count alone does not determine the prediction error.
The covariance parameter count grows quadratically in the feature dimension and is multiplied by the number of classes for QDA. The next figure isolates that multiplier for a three-class problem, holding means and priors aside so the covariance cost is the only changing quantity.
VisualizationOut [4]Expand

Covariance estimation, shrinkage, and limitations
The formulas above describe the population rule when the means, covariances, and priors are known. In practice, these parameters must be estimated. The maximum-likelihood class priors are the empirical proportions, , where counts observations in class and . The maximum-likelihood class means are . For covariance estimates, this chapter uses the unbiased sample convention rather than the Gaussian maximum-likelihood convention:
where:
- : the estimated covariance matrix of class
- : the number of observations in class
- : the empirical mean of class
- : the -th feature vector, associated with label
The denominator gives the unbiased class covariance estimator for . When the centered class scatter is positive definite, the Gaussian covariance maximum-likelihood estimator divides that same scatter by . If the scatter is singular, no finite positive-definite covariance maximizes this unconstrained Gaussian density likelihood. The relative difference between the two normalization factors vanishes as grows. For LDA, the unbiased pooled covariance estimator is
where:
- : the pooled estimate of the shared covariance matrix used by LDA
- : the total number of observations across all classes
- : the number of classes
- : the number of observations in class
- : the empirical mean of class
- : the -th feature vector, associated with label
This pools the within-class scatter and divides by the residual degrees of freedom . When the pooled scatter is positive definite, the shared-covariance Gaussian maximum-likelihood estimator instead divides that same scatter by . If the pooled scatter is singular, the unconstrained positive-definite Gaussian covariance likelihood has no finite maximum. These are different finite-sample normalization conventions; the worked example and primitive implementations below consistently use the unbiased denominators.
Pooling is the estimation analogue of the shared-covariance assumption. Under independent Gaussian samples with a truly common covariance, the pooled estimate has residual degrees of freedom rather than one class's . For a class with , pooling has no larger covariance-entry sampling variance under that model; the reduction is strict when the other classes add residual degrees of freedom, so . If class covariances differ, pooling instead estimates a compromise matrix.
For a centered class sample with , . Thus forces singularity: for and , there are at most 49 nonzero eigenvalues and the inverse does not exist. Having is necessary, but not sufficient, for nonsingularity. LDA's pooled scatter similarly has rank at most . Even when these matrices are full rank, small samples and strong feature dependencies can make covariance estimation unreliable. Rank, conditioning, and estimation uncertainty are separate checks.
Shrinkage estimators regularize the covariance by blending the empirical estimate with a low-dimensional target:
where:
- : the shrunk (regularized) covariance estimate for class at mixing level
- : the mixing (shrinkage) parameter in controlling the bias-variance tradeoff; recovers the empirical covariance and yields the pure target
- : the empirical covariance of class
- : the shrinkage target, for example the identity matrix or a scaled version
At , the estimate is the empirical covariance; at , it is the target . If the empirical covariance is positive semidefinite and the target is positive definite, any makes their convex blend positive definite. A shared identity or positive scaled-identity target is spherical. The Ledoit-Wolf (2004) estimator provides a data-driven shrinkage approach. It should not be conflated with manually choosing a regularization strength. In scikit-learn 1.8, QDA's default 'svd' solver uses reg_param; its 'eigen' solver instead supports shrinkage, including 'auto'. LDA supports shrinkage='auto' with 'lsqr' or 'eigen'. The solver and rank limitations are specified below.
Two further limitations matter. A sufficiently extreme observation can dominate an empirical covariance and move the fitted boundary. The empirical mean and covariance have unbounded influence even when the reference distribution is Gaussian. Moving a contaminating point farther away makes its influence grow without bound. Gaussianity therefore does not make these estimators robust to contamination. Robust covariance estimators address a different estimation problem and are outside this chapter's scope.
Mathematical Properties
Discriminant analysis inherits several structural properties from its Gaussian foundation.
- Invertible affine transformations preserve unregularized LDA and QDA predictions in exact arithmetic when their estimates are transformed consistently. If with invertible , then and . Mahalanobis distances are unchanged, while . The full Gaussian discriminants therefore change by , common to every class. Reduced LDA scores, after dropping their shared quadratic term, can acquire a different common term depending on , but all score differences are still unchanged. This algebraic equivariance does not require Gaussian data; finite precision and a fixed regularization target can limit the invariance in practice.
- Posterior probabilities are given by the softmax of the discriminant scores (the logits):
This means LDA and QDA are not just classifiers but probabilistic models: the same machinery that predicts labels can also predict class probabilities. In practice, these probabilities can be miscalibrated if the Gaussian assumption fails, which motivates the calibration methods discussed in later parts of the book. In the implementation below, we compute the class posteriors directly from the discriminant scores via this softmax.
- Under the shared-covariance Gaussian model, the binary posterior is logistic in . In the earlier sign convention, , so , where . Equivalently, its class-1 logit has coefficient . Logistic regression fits this conditional linear-logit family directly. LDA obtains coefficients by fitting a joint Gaussian model; this imposes assumptions about feature distributions, rather than a smaller family of linear posterior logits.
- QDA does not generally satisfy a linear-logistic relationship. Its log-odds is quadratic in , so holds with , a quadratic function of . The quadratic term enters before the logistic transformation, so the gradient of the log-odds generally varies affinely across feature space.
Comments
Add to the conversation
A question, a correction, or an example from your own work.
No comments yet. Be the first to share your thoughts!