Sub topic 6
Projecting Data and Reconstructing It
This chapter assumes you know NumPy matrix multiplication, the idea of an orthonormal basis, and the covariance matrix and its eigenvectors from the earlier chapters. Here you will turn the principal components into a working compression and decompression step. You will project data onto them, map the result back, and measure what the round trip loses.
The two operations
Suppose you have a data matrix X with n rows (samples) and p columns (features). You have already computed the mean mu and the principal components. Keep the top k components as the columns of a matrix W with shape (p, k). The columns of W are orthonormal: each has length 1 and any two are perpendicular. That means W.T @ W is the k × k identity matrix.
PCA then does two operations.
- Projection (encoding):
Z = (X - mu) @ W. Each row ofZholds the scores of one sample. A score is the coordinate of that sample along one component. - Reconstruction (decoding):
X_hat = Z @ W.T + mu. This places the scores back in the original feature space.
| Quantity | Shape | Meaning |
|---|---|---|
| `X` | `(n, p)` | Original data |
| `mu` | `(p,)` | Feature means from the training data |
| `W` | `(p, k)` | Top `k` principal axes as columns |
| `Z` | `(n, k)` | Scores, the compressed representation |
| `X_hat` | `(n, p)` | Reconstruction, which has rank at most `k` after centering |
Projecting and reconstructing with NumPy
The following code reuses the three-feature data set from the previous chapters. It keeps two components and checks the properties described below.
import numpy as np
rng = np.random.default_rng(0)
mixing = np.array([[3.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 0.0, 0.2]])
X = rng.normal(size=(200, 3)) @ mixing
n, p = X.shape
mu = X.mean(axis=0)
Xc = X - mu
cov = np.cov(Xc, rowvar=False)
eigvals, eigvecs = np.linalg.eigh(cov)
order = np.argsort(eigvals)[::-1]
eigvals = eigvals[order]
eigvecs = eigvecs[:, order]
k = 2
W = eigvecs[:, :k]
Z = Xc @ W # projection
X_hat = Z @ W.T + mu # reconstruction
print(np.round(W.T @ W, 6)) # identity matrix
print(np.round(np.cov(Z, rowvar=False), 4)) # diagonal
print(np.round(eigvals[:k], 4)) # matches that diagonal
sse = np.sum((X - X_hat) ** 2)
print(np.isclose(sse, (n - 1) * eigvals[k:].sum())) # TrueThe code shows three facts.
- The columns of
Ware orthonormal.W.T @ Wprints as the identity matrix. - The scores are uncorrelated. The covariance matrix of
Zis diagonal, and its diagonal entries equal the kept eigenvalues. Each score column has a variance equal to the eigenvalue of its component. - The error is exactly the discarded variance. The total squared reconstruction error equals
(n - 1)times the sum of the discarded eigenvalues. The last line checks this.
The third fact connects this chapter to the next one, on explained variance. Dropping a component does not lose an arbitrary amount of information. It loses exactly that component's eigenvalue, which is why the eigenvalues are enough to decide how many components to keep.
Projection as an orthogonal projection
The product P = W @ W.T has shape (p, p). It maps any centered vector to its closest point in the subspace spanned by the kept components. Two properties follow from W.T @ W = I.
Pis symmetric:P.T == P.Pis idempotent:P @ P == P. Projecting a second time changes nothing.
The residual Xc - Xc @ P is perpendicular to the subspace. The following code checks all three properties.
P = W @ W.T
residual = Xc - Xc @ P
print(np.allclose(P, P.T)) # True
print(np.allclose(P @ P, P)) # True
print(np.allclose(residual @ W, 0)) # TrueBecause the residual is perpendicular to the subspace, the squared lengths add up. For each sample, the squared length of the centered vector equals the squared length of its scores plus the squared length of its residual. This is the Pythagorean theorem applied in p dimensions, and it is why maximizing retained variance and minimizing reconstruction error are the same problem.
Reconstruction is not recovery
X_hat has the original shape, but it is not the original data. The reconstruction keeps only the variation along the first k directions. Every sample lands on a flat k-dimensional surface through the mean, and the information in the discarded directions is gone. The only exception is k = p. Then P is the identity matrix and the round trip is exact, apart from floating-point rounding.
The size of the loss depends on the data.
- Strongly correlated features compress well, because a few directions carry most of the variance.
- Nearly independent features compress badly, because every direction carries a similar share.
- The error is not spread evenly over samples. Samples far from the subspace have large residuals.
Per-sample reconstruction error is a useful signal in its own right. A sample that reconstructs much worse than its neighbors does not fit the correlation structure PCA learned. Some anomaly detectors use this error as their score.
Projecting new data
Projection is only useful if you can apply it to samples that were not in the fit. The rule is that every statistic comes from the training data: the mean, the scaling factors and W. Never recompute them on the new data.
def project(X_new, mu, W):
return (X_new - mu) @ W
def reconstruct(Z, mu, W):
return Z @ W.T + mu
X_new = rng.normal(size=(5, 3)) @ mixing
Z_new = project(X_new, mu, W)
X_new_hat = reconstruct(Z_new, mu, W)
print(Z_new.shape, X_new_hat.shape)If you center a small batch with its own mean, the scores shift by an unknown offset. Scores from different batches then no longer share one coordinate system. The same applies to a scaler: a standardizer fitted on the batch gives each feature a different scale than the one W was learned under.
The error also behaves differently on new data. On the training set, the error is exactly the discarded variance. On held-out data it is usually a little larger, because W was tuned to the training sample. Judge compression quality on held-out data when you can.
The same round trip in scikit-learn
In scikit-learn, transform performs projection and inverse_transform performs reconstruction. When you scale the features first, you must also undo the scaling to return to the original units. The following code fits on a training split and evaluates on held-out data.
from sklearn.datasets import load_iris
from sklearn.decomposition import PCA
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
X, _ = load_iris(return_X_y=True)
X_train, X_test = train_test_split(X, test_size=0.3, random_state=0)
scaler = StandardScaler().fit(X_train)
pca = PCA(n_components=2).fit(scaler.transform(X_train))
Z_test = pca.transform(scaler.transform(X_test))
X_back_std = pca.inverse_transform(Z_test)
X_back = scaler.inverse_transform(X_back_std)
per_feature_mse = ((X_test - X_back) ** 2).mean(axis=0)
per_sample_error = ((X_test - X_back) ** 2).sum(axis=1)
print(Z_test.shape)
print(per_feature_mse)
print(per_sample_error.argmax())The two inverse calls run in the reverse order of the forward steps: pca.inverse_transform first, then scaler.inverse_transform. Calling only the first leaves the result in standardized units, which is a common cause of reconstructions that look wrong by a constant factor and offset.
Wrapping both steps in a Pipeline makes inverse_transform undo the whole chain in the right order. A pipeline whose steps all support inverse_transform exposes it as a single call.
Edge cases and common errors
- Forgetting the mean.
Z @ W.Talone gives the centered reconstruction. Without+ mu, every feature is off by its mean. - Mismatched shapes.
Whas shape(p, k), so the scores areXc @ Wand the reconstruction usesW.T. WritingW @ Zfails because the shapes do not match, and it silently gives wrong results whenn == p. - Sign flips. An eigenvector and its negative are equally valid. Scores from two fits can differ in sign for the same component. Do not compare scores across separate fits without aligning signs.
- Whitening. With
whiten=True, scikit-learn divides each score column by the square root of its eigenvalue so every score has unit variance.inverse_transformaccounts for this, but the scores no longer have the original scale. Do not mix whitened and unwhitened scores. - Reading error as a percentage. Squared error is in squared units. To compare across data sets, divide by the total variance of the data, or use the explained variance ratio in the next chapter.
- Fitting on test data. Fitting PCA on training and test data together lets information from the test set leak into
Wand makes held-out error look better than it is.
Summary
Projection multiplies centered data by W to get scores. Reconstruction multiplies the scores by W.T and adds the mean back. The reconstruction is the closest point to the original in the kept subspace, and its total squared error equals (n - 1) times the sum of the discarded eigenvalues. Always reuse the training mean, scaling and W for new samples, and undo preprocessing in reverse order when you need results in original units.
Exercise
A data set has n = 101 samples and 5 features. The covariance eigenvalues, sorted in decreasing order, are 4, 2, 1, 0.5 and 0.5. You keep k = 2 components. What is the total squared reconstruction error on the training data, and what fraction of the total variance is lost?
Show answer
The total squared error is (n - 1) times the sum of the discarded eigenvalues, so 100 × (1 + 0.5 + 0.5) = 200. The total variance is 4 + 2 + 1 + 0.5 + 0.5 = 8, and the discarded part is 2, so 2 / 8 = 25% of the variance is lost.
Exercise
You fitted a StandardScaler and a PCA on training data. A colleague passes a new batch of 10 samples through a freshly fitted StandardScaler on that batch, then through your PCA's transform. Why are the resulting scores unreliable, and how do you fix it?
Show answer
The new scaler computes its mean and standard deviation from only 10 samples, so the features are centered and scaled differently than the training data that W was learned under. The scores then sit in a different coordinate system and cannot be compared with training scores. Fix it by reusing the scaler fitted on the training data, calling its transform on the new batch and then calling the PCA's transform.