v9.1.1
Menu

PCA via Covariance Matrix

mediumPRODimensionality ReductionMachine Learning 2

Implement Principal Component Analysis from scratch.

Given a 2D dataset, perform PCA to reduce dimensionality to kk components:

  1. Center the data (subtract column means)
  2. Compute the covariance matrix: C=1n−1XcTXcC = \frac{1}{n-1} X_c^T X_c
  3. Compute eigenvalues and eigenvectors of CC
  4. Select top kk eigenvectors (by eigenvalue magnitude)
  5. Project the centered data onto these eigenvectors

Return the projected data (n x k matrix), rounded to 4 decimal places.

Note: For simplicity, this problem works with 2D data (2 features → 1 component).

Example

Input
X = [[2.5, 2.4], [0.5, 0.7], [2.2, 2.9], [1.9, 2.2], [3.1, 3.0], [2.3, 2.7], [2.0, 1.6], [1.0, 1.1], [1.5, 1.6], [1.1, 0.9]]
k = 1
Output
[[-0.8280], [1.7776], [-0.9922], [-0.2742], [-1.6758], [-0.9129], [0.0991], [1.1446], [0.4380], [1.2238]]
Reasoning
  • First, we center the data by subtracting the column means: μ1=1.75\mu_1 = 1.75, μ2=2.03\mu_2 = 2.03, resulting in a centered dataset XcX_c.
  • Then, we compute the covariance matrix C=1n−1XcTXcC = \frac{1}{n-1} X_c^T X_c, where nn is the number of data points.
  • Next, we calculate the eigenvalues and eigenvectors of CC, and select the top k=1k=1 eigenvector corresponding to the largest eigenvalue.
  • Finally, we project the centered data XcX_c onto this eigenvector, resulting in the projected data, which is then rounded to 4 decimal places to produce the output: [[-0.8280], [1.7776], [-0.9922], [-0.2742], [-1.6758], [-0.9129], [0.0991], [1.1446], [0.4380], [1.2238]]

Constraints

  • X: 2D list (n x 2) — two features
  • k: 1 (project to 1 dimension)
  • Return 2D list (n x 1) of projected values, rounded to 4 decimal places
  • Use sample covariance (divide by n-1)

Learn this in

More from Machine Learning 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.