Find the main direction of your data with PCA

PCA finds the directions along which your data varies the most. It is how people squash 768-dimensional embeddings onto a 2D plot.

Write pca(X, k) for X of shape (n, d). Centre the columns, then return (components, projected):
- components: shape (k, d), the top k principal directions as unit vectors, largest variance first.
- projected: shape (n, k), the centred data projected onto them.

Sign is ambiguous for eigenvectors, so make the largest-magnitude entry of each component positive.

Signaturedef pca(X, k)

Understand the idea

PCA finds the directions in which your data spreads out the most. Imagine a cloud of points shaped like a cigar: the first component points along its length. First centre each column by subtracting its mean, otherwise the direction points at the mean rather than along the spread. Then the SVD of the centred data gives the directions as rows of Vt, already sorted by variance. Worked example: points (1, 1), (2, 2), (3, 3). Mean is (2, 2), centred points are (-1, -1), (0, 0), (1, 1). All spread lies along [1, 1], so the top unit component is [0.707, 0.707]. Projections are dot products: -1.414, 0 and 1.414. Since v and -v are both valid, flip each component so its largest-magnitude entry is positive. Rule: Xc = X - mean; Xc = U S Vt; components = Vt[:k] (sign fixed); projected = Xc components^T. PCA is used to plot embeddings in 2D and to compress features.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: top componentpca(_X, 1)[0]
  • Sample 2: two componentspca(_X, 2)[0]
  • Test 3: projectionpca(_X, 2)[1][:5]
  • Test 4: projected mean is zeropca(_X, 2)[1].mean(axis=0)