How Much Each Direction Holds

Machine Learning in CodeEasy+10 XP+10

How Much Each Direction Holds

A running club measured its members: [height_cm, arm_span_cm, shoe_size_eu, weekly_km]. Height, arm span and shoe size all say roughly how big someone is, so some of these columns overlap.

PCA tells you how much of the variation each new direction carries.

Task: write variance_shares(rows, n_components).

  • Scale the columns with StandardScaler().fit_transform(...).
  • Fit PCA(n_components=n_components) on the scaled data.
  • Return explained_variance_ratio_ as a list of plain floats, each rounded to 3 decimal places.

Examples

rows = [[171.5, 171.8, 40.0, 79.3], [175.3, 174.7, 41.5, 59.0], [175.1, 177.9, 41.5, 57.5], [167.9, 169.3, 39.8, 68.9], [154.2, 155.4, 35.9, 47.9], [176.4, 179.6, 41.9, 55.9], [174.2, 175.5, 41.2, 76.1], [178.1, 180.0, 41.9, 41.0], [175.6, 177.0, 41.2, 49.7], [178.3, 180.2, 41.6, 40.7], [167.6, 170.0, 39.6, 70.0], [175.3, 176.3, 41.4, 59.6]]
n_components = 2
returns [0.75, 0.244]
rows = [[172.9, 174.8, 41.3, 73.3], [164.6, 171.0, 38.7, 41.2], [151.1, 163.8, 36.9, 64.1], [172.2, 170.2, 39.5, 69.0], [164.0, 164.2, 39.4, 47.9], [174.4, 173.2, 41.5, 50.1], [171.9, 180.8, 40.7, 50.8], [180.0, 182.1, 41.6, 54.2], [165.7, 171.0, 40.1, 67.2], [184.2, 186.5, 43.3, 88.8], [173.9, 169.9, 39.1, 58.3], [166.8, 167.4, 40.5, 66.7], [174.5, 172.5, 40.4, 67.9], [163.2, 165.5, 38.1, 65.1], [173.5, 180.3, 42.1, 30.7]]
n_components = 4
returns [0.677, 0.247, 0.043, 0.033]

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