Unit 8, lesson 59

PCA with SVD and Reconstruction

How the singular value decomposition of a centered data matrix gives principal component loadings, scores and explained variance, and why keeping k components gives the best low-rank reconstruction with a known error.

  • Video 59
  • Principal Components and Dimensionality Reduction

Two temperature probes mounted side by side on one machine record nearly the same numbers, so a table with one column per probe stores much of its information twice. How many numbers per row does such a table really need, and what is lost by keeping fewer? The lesson on covariance, eigenvectors and PCA found the principal directions as eigenvectors of the sample covariance matrix. This lesson computes the same directions directly from the centered data matrix with the singular value decomposition, reads off the scores and the explained variance, and measures exactly what a reconstruction from kk components keeps and what it loses.

Key terms

Singular value decomposition

Definition Let XX be an n×pn \times p data matrix whose rows are the observations x1⊤,…,xn⊤\mathbf{x}_1^{\top}, \dots, \mathbf{x}_n^{\top}, let xˉ\bar{\mathbf{x}} be their mean, and let XcX_c be the centered matrix whose iith row is (xi−xˉ)⊤(\mathbf{x}_i - \bar{\mathbf{x}})^{\top}. Put q=min⁡(n,p)q = \min(n, p). A thin singular value decomposition of XcX_c is a factorization

Xc=USV⊤X_c = U S V^{\top}

in which UU is n×qn \times q with orthonormal columns, so U⊤U=IqU^{\top}U = I_q, the matrix S=diag⁡(σ1,…,σq)S = \operatorname{diag}(\sigma_1, \dots, \sigma_q) is q×qq \times q with σ1≥⋯≥σq≥0\sigma_1 \ge \dots \ge \sigma_q \ge 0, and VV is p×qp \times q with orthonormal columns, so V⊤V=IqV^{\top}V = I_q. Every real matrix has one. Written column by column, it is a sum of rank-one matrices,

Xc=∑j=1qσjujvj⊤,X_c = \sum_{j=1}^{q} \sigma_j \mathbf{u}_j \mathbf{v}_j^{\top} ,

where uj\mathbf{u}_j and vj\mathbf{v}_j, the jjth columns of UU and VV, are the left and right singular vectors. In PCA the columns of VV are the principal axes, also called loadings. The singular values are determined by XcX_c, but the vectors are not. Each pair (uj,vj)(\mathbf{u}_j, \mathbf{v}_j) can change sign together. When a positive singular value is repeated, any orthonormal basis of the space spanned by its right singular vectors can serve, with uj=Xcvj/σj\mathbf{u}_j = X_c\mathbf{v}_j / \sigma_j. The vectors that belong to zero singular values can be any orthonormal vectors that complete the others.

In plain words The decomposition writes the centered table as a sum of qq layers. Each layer has a direction in feature space, the vector vj\mathbf{v}_j with one entry per feature, a column uj\mathbf{u}_j with one entry per observation, and a size σj\sigma_j. Directions live in Rp\mathbb{R}^p and observation columns in Rn\mathbb{R}^n, and keeping the two apart prevents most dimension errors. In NumPy, np.linalg.svd(Xc, full_matrices=False) returns UU, the singular values and V⊤V^{\top}, so the loadings are the rows of its third output.

Example On this page a tuple written for a vector stands for a column. The constructed cloud (1,1)(1, 1), (2,2)(2, 2), (3,3)(3, 3) has mean (2,2)(2, 2), so the rows of XcX_c are (−1,−1)(-1, -1), (0,0)(0, 0) and (1,1)(1, 1), with n=3n = 3, p=2p = 2 and q=2q = 2. One thin SVD has

σ1=2,σ2=0,v1=12(1,1),u1=12(−1,0,1).\begin{gathered} \sigma_1 = 2, \quad \sigma_2 = 0, \\[0.4em] \mathbf{v}_1 = \tfrac{1}{\sqrt{2}}(1, 1), \\[0.4em] \mathbf{u}_1 = \tfrac{1}{\sqrt{2}}(-1, 0, 1). \end{gathered}

The product σ1u1v1⊤\sigma_1 \mathbf{u}_1 \mathbf{v}_1^{\top} has first row 2⋅12⋅(−1)⋅(1,1)=(−1,−1)2 \cdot \tfrac12 \cdot (-1) \cdot (1, 1) = (-1, -1), and its other rows are (0,0)(0, 0) and (1,1)(1, 1), so this one layer already equals XcX_c. The second pair is far from unique. The vector v2\mathbf{v}_2 must be ±12(1,−1)\pm\tfrac{1}{\sqrt{2}}(1, -1) to keep the columns of VV orthonormal, but u2\mathbf{u}_2 can be any unit vector orthogonal to u1\mathbf{u}_1, because it is multiplied by σ2=0\sigma_2 = 0.

Singular value

Definition The singular values σ1≥⋯≥σq≥0\sigma_1 \ge \dots \ge \sigma_q \ge 0 of XcX_c are the diagonal entries of SS. Because U⊤U=IqU^{\top}U = I_q,

Xc⊤Xc=VS2V⊤,X_c^{\top}X_c = V S^2 V^{\top},

so each vj\mathbf{v}_j is an eigenvector of Xc⊤XcX_c^{\top}X_c with eigenvalue σj2\sigma_j^2. For n≥2n \ge 2 the sample covariance matrix is C=Xc⊤Xc/(n−1)C = X_c^{\top}X_c / (n - 1), so vj\mathbf{v}_j is also an eigenvector of CC, with eigenvalue

λj=σj2n−1.\lambda_j = \frac{\sigma_j^2}{n - 1} .

When p>qp > q, completing the columns of VV to an orthonormal basis of Rp\mathbb{R}^p adds p−qp - q eigenvectors of CC with eigenvalue 00. The rank of XcX_c is the number of positive singular values, and the squares of the singular values add up to the sum of the squared entries of XcX_c, written ∥Xc∥F2\lVert X_c \rVert_F^2 for the squared Frobenius norm. The rows of XcX_c add to the zero vector, so the rank of XcX_c is at most min⁡(n−1,p)\min(n - 1, p).

In plain words A singular value measures how far the centered cloud stretches along its axis. Its square is the sum of the squared coordinates of all observations along vj\mathbf{v}_j, and dividing by n−1n - 1 turns that sum into the variance along the axis. A zero singular value means no spread at all in that direction. With fewer observations than features, centering leaves at most n−1n - 1 directions with positive variance. Singular values and covariance eigenvalues are related but not equal, so check which of the two a program reports.

Example A constructed centered cloud has the rows (−2,−1)(-2, -1), (−2,1)(-2, 1), (2,−1)(2, -1) and (2,1)(2, 1), so n=4n = 4 and p=2p = 2, and its feature means are already 00. The squared first coordinates add to 1616, the squared second coordinates add to 44 and the cross-products 2−2−2+22 - 2 - 2 + 2 cancel, so Xc⊤Xc=diag⁡(16,4)X_c^{\top}X_c = \operatorname{diag}(16, 4). Hence σ1=4\sigma_1 = 4 and σ2=2\sigma_2 = 2, with axes v1=±(1,0)\mathbf{v}_1 = \pm(1, 0) and v2=±(0,1)\mathbf{v}_2 = \pm(0, 1). The covariance matrix is diag⁡(16/3,4/3)\operatorname{diag}(16/3, 4/3), whose eigenvalues are σj2/3\sigma_j^2 / 3. The squared entries add to 20=16+420 = 16 + 4, and the rank is 22. For the cloud of the previous card the singular values are 22 and 00, so its rank is 11 and its covariance eigenvalues are 4/2=24/2 = 2 and 00.

Principal component scores

Definition Given the loadings VV, the principal component score matrix is

T=XcV=US,T = X_c V = U S ,

an n×qn \times q matrix whose entry tij=(xi−xˉ)⊤vjt_{ij} = (\mathbf{x}_i - \bar{\mathbf{x}})^{\top}\mathbf{v}_j is the coordinate of observation ii along axis jj. The second equality holds because V⊤V=IqV^{\top}V = I_q. Each score column has mean 00 and sample variance λj=σj2/(n−1)\lambda_j = \sigma_j^2/(n - 1), and different score columns are uncorrelated, since T⊤T=S2T^{\top}T = S^2 is diagonal. A new observation x\mathbf{x} gets the scores t=Vk⊤(x−xˉ)\mathbf{t} = V_k^{\top}(\mathbf{x} - \bar{\mathbf{x}}) on the first kk axes, where VkV_k holds the first kk columns of VV, and the mean and loadings are the ones fitted on the training data, never refitted on the new observation. A score changes sign when its loading does. On this page a loading is a unit vector. Some texts call λj vj\sqrt{\lambda_j}\, \mathbf{v}_j the loading, so check the scaling before comparing numbers.

In plain words A loading is a direction in feature space with one entry per feature, and it says which mixture of features defines an axis. A score is one observation’s coordinate along that axis, and a row of scores has one entry per retained axis. A reconstructed observation, in the next cards, is a third object, a point back in feature space with one entry per feature.

Example For the four-point cloud with v1=(1,0)\mathbf{v}_1 = (1, 0) and v2=(0,1)\mathbf{v}_2 = (0, 1), the first scores are −2-2, −2-2, 22, 22 and the second scores are −1-1, 11, −1-1, 11. The first score column equals σ1u1\sigma_1 \mathbf{u}_1 with u1=12(−1,−1,1,1)\mathbf{u}_1 = \tfrac12(-1, -1, 1, 1), and its sample variance is 16/3=λ116/3 = \lambda_1. The new observation (3,2)(3, 2) has first score (3,2)⋅(1,0)=3(3, 2) \cdot (1, 0) = 3, because the training mean is 00. A program that returns v1=(−1,0)\mathbf{v}_1 = (-1, 0) reports the score −3-3, and both describe the same position. The computation in NumPy reads as follows.

import numpy as np

X = np.array([[-2, -1], [-2, 1], [2, -1], [2, 1]], dtype=float)
mean = X.mean(axis=0)                     # training mean
U, s, Vt = np.linalg.svd(X - mean, full_matrices=False)
scores = (X - mean) @ Vt.T                # equals U * s
new_scores = (np.array([3.0, 2.0]) - mean) @ Vt.T

Here s is [4, 2], and the signs of the rows of Vt, and with them the signs of the scores, depend on the library.

Explained variance

Definition The variance explained by component jj is λj=σj2/(n−1)\lambda_j = \sigma_j^2/(n - 1), the sample variance of its scores. The total variance is the sum of the pp feature variances, which equals the trace of CC and the sum of all its eigenvalues, with λl=0\lambda_l = 0 for l>ql > q. When Xc≠0X_c \ne 0, the explained variance ratio of component jj is

λj∑l=1pλl=σj2∑l=1qσl2,\frac{\lambda_j}{\sum_{l=1}^{p} \lambda_l} = \frac{\sigma_j^2}{\sum_{l=1}^{q} \sigma_l^2} ,

and the cumulative ratio of the first kk components is the sum of their ratios. When every feature is constant, Xc=0X_c = 0 and the ratio is undefined rather than zero. The ratios depend on the scaling of the features, so PCA on centered raw features and PCA on standardized features give different ratios, and they describe the data the PCA was fitted on.

In plain words The ratio is the share of the total squared spread around the mean that one axis carries. A first ratio of 0.80.8 says that the first axis holds 80 percent of the sum of squared distances from the mean in the fitting data. It is not a measure of predictive value, and it does not say how much of a new observation will be kept.

Example For the four-point cloud the ratios are 16/20=0.816/20 = 0.8 and 4/20=0.24/20 = 0.2, and for the rank-one cloud the first ratio is 4/4=14/4 = 1. Now record the second feature of the four-point cloud in units ten times smaller, so its values become −10-10, 1010, −10-10 and 1010. The squared singular values become 400400 and 1616, the first principal axis switches to the second feature, and its ratio is 400/416≈0.9615400/416 \approx 0.9615. The observations are the same, and only the units changed.

Low-rank reconstruction

Definition For 1≤k≤q1 \le k \le q, the rank-kk reconstruction of the centered matrix keeps the first kk terms of the decomposition,

X^c,k=UkSkVk⊤=TkVk⊤=XcVkVk⊤,\begin{aligned} \hat{X}_{c,k} &= U_k S_k V_k^{\top} \\[0.4em] &= T_k V_k^{\top} = X_c V_k V_k^{\top}, \end{aligned}

where UkU_k, VkV_k and TkT_k hold the first kk columns of UU, VV and TT, and Sk=diag⁡(σ1,…,σk)S_k = \operatorname{diag}(\sigma_1, \dots, \sigma_k). Row ii is the orthogonal projection of xi−xˉ\mathbf{x}_i - \bar{\mathbf{x}} onto the span of v1,…,vk\mathbf{v}_1, \dots, \mathbf{v}_k. In the original units the reconstructed observation is

x^i=xˉ+Vkti,ti=Vk⊤(xi−xˉ),\begin{gathered} \hat{\mathbf{x}}_i = \bar{\mathbf{x}} + V_k \mathbf{t}_i , \\[0.4em] \mathbf{t}_i = V_k^{\top}(\mathbf{x}_i - \bar{\mathbf{x}}) , \end{gathered}

and a new observation is reconstructed by the same formulas with the training mean and loadings. If the features were standardized before PCA, each coordinate of VktiV_k \mathbf{t}_i is multiplied by its training standard deviation before the mean is added. By the Eckart-Young theorem, among all n×pn \times p matrices BB of rank at most kk, the matrix X^c,k\hat{X}_{c,k} makes ∥Xc−B∥F2\lVert X_c - B \rVert_F^2 as small as possible. For k<qk < q this minimizer is unique when σk>σk+1\sigma_k > \sigma_{k+1}.

In plain words Keep the kk strongest layers and drop the rest. Each observation is replaced by the nearest point of the line, plane or flat through the mean that the retained axes span. No other matrix of rank at most kk comes closer in total squared error. That optimality is about squared reconstruction error under a rank limit. It does not mean that the retained axes are the most useful for predicting a target or the easiest to interpret.

Example For the four-point cloud with k=1k = 1, the reconstruction keeps every first coordinate and replaces every second coordinate by 00, so the rows become (−2,0)(-2, 0), (−2,0)(-2, 0), (2,0)(2, 0) and (2,0)(2, 0). The new observation (3,2)(3, 2) has score 33 and reconstruction 3⋅(1,0)=(3,0)3 \cdot (1, 0) = (3, 0). With the flipped loading (−1,0)(-1, 0) the score is −3-3 and the reconstruction is again (−3)⋅(−1,0)=(3,0)(-3) \cdot (-1, 0) = (3, 0), since the sign cancels. For the rank-one cloud, k=1k = 1 reproduces XcX_c exactly, and adding back the mean (2,2)(2, 2) returns the original points (1,1)(1, 1), (2,2)(2, 2) and (3,3)(3, 3).

Reconstruction error

Definition The total squared reconstruction error of the rank-kk reconstruction is

Ek=∥Xc−X^c,k∥F2=∑i=1n∥xi−x^i∥22=∑j=k+1qσj2,\begin{aligned} E_k &= \lVert X_c - \hat{X}_{c,k} \rVert_F^2 \\[0.4em] &= \sum_{i=1}^{n} \lVert \mathbf{x}_i - \hat{\mathbf{x}}_i \rVert_2^2 \\[0.4em] &= \sum_{j=k+1}^{q} \sigma_j^2 , \end{aligned}

the sum of the squared singular values that were dropped, which is 00 for k=qk = q. Adding the mean back does not change any residual. Dividing EkE_k by nn gives the mean squared error per observation, and dividing by npnp gives the mean squared error per matrix entry, so a report should state its denominator. When Xc≠0X_c \ne 0, the fraction Ek/∥Xc∥F2E_k / \lVert X_c \rVert_F^2 equals one minus the cumulative explained variance ratio of the first kk components. For a new observation the error is ∥x−x^∥22\lVert \mathbf{x} - \hat{\mathbf{x}} \rVert_2^2 with the training mean and loadings, and nothing bounds it by the training figures. After standardization the errors are in standardized units unless the scaling is reversed.

In plain words The error is exactly the variation in the discarded directions. A small training error means that the fitting data have little spread off the retained axes. A new observation can still have a large part in a discarded direction, and then it loses much more than the training percentage suggests.

Example For the four-point cloud with k=1k = 1, the residuals are (0,−1)(0, -1), (0,1)(0, 1), (0,−1)(0, -1) and (0,1)(0, 1), so E1=4=σ22E_1 = 4 = \sigma_2^2. The mean squared error is 4/4=14/4 = 1 per observation and 4/8=0.54/8 = 0.5 per entry, and the fraction 4/20=0.24/20 = 0.2 equals 1−0.81 - 0.8. The new observation (3,2)(3, 2) is reconstructed as (3,0)(3, 0), so its error is 22=42^2 = 4, while its squared distance from the training mean is 9+4=139 + 4 = 13. It loses 4/13≈0.314/13 \approx 0.31 of its squared length, more than the share 0.20.2 lost by the training cloud.

Check yourself

  1. A centered matrix with six observations of three features has singular values 55, 33 and 00. Find its rank, the eigenvalues of its sample covariance matrix, the explained variance ratio of the first component and the total squared error of the rank-one reconstruction. What is that error per observation?
Show the answer

The rank is the number of positive singular values, which is 22. The covariance eigenvalues are the squared singular values divided by n−1=5n - 1 = 5, namely 25/5=525/5 = 5, 9/5=1.89/5 = 1.8 and 00.

The squared singular values add to 25+9+0=3425 + 9 + 0 = 34, so the first explained variance ratio is 25/34≈0.735325/34 \approx 0.7353. The rank-one reconstruction drops the second and third terms, so its total squared error is 9+0=99 + 0 = 9, and the error per observation is 9/6=1.59/6 = 1.5. Per matrix entry it would be 9/18=0.59/18 = 0.5. The covariance divides by n−1n - 1, while the ratio divides by the total 3434, and mixing up the two denominators is a common slip.

  1. A constructed centered cloud has the rows (3,1)(3, 1), (1,3)(1, 3), (−1,−3)(-1, -3) and (−3,−1)(-3, -1). Find its singular values and the explained variance ratio of the first component, using the first loading v1=12(1,1)\mathbf{v}_1 = \tfrac{1}{\sqrt{2}}(1, 1). Then give the first score, the rank-one reconstruction and the squared reconstruction error of the observation (3,1)(3, 1), and say which of these objects are points or directions in feature space.
Show the answer

The squared first coordinates add to 9+1+1+9=209 + 1 + 1 + 9 = 20, the squared second coordinates also add to 2020, and the cross-products add to 3+3+3+3=123 + 3 + 3 + 3 = 12, so

Xc⊤Xc=[20121220].X_c^{\top}X_c = \begin{bmatrix} 20 & 12 \\ 12 & 20 \end{bmatrix} .

Its eigenvalues are 3232 with eigenvector 12(1,1)\tfrac{1}{\sqrt{2}}(1, 1) and 88 with eigenvector 12(1,−1)\tfrac{1}{\sqrt{2}}(1, -1). So σ1=32=42≈5.657\sigma_1 = \sqrt{32} = 4\sqrt{2} \approx 5.657, σ2=8=22≈2.828\sigma_2 = \sqrt{8} = 2\sqrt{2} \approx 2.828, and the first ratio is 32/40=0.832/40 = 0.8.

The observation (3,1)(3, 1) has first score (3+1)/2=22≈2.828(3 + 1)/\sqrt{2} = 2\sqrt{2} \approx 2.828. Its reconstruction is 22⋅12(1,1)=(2,2)2\sqrt{2} \cdot \tfrac{1}{\sqrt{2}}(1, 1) = (2, 2), the residual is (1,−1)(1, -1) and the squared error is 22. Every row has a residual of squared length 22, so the total is 8=σ228 = \sigma_2^2, as it must be.

The loading is a direction in feature space and the reconstruction is a point in feature space, each with one entry per feature. The score is a single coordinate along the axis. A program that returns −v1-\mathbf{v}_1 reports the score −22-2\sqrt{2} and the same reconstruction (2,2)(2, 2).

  1. Divide the first feature of the four-point cloud by 22, so the centered rows become (−1,−1)(-1, -1), (−1,1)(-1, 1), (1,−1)(1, -1) and (1,1)(1, 1) and both features have the same variance. One program reports the first loading (1,0)(1, 0) and another reports (0.6,0.8)(0.6, 0.8). Is one of them wrong? Compare their explained variance ratios and rank-one reconstruction errors.
Show the answer

Each column now has squared entries adding to 44, and the cross-products cancel, so Xc⊤Xc=4IX_c^{\top}X_c = 4I and σ1=σ2=2\sigma_1 = \sigma_2 = 2. For every unit vector v\mathbf{v} the squared length of the score column is v⊤(4I)v=4\mathbf{v}^{\top}(4I)\mathbf{v} = 4, half of the total 88. So both loadings give the explained variance ratio 0.50.5 and the rank-one error 8−4=48 - 4 = 4.

Neither program is wrong. With a repeated singular value the first principal axis is not determined, and every direction in the plane is equally good. The two rank-one reconstructions still differ. The row (−1,−1)(-1, -1) becomes (−1,0)(-1, 0) with the first loading, while with (0.6,0.8)(0.6, 0.8) its score is −1.4-1.4 and its reconstruction is (−0.84,−1.12)(-0.84, -1.12). To compare two implementations, compare quantities the data determine, such as the singular values, the reconstruction errors and the subspace spanned by the tied axes, here the whole plane, and not the raw loadings.

How this lesson connects