v9.1.1
Menu

Variance Explained Ratio

easyPRODimensionality ReductionMachine Learning 2

Compute the explained variance ratio from eigenvalues.

Given a list of eigenvalues (sorted descending), compute: ratioi=λi∑jλj\text{ratio}_i = \frac{\lambda_i}{\sum_{j} \lambda_j}

Also compute the cumulative explained variance ratio: entry ii is the running sum of the already rounded ratios up to and including ii, rounded again to 4 decimal places.

Return a tuple (ratios, cumulative) where both are lists rounded to 4 decimal places.

Example

Input
eigenvalues = [4.0, 2.0, 1.0, 0.5]
Output
([0.5333, 0.2667, 0.1333, 0.0667], [0.5333, 0.8, 0.9333, 1.0])
Reasoning
  • eigenvalues holds λ1≥λ2≥…\lambda_1 \ge \lambda_2 \ge \dots, the variance captured along each principal direction. Here the total variance is 4.0+2.0+1.0+0.5=7.54.0 + 2.0 + 1.0 + 0.5 = 7.5.
  • Each ratio is one component's share of that total, rounded to 4 decimal places: 4.07.5=0.53‾→0.5333\frac{4.0}{7.5} = 0.5\overline{3} \to 0.5333, 2.07.5→0.2667\frac{2.0}{7.5} \to 0.2667, 1.07.5→0.1333\frac{1.0}{7.5} \to 0.1333, 0.57.5→0.0667\frac{0.5}{7.5} \to 0.0667.
  • Cumulative entry ii is the share explained by the first ii components together: 0.53330.5333, then 0.5333+0.2667=0.80.5333 + 0.2667 = 0.8, 0.8+0.1333=0.93330.8 + 0.1333 = 0.9333, 0.9333+0.0667=1.00.9333 + 0.0667 = 1.0.
  • Both lists have one entry per eigenvalue. The ratios shrink because the eigenvalues are sorted descending, and the cumulative list climbs to 11 because all components together explain all the variance.
  • Notice the running total adds the already rounded ratios. With three equal eigenvalues each ratio is 0.33330.3333, so the last cumulative value is 0.99990.9999, not 1.01.0.
  • Reading the result: the first two components already explain 80%80\% of the variance, so keeping 2 of 4 loses only 20%20\%.

Constraints

  • eigenvalues: list of non-negative floats (sorted descending)
  • Return (ratios, cumulative) rounded to 4 decimal places
  • cumulative[i] = sum(ratios[0:i+1])

Learn this in

More from Machine Learning 2

PRO

Editor locked

The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.

solution.py

Test results

Sign in to run your code against the test cases.