Task: Calculate Explained Variance Ratio for PCA
In Principal Component Analysis (PCA), the explained variance ratio indicates the proportion of the dataset's total variance captured by each principal component. This metric helps determine how many components are needed to adequately represent the data.
Write a function explained_variance_ratio(X) that takes a data matrix and returns the explained variance ratio for each principal component.
Input:
X: A 2D data matrix of shape (n_samples, n_features) where each row is a sample and each column is a feature.
Output:
- A list of explained variance ratios, one for each principal component, sorted in descending order (largest first). The ratios should sum to 1.0.
Requirements:
- Center the data by subtracting the mean of each feature
- Compute the covariance matrix using the unbiased estimator (divide by n-1)
- Extract eigenvalues from the covariance matrix
- Calculate the ratio of each eigenvalue to the total sum of eigenvalues
- Return results sorted from highest to lowest explained variance