A Cloud With No Favourite Direction

Dimensionality Reduction & EmbeddingsHard+30 XP+30

A Cloud With No Favourite Direction

The dimensionality-reduction pipeline — centre the data, build the covariance matrix, find its eigenvectors, project onto them — hands you new coordinates that are no longer correlated with each other. But they still have very different spreads: the coordinate along PC1 varies a lot, the one along PC2 far less.

Whitening adds one last move. Divide each new coordinate by its own standard deviation, so that every direction ends up with variance exactly 111. The cloud comes out round, with no direction more stretched than any other.

Task: write whiten(points) for 2D data. points is a list of [x,y][x, y][x,y] pairs. Return the whitened pair for every point, in the same order, with each number rounded to 4 decimal places.

  1. Centre. Subtract the mean point from every point, giving centred pairs (dx,dy)(d_x, d_y)(dx​,dy​).
  2. Covariance. With nnn points, and dividing by nnn:
C=[abbc],a=1n∑dx 2,b=1n∑dx dy,c=1n∑dy 2C = \begin{bmatrix} a & b \\ b & c \end{bmatrix}, \qquad a = \frac{1}{n}\sum d_x^{\,2}, \quad b = \frac{1}{n}\sum d_x\, d_y, \quad c = \frac{1}{n}\sum d_y^{\,2}C=[ab​bc​],a=n1​∑dx2​,b=n1​∑dx​dy​,c=n1​∑dy2​
  1. Eigenvectors. Find the eigenvalues of CCC, λ1>λ2\lambda_1 > \lambda_2λ1​>λ2​, and a unit eigenvector for each: u1\mathbf{u}_1u1​ for λ1\lambda_1λ1​ and u2\mathbf{u}_2u2​ for λ2\lambda_2λ2​. Flipping an eigenvector gives another eigenvector, so to make the answer unique, orient each one so that its first component is positive — or, if its first component is 000, so that its second component is positive.
  2. Rotate, then rescale. A centred point d\mathbf{d}d becomes
[ d⋅u1λ1,  d⋅u2λ2 ]\left[\ \frac{\mathbf{d} \cdot \mathbf{u}_1}{\sqrt{\lambda_1}},\ \ \frac{\mathbf{d} \cdot \mathbf{u}_2}{\sqrt{\lambda_2}}\ \right][ λ1​​d⋅u1​​,  λ2​​d⋅u2​​ ]

You may assume there are at least three points, they don't all lie on one straight line, and the two eigenvalues are different — so both are positive, and each has a single eigenvector direction.

Example.

Here C=[5445]C = \begin{bmatrix} 5 & 4 \\ 4 & 5 \end{bmatrix}C=[54​45​], with eigenvalues 999 and 111. Whatever the input, each output coordinate should come out with mean 000 and variance 111 — a handy check on your own work.

Examples

points = [[2, 1], [4, 5], [6, 3], [8, 7]]
returns [[-1.4142, 0.0], [0.0, -1.4142], [0.0, 1.4142], [1.4142, 0.0]]
points = [[0, 0], [2, 1], [4, 4], [6, 3], [3, 7]]
returns [[-1.5091, -0.5371], [-0.8048, 0.179], [0.503, 0.179], [0.6036, 1.6113], [1.2073, -1.4322]]

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