Skip to content
Work Practice Products Coding interviews Machine learning coding Quant developer HFT course Blog Method Why me About Enquire Book a call

ML coding · Classic algorithms

Principal component analysis

Medium · Target 15 minutes · Python and NumPy

Given data X (n × d) and k ≤ min(n, d), return [components, projected]:

  • components (k × d): the top k principal directions of the centred data, as unit-length rows, in decreasing order of variance;
  • each row's sign fixed so that its entry of largest absolute value is positive (the tests avoid ties between entries of opposite sign);
  • projected (n × k): the centred data expressed in those directions.

The tests guarantee the top k variances are distinct.

Examples

Input X = [[1, 1], [2, 2], [3, 3]], k = 1

Output [[[0.7071, 0.7071]], [[-1.4142], [0], [1.4142]]]

All the variance lies along the diagonal (0.7071, 0.7071).

Input X = [[0, 0], [2, 0], [0, 1], [2, 1]], k = 2

Output [[[1, 0], [0, 1]], [[-1, -0.5], [1, -0.5], [-1, 0.5], [1, 0.5]]]

Variance 4/3 along x and 1/3 along y: the axes, in that order.

Input X = [[1, -2], [-1, 2], [3, -6]], k = 1

Output [[[-0.4472, 0.8944]], [[0], [4.4721], [-4.4721]]]

The direction (0.4472, −0.8944) and its negative are both right. The sign rule makes the larger entry positive.

Constraints

  • 2 ≤ n ≤ 1000, 1 ≤ d ≤ 50, 1 ≤ k ≤ min(n, d)
  • The top k + 1 singular values are distinct (k + 1 ≤ min(n, d))
  • Checked to a relative tolerance of 10⁻⁷

Hints

Hint 1

Subtract the column means first. PCA on uncentred data finds the direction of the mean, not of the variance.

Hint 2

np.linalg.svd(Xc, full_matrices=False) returns Vt; its rows are the principal directions, already sorted.

Hint 3

For the sign: find each row's index of largest |value| with argmax, and multiply the row by the sign of that entry. Then project with Xc @ W.T.

Where candidates go wrong

  • Forgetting to centre.
  • Taking columns of Vt instead of rows (or rows of V instead of columns).
  • Forming the covariance matrix and calling np.linalg.eig: eig does not sort its output and may return complex dtype. If you go that way, use eigh and reverse the order.
  • Projecting the uncentred data.
Console⌘/Ctrl + Enter runs

Python runs in your browser with NumPy. The first run downloads the runtime, which takes a few seconds.


Why interviewers ask it

PCA is the standard test of linear algebra in an ML interview: centring, the link between the SVD and the covariance matrix, and an awareness that eigenvectors have no preferred sign. Quant research interviews ask it constantly, because the first principal component of a set of returns is the market.

The theory behind it is in the lesson k-means, kNN, PCA and decision trees from scratch.


Keep going