Project data onto k principal components with the SVD and reconstruct it

Why it matters PCA projection and reconstruction is used for compressing embeddings, denoising, anomaly detection by reconstruction error and quick 2D plots of features.

PCA compresses data by keeping the top directions of variance. Reconstructing from those components shows how much was lost.

Write pca_project_reconstruct(X, k). Center X by its column means, take the thin SVD Xc = U S V^T, and use the first k rows of V^T as components. Fix the sign of each component so that its entry with the largest absolute value is positive. Return (Z, X_rec) where Z = Xc @ components.T has shape (n, k) and X_rec = Z @ components + mean has the shape of X.

Signaturedef pca_project_reconstruct(X, k)

Example

X [[1, 1], [2, 2], [3, 3]], k 1 gives Z [[-1.414214], [0], [1.414214]] and X_rec equal to X.

Understand the idea

PCA finds the directions along which the data spreads the most. Keeping only the top k directions is like describing a long, thin cloud of points with just its main axis: you lose a little detail but keep most of the shape.

The SVD of the centered data does all the work. If Xc = U S V^T, the rows of V^T are the principal directions in order of importance. Projecting gives coordinates Z = Xc V_k^T. Going back gives X_rec = Z V_k + mean.

Worked example: points (1, 1), (2, 2), (3, 3). The mean is (2, 2). Centered points lie exactly on the diagonal, so the first component is (0.707, 0.707). Coordinates are -1.414, 0, 1.414 (distance along the diagonal). Reconstruction gives back the original points exactly, because nothing was off the diagonal.

Rule: Z = (X - mean) V_k^T, X_rec = Z V_k + mean. The reconstruction error is the variance in the dropped components.

PCA compresses embeddings, removes noise and powers simple anomaly detectors that flag rows with big reconstruction error.

Shapes and data flow

X (n, d) -> Vt (min(n, d), d) -> comps (k, d) -> Z (n, k) -> X_rec (n, d)
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplepca_project_reconstruct([[1, 1], [2, 2], [3, 3]], 1)
  • Sample 2: lossypca_project_reconstruct([[2, 0], [0, 1], [-2, 0], [0, -1], [4, 3]], 1)