PCA via Covariance Matrix
Implement Principal Component Analysis from scratch.
Given a 2D dataset, perform PCA to reduce dimensionality to components:
- Center the data (subtract column means)
- Compute the covariance matrix:
- Compute eigenvalues and eigenvectors of
- Select top eigenvectors (by eigenvalue magnitude)
- 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
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
[[-0.8280], [1.7776], [-0.9922], [-0.2742], [-1.6758], [-0.9129], [0.0991], [1.1446], [0.4380], [1.2238]]
- First, we center the data by subtracting the column means: , , resulting in a centered dataset .
- Then, we compute the covariance matrix , where is the number of data points.
- Next, we calculate the eigenvalues and eigenvectors of , and select the top eigenvector corresponding to the largest eigenvalue.
- Finally, we project the centered data 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)