Quadratic discriminant analysis: distance needs a volume term
二次判别分析
Build a two-feature QDA classifier and expose how class covariance, log determinants and priors produce curved or missing boundaries.
quadratic-discriminantA broad class is close to many points
Imagine two fictional fabrication processes with the same average pair of measurements. A produces a tight cluster around the average. B produces a much wider cluster. Their centers cannot distinguish them, but their spreads can: a point near the center favors A, while a sufficiently distant point can favor B.
Quadratic discriminant analysis (QDA) gives each class its own Gaussian covariance. This changes two parts of the comparison: distance is measured in a different geometry for each class, and the density must be normalized by that class’s volume. Keeping only the distances gives the wide class an unfair advantage: almost everything is close when measured in its large units.
The example below keeps those two terms visible. Its training moments and distances are exact rational numbers; logarithms and posterior probabilities use a fixed decimal precision. It is a complete two-feature classifier, not a benchmark on manufacturing data or a general numerical library. Official QDA derivation.
Keep the determinant when the covariance changes
For K classes, assume positive priors summing to one and positive-definite class covariances. Unlike linear discriminant analysis, the matrices need not agree:
The Gaussian constant −d log(2π)/2 is common to all classes and is omitted. The determinant term is not common when the covariances differ. Bayes’ rule gives the posterior by normalizing exp(gₖ); under zero-one loss, choose the largest score. These are probabilities and an optimal decision for the specified model, not a guarantee that its estimated probabilities describe a new dataset.
The squared-distance term penalizes departures from the mean relative to the class’s spread. The volume factor |Σₖ|¹ᐟ² grows when the cloud expands, reducing density near its center. This normalization makes the total class-conditional density integrate to one. A broad Gaussian can still dominate in the tails because its distance penalty grows more slowly. The official guide includes both terms; the general construction from class-conditionals and priors is also explained in Andrew Ng’s generative-learning notes. scikit-learn, §1.2.2.1; CS229, pp. 1–2.
Expanding a score difference shows where the name comes from:
An equality of scores is generally quadratic. It can degenerate: equal covariances cancel the quadratic term and give the LDA form; identical means, covariances and priors tie everywhere. QDA does not promise that every pair has a nonempty curved boundary. Multiclass regions compare a score against every other score and need not be convex.
Fit separate moments, with a denominator for each class
Let class k contain nₖ training rows, and let n be the total. Because the labeled likelihood factors by class, its unregularized Gaussian estimates use each class’s own mean and covariance. We choose the maximum-likelihood denominator nₖ and optionally add the same nonnegative ridge to each diagonal:
The default prior is nₖ/n. Other supplied positive weights are normalized exactly and change only the prior. The code computes the same covariance through second moments, E[xxᵀ]−E[x]E[x]ᵀ. Using rational arithmetic prevents cancellation from corrupting that subtraction; it does not cure uncertainty in the data.
Dividing by nₖ−1 instead is a different covariance convention, available only when nₖ>1. Both distances and log determinants change. The official library’s QDA estimation discussion uses nₖ−1 in its class-centered SVD construction; our outputs therefore should not be expected to match its default fit. The shared-covariance estimator in the CS229 notes uses a total-sample denominator; it is not the separate-covariance QDA estimator implemented here. Official estimation discussion, §1.2.5.
A circular boundary from equal centers
Use four corners (±1,±1) for A and four corners (±2,±2) for B, all equally weighted. Both estimated means are zero. The ML covariances are I and 4I, with determinants 1 and 16. With equal priors, let r²=x₁²+x₂²:
The boundary radius is about 1.923. At the origin, A has posterior 4/5. At (1,0), squared Mahalanobis distances are 1 for A and 1/4 for B, yet A still wins: the determinant penalty outweighs B’s distance advantage. At (2,0), B wins. Its exterior region is not convex; points on opposite sides can belong to B while their midpoint belongs to A.
Increasing the ratio π_B/π_A adds its logarithm to the score difference. A ratio above four makes B win even at the origin and, in this particular example, everywhere. At exactly four, the origin ties and B wins elsewhere. Thus a prior change can remove the boundary; it need not just move an existing curve.
Audit distance, volume and posterior separately
The program accepts records (class label, first feature, second feature). It accumulates a count and five rational sums per class, so it need not retain all training rows. A symmetric two-dimensional covariance is stored as (a,b,c), standing for rows (a,b) and (b,c). Its positive-definiteness and distance calculation are explicit:
Here (u,v) is the query minus the corresponding class mean. The covariance, determinant, prior and squared distance are exact for the supplied rational data. The cached log-volume/prior term and returned scores and probabilities are approximate: the program uses 50 significant decimal digits with round-to-nearest, ties-to-even. Subtracting the largest score before exponentiation stabilizes probability normalization.
Only Python int and Fraction inputs are accepted for coordinates, ridge and prior weights; floats, Booleans and other numeric types are rejected. Labels must be nonempty strings and at least two classes must occur. Lists or tuples are required for records and points. Missing, extra, zero or negative prior weights are rejected. Every class covariance must be positive definite after adding the ridge. A singular class rejects the fit, even if the other classes are well sampled.
Use the returned model unchanged. classify handles one point and returns its label, exact squared distances, decimal scores and probabilities, all in sorted class-label order. Equal computed scores choose the first label in Python string order. The score precision is not a proof of an exact winner near a boundary: logarithms may round and tiny normalized masses may underflow. Trapped decimal range errors become ValueError; there is no arbitrary-size performance or accuracy guarantee.
from decimal import Context, Decimal, DecimalException, ROUND_HALF_EVEN, localcontext
from fractions import Fraction
def rational(value):
if type(value) not in (int, Fraction):
raise ValueError('use integers or Fraction values, not floats or Boolean')
return Fraction(value)
def items(value):
if type(value) not in (tuple, list):
raise ValueError('use a list or tuple')
return value
def context():
return Context(prec=50, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999)
def decimal(value):
return Decimal(value.numerator) / Decimal(value.denominator)
def log_ratio(value):
return Decimal(value.numerator).ln() - Decimal(value.denominator).ln()
def fit_qda(records, ridge=0, prior_weights=None):
"""Each input record is (class_label, first_feature, second_feature)."""
ridge = rational(ridge)
if ridge < 0:
raise ValueError('ridge must be nonnegative')
stats = {}
for row in items(records):
row = items(row)
if len(row) != 3 or type(row[0]) is not str or not row[0]:
raise ValueError('each record needs a nonempty class label and two features')
label, u, v = row[0], rational(row[1]), rational(row[2])
s = stats.setdefault(label, [0] + [Fraction(0)] * 5)
s[0] += 1
for j, value in enumerate((u, v, u*u, u*v, v*v), 1):
s[j] += value
classes = sorted(stats)
if len(classes) < 2:
raise ValueError('at least two observed classes required')
if prior_weights is None:
weights = {label: Fraction(stats[label][0]) for label in classes}
else:
if type(prior_weights) is not dict or set(prior_weights) != set(classes):
raise ValueError('provide exactly the observed class labels as prior keys')
weights = {label: rational(prior_weights[label]) for label in classes}
if any(w <= 0 for w in weights.values()):
raise ValueError('prior weights must be strictly positive')
weight_sum = sum(weights.values(), Fraction(0))
model = []
try:
with localcontext(context()):
for label in classes:
n, su, sv, suu, suv, svv = stats[label]
mu, mv = su/n, sv/n
empirical = (suu/n-mu*mu, suv/n-mu*mv, svv/n-mv*mv)
a, b, c = empirical[0]+ridge, empirical[1], empirical[2]+ridge
determinant = a*c-b*b
if a <= 0 or determinant <= 0:
raise ValueError('class covariance is not positive definite: ' + label)
prior = weights[label]/weight_sum
model.append({'label': label, 'count': n, 'mean': (mu, mv),
'empirical': empirical, 'covariance': (a, b, c),
'determinant': determinant, 'prior': prior,
'log_scale': log_ratio(prior)-log_ratio(determinant)/2})
except DecimalException:
raise ValueError('Decimal range exceeded') from None
return tuple(model)
def classify(model, point):
"""Use an unmodified model returned by fit_qda; classify one 2D point."""
point = tuple(rational(v) for v in items(point))
if len(point) != 2:
raise ValueError('query needs exactly two features')
squared = []
for row in model:
u, v = (point[j]-row['mean'][j] for j in range(2))
a, b, c = row['covariance']
squared.append((c*u*u-2*b*u*v+a*v*v)/row['determinant'])
try:
with localcontext(context()):
scores = tuple(row['log_scale']-decimal(q)/2 for row, q in zip(model, squared))
winner = max(range(len(scores)), key=scores.__getitem__)
masses = tuple((s-scores[winner]).exp() for s in scores)
total = sum(masses, Decimal(0))
probabilities = tuple(m/total for m in masses)
except DecimalException:
raise ValueError('Decimal range exceeded') from None
return {'label': model[winner]['label'], 'squared_distances': tuple(squared),
'scores': scores, 'probabilities': probabilities}
if __name__ == '__main__':
corners = ((-1, -1), (-1, 1), (1, -1), (1, 1))
records = tuple(('A', u, v) for u, v in corners) + tuple(('B', 2*u, 2*v) for u, v in corners)
model = fit_qda(records)
print('determinants:', tuple(str(row['determinant']) for row in model))
for point in ((0, 0), (1, 0), (2, 0)):
answer = classify(model, point)
print(point, answer['label'], tuple(format(p, '.6f') for p in answer['probabilities']))
print('squared distances at (1, 0):', tuple(str(q) for q in classify(model, (1, 0))['squared_distances']))
weighted = fit_qda(records, prior_weights={'A': 1, 'B': 8})
print('B prior 8/9 at origin:', classify(weighted, (0, 0))['label'])
Actual output:
determinants: ('1', '16')
(0, 0) A ('0.800000', '0.200000')
(1, 0) A ('0.733273', '0.266727')
(2, 0) B ('0.471604', '0.528396')
squared distances at (1, 0): ('1', '1/4')
B prior 8/9 at origin: B
The first four training points are corners, not draws from a verified Gaussian. Their fitted covariance provides a transparent calculation. The 0.733273 probability at (1,0) belongs to this fitted model; there is no held-out performance estimate here. Adding a ridge should be evaluated through a selection protocol, not praised merely because inversion succeeds.
For this fixed two-feature implementation, fitting uses O(n+K log K) rational arithmetic/comparison operations plus O(K) decimal logarithms. It retains O(K) numeric records. One query uses O(K) rational and decimal operations, including K exponentials, and returns O(K) values. These are counts of operations, not unit-cost bit bounds: exact numerator and denominator lengths can grow, and decimal conversions and transcendental functions cost work. A dense d-dimensional implementation would ordinarily require O(Σₖnₖd²+Kd³) work for covariance construction and factorizations, and O(Kd²) per query; that algorithm is not implemented here.
A covariance for every class needs evidence in every class
In d dimensions, a class covariance estimated around its fitted mean has rank at most min(d,nₖ−1). Thus nₖ≤d forces singularity without regularization; nₖ>d is only a necessary condition, not a guarantee. In two dimensions, three noncollinear observations can suffice, but a hundred collinear observations still cannot identify two-dimensional spread. A large total sample does not rescue a tiny individual class.
QDA estimates Kd(d+1)/2 covariance parameters, compared with d(d+1)/2 for a shared covariance. That difference can matter when class counts are small. More flexible boundaries are useful when supported by the task and data; they do not make QDA uniformly better than LDA.
Adding γI gives positive definiteness for any γ>0 in exact arithmetic, but does not recreate unobserved variation. Our additive ridge is not a search over covariance pooling, and it is not a claim of compatibility with the library’s regularization parameters. A fixed numerical ridge depends on feature units. Fit any learned preprocessing on training data, and choose regularization inside the validation procedure.
Without ridge, a common invertible affine change of coordinates preserves model posterior probabilities in exact arithmetic. Mahalanobis distances stay unchanged; every determinant gains the same squared Jacobian factor, which cancels between classes. This also explains why arbitrary units do not make the original density comparison meaningless when all fitted parameters are transformed consistently. Adding the same isotropic ridge after rescaling generally breaks that invariance.
Gaussian tails can also produce confident predictions far outside the observed data. A class winning because it is broad is not evidence that an unfamiliar query truly belongs to it. This implementation has no rejection option, out-of-distribution detector, missing-value treatment or cost-sensitive decision rule. Its priors assume the intended deployment mix, and its posteriors assume the class-conditional model is adequate.
Remove one term and see what breaks
-
At (1,0), the example’s squared distances are 1 and 1/4. Why does A win? What would selecting by distance alone do?
Answer: B’s log-score advantage from distance is 3/8, but its determinant contributes −log 4. Their sum is negative, so A wins. Ignoring volume would choose B, even though its normalized density is lower there.
-
Change the prior weights to A:1 and B:8, keeping both fitted covariances unchanged. Is there still a circular boundary?
Answer: The score difference becomes 3r²/8+log 2, which is positive everywhere. B wins at every point; there is no equality boundary. Priors can eliminate a class region in this model.
-
In two dimensions, A has 100 observations but B has two. Can A’s large sample make an unregularized QDA fit invertible for B? Would ridge establish that B’s covariance is accurately estimated?
Answer: No. B’s centered covariance has rank at most one regardless of A’s count. Positive ridge defines an invertible matrix, but the missing direction is supplied by regularization. It does not establish accurate class-conditional geometry.
-
Suppose all fitted class covariance matrices become identical. Which score terms can be dropped, and what remains?
Answer: The shared log determinant and common query quadratic term cancel. The remaining class scores are affine, giving the LDA form with the same means, covariance and priors. Estimating separate covariances and estimating a pooled covariance need not produce identical matrices on actual data.
A related model does not imply identical estimation defaults
The scikit-learn guide was reread at the versioned 1.7 path, displaying 1.7.2. Its QDA derivation supplies the separate log determinant and quadratic form; its estimation section identifies an SVD route and a class-sample nₖ−1 covariance convention. This chapter follows the probabilistic model but deliberately exposes a two-dimensional ML moment calculation. It does not reproduce the library’s solver or numerical behavior.
The CS229 source is Andrew Ng’s original course material read from the summer2023 path. Its opening separates learning class-conditionals from directly fitting conditional labels and derives classification through Bayes’ rule. Its later GDA example shares a covariance, so it is cited for that general setup rather than presented as a QDA implementation. The course path is not a claimed original publication year.
The independent tests construct covariances from centered data and score through an eigendecomposition, rather than this program’s second-moment subtraction and two-by-two inverse formula. They examine the volume counterexample, unequal priors, degenerate linear boundaries, singular classes and coordinate changes. Those checks establish agreement for specified small cases, not which covariance assumptions should be trusted on a new application.
Make a prediction, then check
Two classes have identical means, covariances I and 4I, and equal priors. Which has the higher posterior at the common center?
Learning objectives
- Explain why QDA must compare distance, log determinant and prior together.
- Derive quadratic score differences and recognize linear degeneracy and priors that remove a boundary.
- Run the two-feature exact-moment example and distinguish invertibility, numerical score precision and evidence for class covariance.
Prerequisites & connections
Explore related knowledge →References
- Linear and Quadratic Discriminant Analysis (1.7.2)
scikit-learn contributors - 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. The independent reference constructs rational covariance from centered observations, then uses an orthogonal eigendecomposition for quadratic distances and log determinants. It checks 12 fits and 48 queries without reusing production raw second moments or the two-by-two inverse formula.
- Verified the volume counterexample, circle boundary, prior-driven boundary removal, affine score reduction with common covariance, exact ties, undersampled classes, ridge and invalid input. An invertible affine change preserves distances and posteriors; moments survive a 10^40 translation exactly and a 1/10^400 prior is not lost through binary floating-point conversion.
- Both languages contain the full program, six-line actual stdout, five matching display formulas, six anchors and four answered exercises. Strict MDX/KaTeX and actual React HTML pass, including MathML-to-source correspondence. article_text is the sole article path entry point in tests.
- Targeted Humanizer scanning and paragraph-level AI rereading completed; author AI check only, remains written. Exactness covers rational moments and distances; 50-digit logarithms and exponentials still round and do not certify an exact boundary winner. No library execution, real fabrication experiment, general high-dimensional algorithm, whole-site build or browser acceptance.
- Reread both complete articles, four answers, five equations and code without outstanding defects. Nine author tests and strict MDX/KaTeX/React HTML pass in both locales, with six anchors/four answers and identical full stdout.
- A third reference constructs three classes from corners with known axis Gaussian moments, applies three common shears, two translations and two prior sets, then multiplies univariate densities and normalizes with 70-digit Decimal. It uses no inverse matrix, eigendecomposition or cached log scores. Twelve fits check 36 covariances, 72 queries and 216 posterior probabilities, plus exact distances and winning labels.
- Checked definiteness/class-sample rank, ridge and units, determinant volume penalty, vanished boundaries, near-boundary rounding and probability-underflow limits, fixed-2D storage and arithmetic/bit costs. Model posteriors are not measured calibration; review is not independent human peer review.
- 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 reopened the official versioned 1.7 guide, displaying 1.7.2. Read §1.2.2.1, lines 85–108: separate class Gaussian densities and the retained class log determinant; §1.2.2.2, lines 109–120: common-covariance cancellation; §1.2.5, lines 138–145: QDA SVD and the class-centered n−1 covariance convention. The article explicitly chooses class ML denominators n_k instead of claiming library-compatible defaults. No scikit-learn run or copied code.
- CS229 Lecture Notes, Part IV: Generative Learning Algorithms · Reuses the same original Andrew Ng lecture PDF actually opened while authoring the adjacent LDA chapter in this session. Relevant inspected portion is the cover/author and printed pp. 1–2, extracted lines 0–53: generative versus discriminative models, priors, Bayes normalization and classification by class-conditional density times prior. Its §1.2 on pp. 5–6 uses shared covariance; this chapter expressly does not cite that estimator as separate-covariance QDA. No new publication-year claim or full-PDF visual audit.
- Linear and Quadratic Discriminant Analysis (1.7.2) · Root independently read official fixed 1.7.2 LDA/QDA documentation in this session, lines 85–125 for class Gaussian densities, determinant and common-covariance cancellation; lines 138–144 for class-centered SVD and n−1 convention. Rechecked chapter choice of n_k ML denominator and explicit distinction from library defaults. No library execution.
- CS229 Lecture Notes, Part IV: Generative Learning Algorithms · Root independently opened the official summer2023/cs229-notes2.pdf and read lines 0–53, printed pp.1–2: Andrew Ng header, generative/discriminative distinction, prior times class-conditional density and Bayes normalization. Course path not treated as first publication date; no full-PDF or visual audit claimed.
Related topics