Sub topic 6
Projecting data and reconstructing it
This chapter assumes you can multiply matrices, know what a basis is, and have seen centering and the principal components from earlier chapters. Here you will use those components to move data into a smaller space and back, and to measure what that trip loses.
Scores: coordinates in the new basis
Let Xc be the centered data matrix with n rows (samples) and p columns (features). Let W be a p × k matrix whose columns are the top k principal components. Each column has unit length, and the columns are orthogonal to each other.
The projection is one matrix product:
scores = Xc @ W # shape (n, k)Each row of scores holds the coordinates of one sample along the k component axes. Column j is the score of every sample on component j. Because the components are orthogonal, the score columns are uncorrelated. The variance of column j equals the j-th eigenvalue of the covariance matrix.
Reconstruction: mapping back
To return to the original feature space, multiply by W.T and add the mean you subtracted:
X_hat = scores @ W.T + meanThe result is the closest rank-k approximation of the data, in the least-squares sense. Each point lands on the k-dimensional plane spanned by the components. The part of each point that was perpendicular to that plane is gone.
A worked example
This code uses the SVD of the centered data to get W. It then projects, reconstructs, and checks the error against the discarded singular values.
import numpy as np
rng = np.random.default_rng(0)
X = rng.normal(size=(200, 3)) @ np.array([[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2]])
n, p = X.shape
mean = X.mean(axis=0)
Xc = X - mean
U, S, Vt = np.linalg.svd(Xc, full_matrices=False)
k = 2
W = Vt[:k].T # (p, k)
scores = Xc @ W # (n, k)
X_hat = scores @ W.T + mean # (n, p)
mse = np.mean((X - X_hat) ** 2)
predicted = np.sum(S[k:] ** 2) / (n * p)
print(scores.shape)
print(mse, predicted)
print(np.allclose(mse, predicted))
print(np.allclose(np.cov(scores, rowvar=False),
np.diag(S[:k] ** 2 / (n - 1))))The first allclose check is True. The mean squared reconstruction error equals the sum of the squared discarded singular values, divided by n·p. Equivalently, the lost energy is the sum of the discarded covariance eigenvalues, scaled by (n − 1). The second check confirms that the scores are uncorrelated, with variances equal to the kept eigenvalues.
Common errors
- Forgetting to add the mean back.
scores @ W.Talone gives a reconstruction centered at the origin, so every feature is off by its mean. - Transposing
Wthe wrong way.Vtfrom NumPy stores components as rows. UseVt[:k].Tto get the p × k matrix used here. - Projecting new data with its own mean. For test data, subtract the mean learned from the training data. Do the same with any scaling factors, then use the training
W. Refitting on new data gives a different basis. - Comparing errors in different units. If you standardized before PCA, compute the error on the standardized data. Otherwise, undo the scaling before comparing.
Summary of shapes
| Object | Shape | Meaning |
|---|---|---|
| `Xc` | n × p | centered data |
| `W` | p × k | kept components as columns |
| `scores` | n × k | coordinates in component space |
| `X_hat` | n × p | rank-k reconstruction |
Exercise
You fit PCA on training data with k = 2 and now have one new sample x_new (a vector of length p). Write the two expressions that give its scores and its reconstruction, using the training mean and W. Why must you not recompute the mean from x_new?
Show answer
scoresnew = (xnew - mean) @ W, and xhat = scoresnew @ W.T + mean. The mean is a parameter learned from the training data. Components are defined relative to that center, so using a different mean shifts the sample relative to the learned axes. A single sample's own mean would also be meaningless as a center.