Principal component analysis
主成分分析
Connect centered variance, covariance eigenvectors, SVD, and reconstruction, with a two-dimensional implementation and leakage counterexamples.
pcaKeep one reading that describes most of the movement
Two sensors record four invented observations: (13,21), (11,23), (9,17), and (7,19). Suppose both channels have comparable units. We have room to store one number per observation, plus a shared decoding rule. Keeping the first sensor would discard the second sensor’s changes. Could a combination describe the observations more economically?
Subtract the mean (10,20). The centered points are (3,1), (1,3), (−1,−3), and (−3,−1). They spread farther along the diagonal where both channels increase together than across it. Projecting onto that diagonal stores one signed coordinate. Decoding gives (12,22) for the first two observations and (8,18) for the last two. Each reconstruction has squared error 2, for a total of 8.
Principal component analysis, or PCA, chooses orthogonal directions that maximize retained variance. Equivalently, it chooses a linear subspace giving the smallest total squared reconstruction error after centering. This equivalence concerns the specified geometry; it says nothing by itself about which features predict a later target. MML, §§10.1–10.3
Center, project, and compare the unexplained part
Put n observations into the rows of an n-by-d matrix X. Let m be their featurewise mean and let Z contain the centered rows. This row convention matters: some textbooks instead place observations in columns. Define the empirical covariance here with divisor n:
The construction is a deterministic operation on a finite dataset; Gaussianity, independence, and identical sampling distributions are not prerequisites for computing it. Population interpretations need separate sampling assumptions. Using n−1 instead scales C by n/(n−1), changing its eigenvalues but leaving directions and explained-variance ratios unchanged. scikit-learn reports component variances using n−1. scikit-learn PCA, explained_variance_
For a unit direction v, the centered coordinate is . Its empirical mean is zero, so its variance is
To maximize it, differentiate the constrained objective . Since C is symmetric, the stationary equation is . The spectral theorem supplies an orthonormal eigenbasis. Expanding any unit v in that basis makes its variance a weighted average of eigenvalues, with nonnegative weights summing to one. The largest eigenvalue is therefore the maximum. Successive orthogonal directions choose the remaining largest eigenvalues. CS229, pp.5–6
For , collect the first r directions as columns of . Coordinates and reconstruction are
The residual is perpendicular to the retained subspace. Pythagoras splits each centered squared norm into retained and discarded parts. Summing gives
Eigenvalues are ordered from largest to smallest. EVR is defined only when total variance is positive. This is a best reconstruction of the data under the chosen squared-error criterion, not a best approximation of the identity matrix independently of the data. MML, §10.3, equations 10.29–10.44
For the sensor example, C is [[5,3],[3,5]]. Its eigenvalues are 8 and 2. Unit directions may be chosen as (1,1)/√2 and (−1,1)/√2. The leading coordinates are . One component retains 8/(8+2)=80% of the variance and discards total squared error . With n−1, the reported variances become 32/3 and 8/3; the same reconstruction still has error 8.
The singular value decomposition gives another route. If , then the right singular vectors are PCA directions, scores are the relevant columns of , and
The example’s singular values are √32 and √8. Work with centered Z: decomposing raw X instead optimizes approximation through the original coordinate origin, which generally solves a different problem. MML, §10.4
Fit the axes once, then reuse them
This complete standard-library program solves the two-feature case. For covariance [[a,b],[b,c]], a leading direction has angle . Its perpendicular supplies the other direction. We evaluate variances from squared projected coordinates instead of subtracting nearly equal eigenvalue formulas. The code retains one or both coordinates and can reconstruct them.
import math
def point2(row):
try:
p = tuple(float(v) for v in row)
except (TypeError, ValueError, OverflowError) as error:
raise ValueError("numeric two-dimensional point required") from error
if len(p) != 2 or any(not math.isfinite(v) or abs(v) > 1e100 for v in p):
raise ValueError("two finite coordinates with magnitude <= 1e100 required")
return p
def fit_pca2(rows):
points = tuple(point2(p) for p in rows)
n = len(points)
if n < 2:
raise ValueError("at least two training points required")
origin = points[0]
mean = tuple(origin[j]+math.fsum((p[j]-origin[j])/n for p in points) for j in (0,1))
z = tuple((p[0]-mean[0], p[1]-mean[1]) for p in points)
a = math.fsum(x*x/n for x,y in z)
b = math.fsum(x*y/n for x,y in z)
c = math.fsum(y*y/n for x,y in z)
theta = 0.5*math.atan2(2*b, a-c)
u = (math.cos(theta), math.sin(theta))
v = (-u[1], u[0])
axes = (u,v)
variances = tuple(math.fsum((x*w[0]+y*w[1])**2/n for x,y in z)
for w in axes)
total = math.fsum(variances)
ratios = tuple(value/total for value in variances) if total else None
return {"mean": mean, "axes": axes, "variances": variances,
"ratios": ratios, "covariance": ((a,b),(b,c))}
def transform2(model, rows, components=1):
if type(components) is not int or components not in (1,2):
raise ValueError("retain one or two components")
result = []
for row in rows:
p = point2(row)
z = (p[0]-model["mean"][0], p[1]-model["mean"][1])
result.append(tuple(z[0]*w[0]+z[1]*w[1] for w in model["axes"][:components]))
return result
def inverse2(model, scores):
result = []
for row in scores:
s = tuple(float(v) for v in row)
if len(s) not in (1,2) or any(not math.isfinite(v) or abs(v) > 1e101 for v in s):
raise ValueError("one or two finite bounded scores required")
result.append(tuple(model["mean"][j]+math.fsum(v*w[j] for v,w in zip(s,model["axes"]))
for j in (0,1)))
return result
points = [(13,21), (11,23), (9,17), (7,19)]
model = fit_pca2(points)
scores = transform2(model, points)
reconstructed = inverse2(model, scores)
error = math.fsum((x-y)**2 for p,q in zip(points,reconstructed) for x,y in zip(p,q))
assert model["mean"] == (10.,20.)
assert math.isclose(model["variances"][0], 8.)
assert math.isclose(model["ratios"][0], .8)
assert math.isclose(error, 8.)
assert fit_pca2([(3,4),(3,4)])["ratios"] is None
print("variances:", model["variances"], "reconstruction SSE:", error)
fit_pca2 saves the training mean and axes; transform2 applies them without fitting again. inverse2 restores the mean and uses zero for discarded coordinates. The printed variances are approximately (8,2), with reconstruction SSE 8. Constant data return None for the undefined explained-variance fractions, rather than calling 0/0 a perfect percentage.
This implementation uses O(n) work and O(n) working storage to fit two-dimensional data; transforming or reconstructing m observations costs O(m) work and output storage. A general d-feature dense covariance approach costs O(nd²+d³), with O(d²) covariance storage in addition to any stored data. A usual dense full SVD costs O(nd min(n,d)); truncated methods have different costs. Forming squares the nonzero singular-value ratio, so direct SVD can better preserve small directions numerically.
The teaching API accepts finite input coordinates of magnitude at most and bounded reconstruction scores. These limits avoid overflow in its small-matrix arithmetic. They do not repair information already lost when a tiny difference is represented beside a huge offset, or underflow of extremely small squared variations. For large dimensions or demanding precision, use a tested eigensolver or SVD implementation instead of extending this angle formula.
Variance depends on units and does not identify meaning
Centering removes the mean; standardizing also divides each feature by a scale such as its training standard deviation. They are different operations. PCA on standardized features optimizes squared error in those standardized coordinates, which weights the original features differently. scikit-learn’s PCA centers automatically but does not perform featurewise scaling. Constant features need a convention before division by their standard deviation. CS229, pp.2–3; scikit-learn PCA, input contract
A direction’s sign is arbitrary: replacing v by −v flips its scores and leaves reconstruction unchanged. Equal eigenvalues permit rotations within their eigenspace. If a truncation boundary cuts through a repeated eigenvalue, even the retained subspace need not be unique. With a strict gap between retained and discarded eigenvalues, the retained projector is unique, although its basis can still have sign or rotation freedom. Near a tie, small data changes can rotate individual components substantially.
Consider four equally likely points at (±10,±1), with a label determined by the sign of the second coordinate. The first principal component keeps the horizontal coordinate and retains 100/101 of the variance, about 99.01%. Each horizontal value nevertheless occurs with both labels equally often. The discarded direction contains all the label information in this constructed example. Large variance is not automatically useful signal, and small variance is not automatically noise. Outliers and curved structure can also make a linear squared-error summary unsuitable.
For an ordinary held-out evaluation, fit the mean, any scales, and PCA axes only on the training data, inside each training fold when using cross-validation. Transform validation or test points using those saved quantities. PCA can leak evaluation information even though it ignores labels. Fitting on all available unlabeled points is a different, transductive protocol that must be stated explicitly. scikit-learn common pitfalls, §§12.1–12.2
Check the reconstruction, not just the component name
- Reconstruct (13,21) using the example’s leading component. Answer: subtract (10,20), project (3,1) onto (1,1)/√2 to get (2,2), and add the mean. The reconstruction is (12,22), with squared error 2.
- Change the covariance divisor from 4 to 3. Does the retained fraction change? Answer: no. Eigenvalues become 32/3 and 8/3, their ratio remains 80%, and the total one-component reconstruction SSE remains 8.
- For points (1,0),(−1,0),(0,1),(0,−1), is there a unique best one-dimensional direction? Answer: no. C=I/2, every unit direction retains variance 1/2, and every such projection has total SSE 2.
- A test point is centered by subtracting itself before applying training axes. What goes wrong? Answer: every such point gets zero coordinates and reconstructs as the training mean. Use the saved training mean; fitting a new mean or axes on the evaluation set also changes the evaluation protocol.
From perpendicular residuals to matrix approximations
Pearson’s 1901 paper studied lines and planes minimizing squared perpendicular distances, distinguished that problem from choosing one response direction in regression, and showed that the fitted line or plane passes through the data centroid. These are specific historical contributions supporting the geometric formulation here; the modern SVD implementation should not be read back into the original notation. Pearson, pp.559–562, original scan
PCA connects projection geometry, covariance eigendecomposition, and low-rank matrix approximation. Kernel PCA changes the feature space; probabilistic formulations specify a generative noise model; incremental and randomized methods change how the approximation is computed. These extensions address different questions. To investigate an empirical PCA result, record centering and units, retained dimension, reconstruction error, and stability, then test any downstream prediction claim on data withheld from fitting.
Make a prediction, then check
Four equally likely points (±10,±1) have labels determined by the sign of their second coordinate. PC1 retains 100/101 of the variance. How much label discrimination does it preserve?
Learning objectives
- Derive the equivalence of maximum variance and minimum squared reconstruction from centered covariance, using SVD with row-oriented data.
- Fit, project, and reconstruct with a two-dimensional standard-library program; calculate 80% variance, error 8, and the n versus n−1 distinction.
- Identify sign and repeated-eigenvalue nonuniqueness, unit changes, a predictive counterexample, and train/evaluation preprocessing leakage.
Prerequisites & connections
Explore related knowledge →References
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020 - CS229 — Principal Components Analysis
Andrew Ng - scikit-learn — PCA
scikit-learn developers - scikit-learn — Common pitfalls and recommended practices
scikit-learn developers - On Lines and Planes of Closest Fit to Systems of Points in Space
Karl Pearson · 1901
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex multi-agent technical check: primary-source verification, derivation and numerical assertions, bilingual comparison, and review by another agent or the parent; no independent human peer review.
- Independently checked the four-point mean, covariance, and reconstruction with rational arithmetic; checked orthogonal axes, the projector, 80% variance, and discarded squared singular value equal to error 8.
- Compared 24 random integer datasets against 75-digit Decimal characteristic roots,721 independent projection directions per dataset, and eigen-equation residuals.
- Checked sign flips, repeated-eigenvalue rotations, rank-one and constant data, translation and row order, two-dimensional roundtrip, test-only transformation, unit changes, and the 99.01%-variance/no-label-information counterexample.
- Used a first-observation origin for mean accumulation so constant floating-point samples do not acquire spurious variance from division rounding; checked finite range, n versus n−1, two-dimensional versus general complexity, and bilingual math/code.
- The parent reviewed n/n−1 scaling, SVD reconstruction, sign/repeated-eigenvalue ambiguity, the low-variance signal counterexample, saved means and evaluation leakage, and executed direction/error/boundary checks without treating PCA as a prediction guarantee.
- The parent executed all 37 independent classical-method checks successfully; bilingual code, display equations, six main anchors and four answered exercises were individually compared.
Source locations checked:
- Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft) · Actual local /tmp/aiwiki-mml-book.pdf, 2024-01-15 draft; printed pp.318–334/PDF pp.324–340, §§10.1–10.4. Especially equations10.29–10.44 for reconstruction and10.45–10.49 for SVD. Samples are columns in source, explicitly transposed to article's row convention. Did not repeat unqualified source wording about approximating identity or equate retained variance with predictive information.
- CS229 — Principal Components Analysis · Actual six-page PDF read: pp.2–3 centering and optional variance scaling; pp.5–6 Rayleigh quotient, largest eigenvector, orthogonal components, reconstruction objective. No publication year asserted.
- scikit-learn — PCA · PCA input contract and Attributes: input centered but not feature-scaled; components are right singular vectors of centered row data; explained_variance_ uses n_samples−1; mean_ comes from training data. Current stable documentation read, no claim about recently added solver features.
- scikit-learn — Common pitfalls and recommended practices · Actual §§12.1–12.2, lines104–140: training fit versus test transform, split before fitted preprocessing, fold-local pipeline fitting, and explicit inclusion of PCA in leakage warning.
- On Lines and Planes of Closest Fit to Systems of Points in Space · Original scanned pp.559–562 / PDF pp.1–4 actually viewed as images from /tmp/aiwiki-pearson1901.pdf: perpendicular residual criterion versus directed regression, centroid passage, constrained equations. Accessible mirror of Lyon reprint; Lyon URL failed fetch. Scan footer verifies1901 and journal2:559–572. Only these four pages claimed read, not the whole paper.
Related topics