Project onto Principal Components

Medium
~15 min
code completion

PCA Projection

Once we have the principal components (eigenvectors of the covariance matrix, or right singular vectors from SVD), we project the centered data onto them to get the lower-dimensional representation:

where:

  • : centered data, shape (n, d)
  • : top- principal components, shape (r, d) — each row is a component
  • : projected data (principal component scores), shape (n, r)
  • The projection rotates data into the new coordinate system defined by the principal components.

    Your task:

    Implement pca_project(X_centered, components) where components has shape (r, d).

    Example Tests

    Project onto 1 component: shape (n, 1)

    Input: {"X_centered":[[-2,0],[0,0],[2,0]],"components":[[1,0]]}

    Expected: [[-2],[0],[2]]

    Identity-like: 2 components, 2D data preserved

    Input: {"X_centered":[[1,0],[0,1],[-1,0]],"components":[[1,0],[0,1]]}

    Expected: [[1,0],[0,1],[-1,0]]

    Output shape is (n, r)

    Input: {"X_centered":[[1,2,3],[4,5,6],[7,8,9]],"components":[[1,0,0],[0,1,0]]}

    Expected: [3,2]

    Sign in to solve this problem

    You can read the full problem statement above. Create a free account to run code in the browser, submit solutions, and track your progress.