PCA: Rewrite Data in Its Top Directions

Classic MLHard+20 XP+20

PCA: Rewrite Data in Its Top Directions

Two features that move together carry nearly the same information twice. PCA finds the directions your data actually varies along, and rewrites every point in terms of those directions instead — keeping the few that matter and dropping the rest.

Task: write pca_project(data, n_components) returning each row rewritten in the top n_components directions, every number rounded to 4 decimal places.

The four steps:

  1. Centre the data: subtract each column's mean, so the cloud sits around the origin. PCA measures variation about the mean, and skipping this makes the first component point at the data instead of through it.
  2. Build the covariance matrix of the centred data, dividing by n - 1.
  3. Take its eigenvectors, and keep the n_components whose eigenvalues are largest. Those are your directions, biggest-variance first.
  4. Project: multiply the centred data by that matrix of kept eigenvectors.
  • An eigenvector points in a direction, and -v describes the same direction as v, so the sign is arbitrary. To make the answer unique, flip each component so that its largest-magnitude entry is positive.
  • Return a list of rows, one per input row, each n_components long.
  • NumPy is available. Use np.linalg.eigh — the covariance matrix is symmetric, and eigh exploits that to return real, sorted eigenvalues where the general-purpose eig can hand you complex noise.

When two features are perfectly correlated, the second eigenvalue comes out at zero: the data is really one-dimensional, and PCA has just told you so.

Compressing the Data

Toggle to project every point onto the principal component.

2 numbers per point (x, y)

Instead of storing two coordinates, we now store one position along the line. The important pattern remains.

Examples

data = [[1, 2], [3, 4], [5, 6], [7, 8]]
n_components = 1
returns [[-4.2426], [-1.4142], [1.4142], [4.2426]]
data = [[2, 1], [1, 3], [4, 5], [7, 6]]
n_components = 1
returns [[-2.8947], [-2.4163], [1.1743], [4.1366]]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run