Problem 664257 · easy · Level 06 Heuristics & Optimization

The Direction Where the Data Spreads Most

PCA · power iteration · covariance matrix · eigenvector · variance

A fitness app logs, for every user, a few numbers per week (for example hours of exercise, kilometres run and hours of sleep). Several of them move together, and the app's analysts want the single direction in feature space along which the users differ most.

Write top_component(rows, rounds) that returns a tuple (v, variance) computed exactly like this:

  1. Centre the data: subtract each feature's mean from that feature.
  2. Build the covariance matrix C with C[i][j] = the mean over the rows of (centred x_i) · (centred x_j) (divide by n, not n - 1).
  3. Start from the vector v = [1.0, 1.0, ..., 1.0] (one entry per feature). Repeat rounds times: w = C·v, then v = w / |w| (divide by the Euclidean length, so v has length 1).
  4. Return the final v as a list of floats and variance = v·(C·v), the variance of the data along v.

Examples

Input:  rows = [[2, 0], [0, 2], [4, 4], [2, 2]], rounds = 10
Output: ([0.7071067811865475, 0.7071067811865475], 2.9999999999999996)
Explanation: the means are [2, 2] and C = [[2, 1], [1, 2]]. C·[1, 1] = [3, 3], which already
points along the diagonal, so every round gives [0.7071, 0.7071]; the variance along it is 3.

Input:  rows = [[8, 40, 7], [12, 65, 6], [5, 25, 8], [10, 50, 7], [15, 80, 5]], rounds = 30
Output: ([0.1746505803448022, 0.9832784437273497, -0.05158174954714744], 378.5525555781835)

Constraints

  • 2 <= n <= 2000 rows, 1 <= d <= 8 features, 1 <= rounds <= 200
  • the tests make sure that C·v is never the zero vector
  • floats are compared with a tolerance of 1e-6

Goals

  • Centre a dataset and build its covariance matrix
  • Find the top principal component by repeated matrix-vector products
  • Read off the variance along a unit direction as v·C·v
Starting Python…