AI Wiki中文/EN

Linear discriminant analysis: covariance, priors and a straight boundary

线性判别分析

Derive shared-covariance Gaussian classification, fit a small LDA model, and distinguish its decision rule from Fisher projection.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Two sensors can be misleading when read separately

A fictional sorting station records two sensor readings for each object. Within either class, the readings tend to rise together. A point that looks unusual on each coordinate separately may be ordinary along that shared direction. Conversely, a small movement against the correlation can matter a great deal.

Linear discriminant analysis (LDA) models each class as a Gaussian cloud with its own center and a common covariance matrix. It combines how plausible the measurements are within a class with that class’s prior probability. The resulting pairwise decision boundaries are straight, although computing the rule requires a covariance estimate. The official guide derives this classifier and its Mahalanobis geometry. scikit-learn 1.7, §1.2.2.

Our small example will classify the same query twice. First, both classes are equally likely. Then B is assigned an 80% prior. Nothing about the measured class centers or spread changes; the preferred class does. This is an exercise in a fitted probability model, not a measured result from a sorting system.

LDA also names a supervised projection method associated with Fisher’s separation criterion. The classifier and the projection share mathematics, but finding a direction does not by itself supply class priors, a decision threshold or calibrated probabilities. Keep those tasks separate as we work through the model.

Why a Gaussian model gives a linear rule

Let x have d real-valued features and let k range over K classes. Assume strictly positive priors summing to one and a common positive-definite covariance. In particular, features need not be independent within a class: off-diagonal covariance entries are allowed. The model is

P(Y=k)=πk>0,∑k=1Kπk=1,X∣Y=k∼N(μk,Σ),Σ≻0,p(x∣k)=exp⁡[−12(x−μk)TΣ−1(x−μk)](2π)d/2∣Σ∣1/2.P(Y=k)=\pi_k>0,\quad \sum_{k=1}^{K}\pi_k=1,\qquad X\mid Y=k\sim\mathcal N(\mu_k,\Sigma),\quad\Sigma\succ0,\qquad p(x\mid k)=\frac{\exp[-\tfrac12(x-\mu_k)^T\Sigma^{-1}(x-\mu_k)]}{(2\pi)^{d/2}|\Sigma|^{1/2}}.

For zero-one classification loss, maximizing the posterior minimizes conditional error under this model. Bayes’ rule says to compare the logarithm of the density plus the logarithm of the prior. The determinant term is common to every class. Expanding the quadratic also produces a common term −xᵀΣ⁻¹x/2, which can be dropped from every score:

δk(x)=xTΣ−1μk−12μkTΣ−1μk+log⁡πk,P(Y=k∣x)=eδk(x)∑jeδj(x),y^(x)=arg⁡max⁡kδk(x).\delta_k(x)=x^T\Sigma^{-1}\mu_k-\frac12\mu_k^T\Sigma^{-1}\mu_k+\log\pi_k,\qquad P(Y=k\mid x)=\frac{e^{\delta_k(x)}}{\sum_j e^{\delta_j(x)}},\qquad \widehat y(x)=\arg\max_k\delta_k(x).

The difference between two scores is affine in x, so their equality is a hyperplane when their slope vectors differ. If the means coincide, their slope vectors coincide: priors can favor one class everywhere, or equal priors can give a tie everywhere. With more than two classes, a class region is an intersection of score-comparison half-spaces and can be empty. The program resolves exactly equal computed scores by the first class label in Python string order.

Equivalently, compare squared Mahalanobis distances to the means, with an adjustment for log priors. Whitening by the common covariance turns those distances into Euclidean distances. With equal priors this is nearest-center classification in whitened coordinates. A spherical covariance with equal priors gives ordinary Euclidean nearest-center classification in the original coordinates. An arbitrary covariance does not generally give that rule. The nearest-centroid chapter develops that simpler rule.

Estimate one covariance, and say which denominator you used

Suppose all K classes occur in the training data. Write nₖ for a class count and n for the total. This implementation uses the class means and the within-class maximum-likelihood covariance convention, then optionally adds a diagonal ridge:

μ^k=1nk∑i:yi=kxi,SW=∑i=1n(xi−μ^yi)(xi−μ^yi)T,Σ^ML=SWn,Aγ=Σ^ML+γI,γ≥0.\widehat\mu_k=\frac1{n_k}\sum_{i:y_i=k}x_i,\qquad S_W=\sum_{i=1}^{n}(x_i-\widehat\mu_{y_i})(x_i-\widehat\mu_{y_i})^T,\qquad\widehat\Sigma_{\mathrm{ML}}=\frac{S_W}{n},\qquad A_\gamma=\widehat\Sigma_{\mathrm{ML}}+\gamma I,\quad\gamma\ge0.

These are within-class residuals, not deviations from the grand mean. The latter would mix class separation into the noise estimate. The default prior is nₖ/n. Supplying other positive prior weights changes the prior probabilities after normalization; it does not change the means or reweight the covariance. Andrew Ng’s original course notes give the shared-covariance Gaussian model and the 1/n estimator for two classes. CS229 notes, §1.2, pp. 5–6.

Another convention divides S_W by n−K, when n>K, for an unbiased pooled covariance under the common-covariance sampling assumptions. The two conventions are not numerically interchangeable. With no ridge and equal priors, their common positive scaling preserves the classifier’s boundary but changes its posterior probabilities. With unequal priors, the relative strength of the distance and log-prior terms changes, so even the boundary can move.

The matrix formula is computable even when singular, but an invertible Gaussian density fit then is not available from the unregularized estimate. In exact arithmetic, a positive ridge makes this positive-semidefinite matrix positive definite. It is an explicit change to the fitted model, not evidence that its predictions are better. Our ridge is an additive variance in the supplied feature units; it is not scikit-learn’s dimensionless shrinkage parameter. Changing units while keeping the same numeric ridge generally changes the model.

Read the example’s boundary before running it

Each class has four observations with the same residual pattern. A is centered at (0,0), B at (2,0). The resulting estimates and score difference are

Σ^=(2111),Σ^−1=(1−1−12),δB(x)−δA(x)=2x1−2x2−2+log⁡(πB/πA).\widehat\Sigma=\begin{pmatrix}2&1\\1&1\end{pmatrix},\qquad\widehat\Sigma^{-1}=\begin{pmatrix}1&-1\\-1&2\end{pmatrix},\qquad\delta_B(x)-\delta_A(x)=2x_1-2x_2-2+\log(\pi_B/\pi_A).

At (1.5,1), the difference is −1 with equal priors. A wins, with model probability about 0.731059. Assigning weights A:1 and B:4 adds log 4, so B wins with probability 4/(4+e), about 0.595390. Neither a new observation nor a different covariance was needed to move the boundary.

Fisher’s direction is not the entire classifier

For two classes with distinct means and positive-definite S_W, Fisher’s criterion compares separation of the projected means with within-class projected scatter. Cauchy–Schwarz after whitening gives

Δμ=μ^B−μ^A,J(w)=(wTΔμ)2wTSWw≤ΔμTSW−1Δμ,w≠0,w⋆∝SW−1Δμ.\Delta\mu=\widehat\mu_B-\widehat\mu_A,\qquad J(w)=\frac{(w^T\Delta\mu)^2}{w^TS_Ww}\le\Delta\mu^TS_W^{-1}\Delta\mu,\qquad w\ne0,\qquad w_\star\propto S_W^{-1}\Delta\mu.

Equality holds when the whitened projection direction aligns with the whitened mean difference. The ratio is unchanged by a nonzero rescaling of w. This direction is parallel to the difference of the unregularized LDA score coefficients because the covariance is proportional to S_W. Priors and the intercept still determine where to cut along that direction. Maximizing this sample scatter ratio does not itself require a Gaussian population or prove any probability estimate correct.

For K classes, the usual between-class scatter has rank at most min(d,K−1); after a nonsingular within-class whitening, there are at most that many separating projection directions. With two classes, a single useful direction is possible. A projection can also discard class information if fewer available directions are retained. This program performs classification and supplies no projection API. Official guide, §§1.2.3 and 1.2.5.

Fit the model without forming an inverse

The complete standard-library Python program computes a Cholesky factor of Aγ and solves Aγwₖ=μₖ for each class. It stores one coefficient vector and offset per class. Prediction uses those linear scores; subtracting the largest score before exponentiation avoids overflowing the softmax exponentials.

Use lists or tuples of fixed-width feature rows, with at least one feature and two observed classes. Labels are nonempty strings; inputs are finite Python integers or floats, with Booleans rejected. Prior weights, when supplied, must cover exactly the observed classes and must all be positive. Zero-prior classes are excluded by this API rather than silently removed. Class order is sorted label order. The returned model must remain unmodified when passed to predict; an empty prediction batch returns an empty tuple.

A Cholesky pivot at most 10⁻¹² times the largest covariance diagonal is rejected, as is a nonpositive pivot. This is a stated numerical guard, not a condition-number certificate. Even positive ridge values may be too small to pass it in floating point. Detected nonfinite arithmetic raises ValueError; rounding and underflow can still affect moments and probabilities, and very small posterior masses may become zero. The code is for small, reasonably scaled data and does not replace a numerically robust library. Exact mathematical invariances can become approximate near floating-point ties.

from math import exp, fsum, isfinite, log, sqrt


def number(value):
    if type(value) not in (int, float):
        raise ValueError('expected a finite number, not Boolean')
    try:
        value = float(value)
    except OverflowError:
        raise ValueError('number exceeds floating-point range') from None
    if not isfinite(value):
        raise ValueError('nonfinite arithmetic or input')
    return value


def total(values):
    try:
        return number(fsum(values))
    except (OverflowError, ValueError):
        raise ValueError('sum exceeds supported numerical range') from None


def sequence(values):
    if type(values) not in (list, tuple):
        raise ValueError('expected a list or tuple')
    return values


def average(values):
    values = tuple(values)
    if all(v == values[0] for v in values):
        return values[0]
    return total(v / len(values) for v in values)


def dot(a, b):
    return total(number(x * y) for x, y in zip(a, b))


def cholesky(matrix):
    d = len(matrix)
    scale = max(matrix[j][j] for j in range(d))
    if scale <= 0:
        raise ValueError('covariance is singular; consider an explicit ridge')
    lower = [[0.0] * d for _ in range(d)]
    for i in range(d):
        for j in range(i + 1):
            value = number(matrix[i][j] - dot(lower[i][:j], lower[j][:j]))
            if i == j:
                if value <= 0 or value / scale <= 1e-12:
                    raise ValueError('covariance has a nonpositive or small pivot')
                lower[i][j] = sqrt(value)
            else:
                lower[i][j] = number(value / lower[j][j])
    return tuple(map(tuple, lower))


def solve(lower, rhs):
    d = len(rhs)
    forward, answer = [0.0] * d, [0.0] * d
    for i in range(d):
        forward[i] = number(number(rhs[i] - dot(lower[i][:i], forward[:i])) / lower[i][i])
    for i in range(d - 1, -1, -1):
        upper = tuple(lower[j][i] for j in range(i + 1, d))
        answer[i] = number(number(forward[i] - dot(upper, answer[i + 1:])) / lower[i][i])
    return tuple(answer)


def fit_lda(features, labels, ridge=0.0, prior_weights=None):
    rows = tuple(tuple(number(v) for v in sequence(row)) for row in sequence(features))
    labels = tuple(sequence(labels))
    if not rows or not rows[0] or len(labels) != len(rows):
        raise ValueError('nonempty feature rows and one label per row required')
    d, n = len(rows[0]), len(rows)
    if any(len(row) != d for row in rows):
        raise ValueError('feature dimensions differ')
    if any(type(label) is not str or not label for label in labels):
        raise ValueError('class labels must be nonempty strings')
    classes = tuple(sorted(set(labels)))
    if len(classes) < 2:
        raise ValueError('at least two observed classes required')
    ridge = number(ridge)
    if ridge < 0:
        raise ValueError('ridge must be nonnegative')
    grouped = {label: [] for label in classes}
    for row, label in zip(rows, labels):
        grouped[label].append(row)
    means = tuple(tuple(average(row[j] for row in grouped[c])
                        for j in range(d)) for c in classes)
    by_class = dict(zip(classes, means))
    residuals = tuple(tuple(number(v - m) for v, m in zip(row, by_class[c]))
                      for row, c in zip(rows, labels))
    covariance = tuple(tuple(total(number(row[i] * row[j]) / n for row in residuals)
                             for j in range(d)) for i in range(d))
    regularized = tuple(tuple(number(covariance[i][j] + (ridge if i == j else 0.0))
                              for j in range(d)) for i in range(d))
    if prior_weights is None:
        weights = tuple(float(len(grouped[c])) for c in classes)
    else:
        if type(prior_weights) is not dict or set(prior_weights) != set(classes):
            raise ValueError('provide exactly one prior weight for each observed class')
        weights = tuple(number(prior_weights[c]) for c in classes)
    if any(w <= 0 for w in weights):
        raise ValueError('prior weights must be strictly positive')
    maximum = max(weights)
    scaled = tuple(w / maximum for w in weights)
    normalizer = total(scaled)
    priors = tuple(w / normalizer for w in scaled)
    if any(p <= 0 for p in priors):
        raise ValueError('a positive prior underflowed; rescale the problem')
    lower = cholesky(regularized)
    coefficients = tuple(solve(lower, mean) for mean in means)
    offsets = tuple(number(-0.5 * dot(mean, coef) + log(p))
                    for mean, coef, p in zip(means, coefficients, priors))
    return {'classes': classes, 'means': means, 'covariance': covariance,
            'regularized': regularized, 'priors': priors,
            'coefficients': coefficients, 'offsets': offsets, 'dimension': d}


def predict(model, features):
    """The model must be an unmodified result of fit_lda."""
    result = []
    for row in sequence(features):
        row = tuple(number(v) for v in sequence(row))
        if len(row) != model['dimension']:
            raise ValueError('prediction feature dimensions differ')
        scores = tuple(number(dot(row, coef) + offset)
                       for coef, offset in zip(model['coefficients'], model['offsets']))
        best = max(range(len(scores)), key=scores.__getitem__)
        masses = tuple(exp(number(score - scores[best])) for score in scores)
        denominator = total(masses)
        result.append({'label': model['classes'][best], 'scores': scores,
                       'probabilities': tuple(mass / denominator for mass in masses)})
    return tuple(result)


if __name__ == '__main__':
    spread = ((2, 1), (-2, -1), (0, 1), (0, -1))
    X = spread + tuple((x + 2, y) for x, y in spread)
    y = ('A',) * 4 + ('B',) * 4
    equal = fit_lda(X, y)
    frequent_b = fit_lda(X, y, prior_weights={'A': 1, 'B': 4})
    print('means:', equal['means'])
    print('pooled covariance:', equal['covariance'])
    for name, model in (('equal', equal), ('B prior 0.8', frequent_b)):
        row = predict(model, ((1.5, 1),))[0]
        print(name, row['label'], tuple(round(p, 6) for p in row['probabilities']))
    print('ridge 0.5 covariance:', fit_lda(X, y, ridge=0.5)['regularized'])

Actual output:

means: ((0.0, 0.0), (2.0, 0.0))
pooled covariance: ((2.0, 1.0), (1.0, 1.0))
equal A (0.731059, 0.268941)
B prior 0.8 B (0.40461, 0.59539)
ridge 0.5 covariance: ((2.5, 1.0), (1.0, 1.5))

With n rows, d features and K observed classes, fitting uses O(nd²+d³+Kd²+K log K) arithmetic/comparison operations. The terms account for the covariance, factorization, K linear solves and label sorting. It retains O(nd+d²+Kd) numeric storage during fitting and O(d²+Kd) in the returned model. Predicting m rows takes O(1+mKd) arithmetic operations and O(1+mK+d) extra storage, including all returned scores and probabilities. These are operation counts; label lengths and integer-to-float conversion costs are separate. The dimension d and class count K are positive, so those expressions include fixed work.

There is no standardization, feature selection or prior estimation on prediction rows. If a preprocessing transformation is learned, fit it on training data and apply the same transformation later. Select a ridge or feature set inside the validation protocol, then evaluate on appropriate untouched data.

A straight boundary carries strong assumptions

Sharing a covariance means that classes have the same modeled shape and orientation. It does not mean identical means, equal priors or independent features. If classes need different covariance matrices, quadratic discriminant analysis retains class-dependent quadratic and determinant terms. That greater flexibility also means estimating more parameters; it is not automatically an improvement.

Since the centered rows within each class sum to zero, rank(S_W) is at most min(d,n−K). Therefore d>n−K guarantees singularity; the reverse inequality does not guarantee invertibility. Collinear features can still cause failure. One observation per class supplies no within-class variation at all. Ridge can define a classifier in that situation, but its geometry comes from the regularization choice rather than observed within-class spread.

For zero ridge and nonsingular estimates, a shared invertible affine change of coordinates preserves posterior probabilities in exact arithmetic: transform each mean and covariance with the data and the Mahalanobis terms remain equal. This statement does not apply to a fixed isotropic ridge after arbitrary rescaling. Standardization is useful numerically, but it changes what a chosen ridge means.

Gaussian model probabilities are not a guarantee of empirical calibration. Outliers, unequal class shapes, multimodal classes, selection effects and changing deployment priors can break the model. A supplied prior is an assumption that needs justification; changing it does not repair changing class-conditional distributions. Under unequal mistake costs, the decision should minimize expected cost instead of simply maximizing the posterior. This example implements zero-one loss only.

LDA is also an acronym for latent Dirichlet allocation, a different topic model. The covariance and projection calculations on this page concern linear discriminant analysis.

Check the geometry and the assumptions

  1. In the example, what decides the class at (1.5,1) with equal priors? What changes when the weights become A:1, B:4?

    Answer: The score difference B−A is −1, so A wins. The new log-prior ratio adds log 4, making the difference positive. B then has model probability 4/(4+e), about 0.595390. The measured means and covariance stay fixed.

  2. There are eight observations in two classes and three features. Must the covariance be singular? What if there are seven features?

    Answer: Its rank is at most min(d,8−2). Three features do not force singularity, but dependence among them can still make it singular. Seven features force rank at most six, so the unregularized inverse cannot exist. Positive ridge repairs positive definiteness in exact arithmetic, not the absence of information.

  3. Replace S_W/n by S_W/(n−K), with n>K and no ridge. Does that leave every prediction and probability unchanged?

    Answer: No. The covariance is multiplied by n/(n−K), so the distance contribution to every log score is scaled. Equal priors preserve the maximizing class and its boundary, but usually change probabilities. Unequal priors need not preserve the boundary because the log-prior term is not scaled.

  4. A two-class Fisher projection supplies w. Can you now report class probabilities, or assume the first coordinate is a calibrated confidence?

    Answer: No. The scatter ratio determines a direction only up to scale and sign. Classification still needs a threshold and a tie rule; Gaussian posterior probabilities additionally require the generative parameters and priors. The projection criterion alone does not establish Gaussian assumptions or calibration.

Keep the generative model and the projection objective distinct

The versioned scikit-learn guide was read at the 1.7 path, displaying 1.7.2. Its classifier derivation, whitening interpretation and estimation discussion help distinguish the two uses of LDA. Its library offers several solvers and covariance estimators; this chapter does not reproduce those implementations or claim compatible defaults. In particular, the additive ridge and small-pivot rejection are explicit choices of our own example.

Andrew Ng’s CS229 notes were read from the summer 2023 course path, with the author named in the document. The binary shared-covariance likelihood and 1/n estimator support the fitting convention used here. The path identifies the accessed teaching version, not a claimed first publication date. This example extends the same conditional model to multiple classes and does not reproduce the notes’ animal examples or figures.

Tests compare the program with rational covariance construction, independent elimination and Gaussian distance scores, then check an invertible coordinate change, priors, ties, singularity and input boundaries. These checks validate the stated small model. They do not measure whether LDA is the right assumption for a future dataset. Logistic regression provides a related linear decision rule learned through a different objective.

Make a prediction, then check

With fitted means and common covariance fixed, can replacing equal priors by B:80%, A:20% move an LDA boundary?

Choose one answer

Learning objectives

  • Derive linear scores from shared-covariance Gaussians and explain how priors and Mahalanobis distances determine a class.
  • Distinguish 1/n and 1/(n−K) covariance conventions and check singularity, additive ridge and numerical boundaries.
  • Distinguish Fisher’s projection direction from a complete classifier and verify the program against an independent Gaussian-distance reference.

Prerequisites & connections

Explore related knowledge →

References

  1. Linear and Quadratic Discriminant Analysis (1.7.2)
    scikit-learn contributors
  2. CS229 Lecture Notes, Part IV: Generative Learning Algorithms
    Andrew Ng; Stanford University

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.

  • Nine standard-library tests passed. An independent reference constructs rational covariance from within-class pairwise outer differences, then uses Gauss–Jordan elimination and Gaussian quadratic-distance scores. It checks 12 fits in one to three dimensions with two or three classes and 48 queries, without reusing production residual covariance or Cholesky solving.
  • Checked changed-prior decisions, affine invariance, repeated training rows, exact ties, empty prediction, input preservation, singular and small-pivot rejection, ridge units and prior underflow. A concrete n versus n−K case changes the query from A to B; out-of-range numbers and invalid shapes are rejected as specified.
  • Complete bilingual prose, identical Python and five-line actual stdout, five matching display formulas, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML pass, including decoded MathML comparison. Only article_text determines the article path in tests.
  • Targeted Humanizer scanning and paragraph-level AI rereading completed. AI author check only; remains written. No scikit-learn execution, Fisher projection implementation, real sorting experiment, whole-site build or browser acceptance. Floating-point guards do not certify arbitrary condition numbers or accuracy for every finite input.
  • Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
  • Publication navigation points existing topics to their complete articles, retaining pending directory entries. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.

Source locations checked:

  • Linear and Quadratic Discriminant Analysis (1.7.2) · Actually opened and read the official page: §1.2.2, lines 85–120 (class-conditional Gaussian model, shared covariance, posterior and linear coefficients); §1.2.3, lines 121–126 (whitening and K−1 geometry); §§1.2.4–1.2.5, lines 127–145 (covariance options and solving without an inverse). The page displays 1.7.2. The article does not adopt broad claims of guaranteed accuracy improvement, or present additive ridge as the library’s shrinkage setting. No library run.
  • CS229 Lecture Notes, Part IV: Generative Learning Algorithms · Actually opened the 14-page original PDF. Read title/author and introduction, pp. 1–2 (generative versus discriminative modeling and Bayes rule), then §1.2, printed pp. 5–6, extracted lines 360–464 (shared covariance, labeled likelihood, class means, covariance divided by total n and linear decision boundary). Also read the opening of §1.3, lines 465–482, distinguishing Gaussian assumptions from the logistic posterior form. Text extraction only, no full-paper visual audit or claim of first publication in 2023.
  • Linear and Quadratic Discriminant Analysis (1.7.2) · Actually read official page displaying 1.7.2, §§1.2.2–1.2.4, lines 85–130: Gaussian class densities, shared covariance, Mahalanobis/linear scores, whitening, K−1 mean geometry and library shrinkage distinction. No library execution or reproduction of general accuracy claims.
  • CS229 Lecture Notes, Part IV: Generative Learning Algorithms · Actually opened the 14-page official PDF; read §1.2 printed 5–6 (lines 360–464) shared covariance, labeled likelihood, class means, 1/n covariance and boundary. Read §1.3 opening printed 7 (lines 465–482) Gaussian generative assumptions versus logistic posterior form. Text extraction only; no original-2023 publication or full visual audit claimed.

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.