Click4Ai

90.

Easy

Calculate the **Explained Variance Ratio** for PCA components.

Formula:

explained_variance_ratio_i = eigenvalue_i / sum(all eigenvalues)

Each ratio tells you what fraction of the total variance is captured by that principal component.

Write a function explained_variance_ratio(eigenvalues) that takes an array of eigenvalues (sorted descending) and returns the ratio for each.

Example:

eigenvalues = [4.0, 2.0, 1.0, 0.5, 0.25]

explained_variance_ratio(eigenvalues) → [0.5161, 0.2581, 0.1290, 0.0645, 0.0323]

**Explanation:** The first component explains 51.6% of total variance, the first two together explain 77.4%, etc. This helps decide how many components to keep.

Constraints:

  • Return an array of the same length as input
  • All ratios should sum to 1.0
  • Eigenvalues are assumed to be non-negative
  • Test Cases

    Test Case 1
    Input: [4.0, 2.0, 1.0, 0.5, 0.25]
    Expected: [0.5161, 0.2581, 0.1290, 0.0645, 0.0323]
    Test Case 2
    Input: [1.0, 1.0, 1.0]
    Expected: [0.3333, 0.3333, 0.3333]
    Test Case 3
    Input: [10.0, 0.0]
    Expected: [1.0, 0.0]
    + 2 hidden test cases