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:
- Centre the data: subtract each feature's mean from that feature.
- Build the covariance matrix
CwithC[i][j]= the mean over the rows of(centred x_i) · (centred x_j)(divide byn, notn - 1). - Start from the vector
v = [1.0, 1.0, ..., 1.0](one entry per feature). Repeatroundstimes:w = C·v, thenv = w / |w|(divide by the Euclidean length, sovhas length 1). - Return the final
vas a list of floats andvariance = v·(C·v), the variance of the data alongv.
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 <= 2000rows,1 <= d <= 8features,1 <= rounds <= 200- the tests make sure that
C·vis 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