Loading…
Loading…
Derive principal components from a centered data matrix, connect variance to singular values, and calculate the error of a low-rank reconstruction.
A table with many measured features can contain far fewer independent patterns than its number of columns suggests. Two measurements may move together, or most observations may lie close to a plane inside a much larger feature space. Dimensionality reduction asks for coordinates that describe this structure with fewer numbers. To make that request mathematical, we must specify what the reduced coordinates preserve and how reconstruction error is measured.
Principal component analysis, or PCA, chooses orthogonal directions that retain as much variation as possible. Singular value decomposition, or SVD, gives the coordinates and a precise account of the variation discarded. The same calculation can be understood as fitting a low-dimensional affine subspace to the observations. This connection explains both the centering step and the role of squared singular values.
Unlike regression, PCA does not single out one column as a response variable. All the selected features contribute to the geometry. Consequently, the units used to measure them influence the answer: changing metres to centimetres changes ordinary Euclidean distances unless we also change the preprocessing. Choosing features and their scales is therefore part of specifying the mathematical problem.
Let contain observations. Row is , where is a column vector of features. Keep this convention throughout: directions live in feature space , while a list of scores for all observations lives in .
Definition
The mean feature vector and centered matrix are
Here has every entry equal to one. The sample covariance matrix is
The columns of sum to zero because . Also and : centering twice changes nothing. Its null space contains the constant vector, so . This rank bound explains why centering can produce a zero singular value even when the raw table has full row rank. Subtracting the mean removes a location, rather than a genuine direction of variation around that location.
For a unit direction , the score of observation is . The score vector is , whose mean is zero. Its sample variance is therefore
Definition
Write a reduced SVD as
where and have orthonormal columns, and with . Positive singular values number . The right singular vectors are PCA loading directions, and are their score vectors.
The full SVD instead uses square orthogonal matrices and , with a rectangular diagonal middle matrix. It supplies additional zero directions when required. For any , both versions give the same leading loading matrix and reduced coordinates . A score is an observation's coordinate; a loading is a direction used to measure that coordinate. Their different dimensions make them easy to distinguish.
Theorem
Let be centered and let . Pad the singular-value list with zeros through index when necessary. The covariance eigenvalues are
Among unit directions, maximizes score variance. More generally, for with , the maximum of is , attained by the first right singular vectors.
For nonzero total variation, the explained-variance fraction of component and the cumulative fraction of the first components are
The denominator cancels in these fractions. Using a population normalization of would change covariance eigenvalues, but not principal directions or explained-variance fractions. If every observation is identical, : every score is zero and there is no positive total variation from which to form a percentage.
Theorem
For orthonormal , the reconstruction in centered coordinates is , and
Thus PCA also minimizes total squared reconstruction error. Its solution is
Moreover, minimizes among all matrices of rank at most . In the original coordinates, reconstruct with .
The squared Frobenius norm is the sum of the squares of all matrix entries. Consequently the error above totals deviations across all observations and all features; it is not a variance per observation or an average per table entry. A chosen rank should be interpreted together with this scale. An eighty-percent retained fraction can be acceptable for one purpose and lose a crucial small-variance feature for another. The optimization states exactly which squared-distance criterion PCA solves.
The score table has orthogonal columns as well as a zero column mean. In fact,
Thus different retained scores have zero sample covariance. Their variances appear in decreasing order, so one can read the contribution of each retained coordinate directly from the diagonal. Zero covariance describes the second moments of this score table; it does not, by itself, establish statistical independence of the underlying measurements. PCA constructs orthogonal linear coordinates and optimizes their total variation without specifying a probability model for the observations.
Reconstruction uses the same loading directions in reverse. Given a score row, multiply it by the transpose of the loading matrix to put it back into feature space. The reconstructed centered row lies inside the selected subspace, while its residual is perpendicular to every retained direction. This perpendicularity is a useful computational check: multiplying the residual table by the loading matrix should give zero, up to numerical rounding. The discarded part cannot be recovered from the retained scores alone because the projection maps many different original rows to the same reduced row.
PCA also differs from line fitting with a designated response variable. Its distance to a candidate line is the shortest perpendicular distance in the selected feature metric. Ordinary regression instead measures errors in the response coordinate while treating the explanatory values as given. Even for two features and a one-dimensional fit, these objectives can select different lines. Before applying an algorithm, identify which measurements may vary in the error model and whether a prediction or a geometric representation is the intended output.
Proof
The symmetric matrix is positive semidefinite, since . Choose an orthonormal eigenbasis, ordered by nonincreasing eigenvalue. For a positive eigenvalue , set . Then , which is one for and zero otherwise. If an eigenvalue is zero, , so ; no division by a zero singular value is needed. The constructed vectors span the column space of . Complete them to an orthonormal basis of , giving square , and keep the full feature eigenbasis . Let have the positive on its first diagonal positions and zeros elsewhere. Column by column, , hence . This proves existence even for a rectangular or rank-deficient data matrix.
Expand a unit vector as . Then because . For several directions, put . Orthogonal projection gives and . Hence is at most the sum of the largest eigenvalues. Taking their eigenvectors attains the bound.
The projection identity follows observation by observation. Each centered row splits into a part in the chosen subspace and a perpendicular remainder. Pythagoras says their squared lengths add. Summing over rows converts this geometric statement into the Frobenius identity. In SVD coordinates, the discarded rank-one terms are orthogonal under the Frobenius inner product, so each contributes exactly its squared singular value to the error.
To see why allowing an arbitrary rank- matrix cannot improve the answer, let its rows lie in a subspace of dimension at most . Projecting each row of onto is at least as accurate as choosing that row of the candidate matrix. Among such subspaces, the variance argument has already found the best one. This proves the low-rank statement as well as the geometric PCA statement.
Truncation is also optimal for the spectral norm . For ,
To prove the lower bound, restrict any candidate of rank at most to . Its kernel there contains a unit vector , because the domain has dimension . Then and . The truncated residual attains this bound: its largest singular value is precisely the first discarded one. The spectral error measures the worst amplification of a unit direction; the squared Frobenius error instead adds squared losses over all discarded directions.
Worked example
Consider four observations, with rows
The columns of are orthogonal, and
Choose , . Then , , and
Multiplying reproduces . The first score vector is , with sample variance . It retains of the total variation. Keeping only this coordinate and restoring the mean gives
The last two observations each have an error of magnitude one. Total squared error is , agreeing with the discarded value . Averaged over the eight entries, the squared error is , so the entrywise root mean square error is .
This example separates four quantities often called the size of a component: the singular value, its squared value, the sample variance, and the explained fraction. They describe the same direction but answer different questions. The singular value is a length in score space; division of its square by gives a sample variance. Ratios require the squares because orthogonal energy, rather than unsquared length, is additive.
Worked example
For the same raw observations,
The off-diagonal entry is now , so is not an eigenvector of . An SVD of would select a different leading direction, influenced by the data's location relative to the origin. Projecting the raw rows onto the horizontal axis through the origin alone would discard their entire second coordinate, producing squared error .
Centered PCA instead fits the horizontal line through and has error . These are different fitting problems. The best raw rank-one direction need not be horizontal; the comparison explains why the raw horizontal projection is not the centered reconstruction.
For a new observation , subtract the training mean to obtain . Its first score is and its one-component reconstruction is . Use the same mean and loading directions when transforming additional observations, so their scores share one coordinate system.
The affine viewpoint is useful here. The retained centered subspace passes through zero, but adding the mean translates it back to the part of feature space occupied by the data. Centering therefore allows the dimensions to describe variation around the observations, rather than spending a direction to describe their displacement from zero. A reduced score table alone cannot restore the original location: the mean vector is also needed for decoding.
Worked example
Multiply the second feature by three. After centering, the new matrix has rows , , , , so its scatter matrix is . Its first loading is now , the retained fraction is , and the rank-one squared error is .
Alternatively, standardize each original centered column by its sample standard deviation. Those standard deviations are and . The standardized scatter matrix is , so its covariance matrix is . Every unit direction has score variance one. There is no preferred single first component; any orthonormal pair spans the same two-dimensional space.
Standardization selects a different metric by giving features comparable scales. It may be useful when units are arbitrary, but it also removes meaning from an intentional difference in feature variability. State whether the objective measures error in original units or standardized units before interpreting the retained fraction. A zero-variance feature has no positive standard deviation to divide by; it contributes no centered variation.
The eigenvalue definitions, real diagonalization, and diagonalization tests provide the prerequisites. Consider a real square matrix with a real eigenbasis, taking each column of to have unit length. The eigenvectors need not be orthogonal. A sufficient dominant-modulus condition is
Here is a unit initial vector. Normalize after each multiplication and expand its unnormalized powers in the fixed eigenbasis:
The remaining coefficients decay geometrically relative to the first, so the eigenvector line is approached. The nonzero leading coefficient also ensures that the normalization denominator cannot vanish. The ratios concern the eigenbasis coordinates; bounds in Euclidean norm additionally depend on the geometry of that basis. The sharper orthogonal-coordinate estimate below is available for a symmetric scatter matrix.
The coefficient condition means solving , rather than taking a dot product with . For a nonorthogonal eigenbasis, can be nonzero even when . Conversely, a nonzero dot product does not ensure a nonzero first eigenbasis coordinate. If that coordinate is absent, multiplication does not create it. The strict modulus gap excludes a second mode of equal asymptotic size, which could otherwise persist alongside the first.
When , normalized vectors can alternate signs while approaching the same line. The Rayleigh quotient still tends to : it is continuous near either unit representative of that line and has the same value at opposite signs. For nonsymmetric , this limit does not supply the extremal-variance interpretation available for a symmetric matrix. In particular, intermediate quotient values need not lie between the smallest and largest real eigenvalues.
Worked example
Take
These displayed basis columns are unnormalized eigenvectors. With , their coordinates are , so the dominant coefficient is present. Normalizing the basis columns rescales these coefficients without changing which ones are zero. The raw iterates are and ; has . The dominant line is horizontal, and the signs alternate. Starting instead along stays in the eigenvalue-one direction despite its nonzero dot product with the horizontal eigenvector.
For a unit right eigenvector, subtracting still gives eigenvalue zero along , but usually changes the other original eigenvectors. To preserve their eigenpairs, take a left eigenvector with and , and subtract . In the example, and give
The first sends the original eigenvector to ; the paired update preserves it. For a symmetric matrix, left and right unit eigenvectors can coincide, recovering the familiar orthogonal deflation formula.
When only the first principal direction is needed, power iteration can avoid a full decomposition. Let have eigenvalues and orthonormal eigenvectors . Start with a unit vector whose first coefficient is nonzero, and repeat
Each step amplifies the first component relative to the others. Before normalization, the iterate is proportional to ; after factoring out , every other eigenvector's coefficient contains . The ratio of the perpendicular part to the leading part is at most
Thus the direction converges geometrically to up to sign. Normalizing keeps vector lengths manageable without changing this ratio. A small spectral gap gives slower convergence; an initial vector perpendicular to the first direction never gains that component. For a unit iterate, estimates the leading eigenvalue. Once an exact leading pair is known, removes that mode. With a large data table, evaluate without explicitly forming the scatter matrix.
Worked example
Take and . Two iterations give
The second coordinate divided by the first is successively , , and . These ratios exhibit the spectral factor . The iterates approach the first PCA loading .
SVD also resolves coefficient ambiguity in a fit. For a real matrix , retain its positive singular values in . Define
Direct SVD multiplication verifies the four Penrose identities:
In particular, projects orthogonally onto the column space, while projects onto the row space. Both are symmetric and idempotent. The first is for full row rank; the second is for full column rank. For a square invertible matrix these become the usual two-sided inverse relations, and . For a singular fit, the projections identify exactly which response and coefficient directions the data determine.
For any response , this is the unique minimum-norm least-squares coefficient. Indeed, is the orthogonal projection of onto the column space of . It attains the smallest residual. Every other least-squares coefficient is with . Since lies in the span of , it is perpendicular to , giving . Equality of norms requires .
When the equations are consistent, the residual vanishes and this chooses the shortest exact solution. Otherwise it chooses the shortest coefficient among all equally accurate fits. Taking reciprocals only of positive singular values distinguishes this construction from trying to invert a singular matrix. The same SVD supplies both data-reduction directions and a precise rule for selecting coefficients along directions the observations determine.
In left singular coordinates, the coefficient of is . A portion of perpendicular to the column space cannot be fitted and remains in the residual; zero right singular directions create the freedom to add null-space vectors. The minimum-norm choice sets those free coordinates to zero. This coordinate description explains both the fit and the coefficient selection through one division per positive singular value. Keeping only some positive singular directions instead solves a restricted fitting problem in their selected span, rather than the same unrestricted minimum-norm least-squares problem.
Worked example
Let and . Then , so . All exact solutions are , and
The minimum occurs at , confirming and its squared norm . The difference from this solution is , a null-space direction perpendicular to .
The following calculation implements the first example. Vt stores loading
directions as rows, because the numerical SVD returns the transpose of .
import numpy as np
X = np.array([[12., 5.], [8., 5.], [10., 6.], [10., 4.]])
mean = X.mean(axis=0)
A = X - mean
U, s, Vt = np.linalg.svd(A, full_matrices=False)
k = 1
scores = A @ Vt[:k].T
reconstruction = scores @ Vt[:k] + mean
fractions = s**2 / np.sum(s**2)
squared_error = np.sum((X - reconstruction)**2)
print(fractions) # [0.8 0.2]
print(squared_error) # 2.0, up to rounding
A numerical routine can flip the sign of a loading and the corresponding score column. Their product, the reconstruction, remains unchanged. Compare subspaces, explained variances, and reconstructed matrices when checking two implementations. If singular values tie across the chosen cutoff, even the optimal retained subspace can be nonunique. With a strict gap at that cutoff, the subspace is determined even though the signs of its basis vectors are not.
Common mistake
For the first example, the unsquared ratio is not the retained variance fraction. The correct value is . Also distinguish , whose columns describe feature directions, from , whose rows describe observations. Confusing the two usually creates a dimension mismatch before it creates a plausible interpretation.
Center the columns, select a metric, and compute the SVD of the centered matrix. Right singular vectors supply loading directions; multiplying by them supplies scores. Covariance eigenvalues are squared singular values divided by . The first components maximize retained variance and minimize orthogonal squared reconstruction error. Restore the mean when returning to the original feature coordinates.
Checkpoint
Separate centering, projection, and restoring the mean.
Checkpoint
Form cumulative sums of squared singular values.
Checkpoint
Compare a tie inside a retained subspace with a tie across the truncation cutoff.
The explained fraction is , and squared error is . The new point has centered coordinates and first score . Its centered reconstruction is ; adding gives .
Total squared singular value is . One component retains , below . Two retain , above , so the smallest rank is two. The discarded squared singular value is , which is the remaining total squared reconstruction error.
Every unit vector in the eigenvalue-five eigenspace maximizes the variance, so a first loading is not unique, even after accounting for sign. The full two-dimensional eigenspace is unique because its eigenvalue is separated from zero. Any orthonormal basis of this plane retains total variance ; changing that basis rotates the scores without changing their reconstruction.