PCA From Scratch via Eigendecomposition

Quick Overview

Implement PCA fit and transform in NumPy by eigendecomposing the sample covariance of centred data, with sorted components, a fixed sign convention and explained variance ratios. It tests covariance with the n - 1 denominator, correct use of a symmetric eigensolver, and projecting new data with the training mean.

PCA From Scratch via Eigendecomposition

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: easy

Interview Round: Other

Implement `PCA.fit(X)` and `PCA.transform(X)` in NumPy by eigendecomposing the sample covariance of the centred data. `fit` returns `self`. `transform` projects data, centred with the training mean, onto the stored components. Requirements: - After `fit`, set `mean_`, `n_components_`, `components_` (shape `(k, d)`, orthonormal rows), `explained_variance_` and `explained_variance_ratio_`. - Covariance uses the `n - 1` denominator. Components are sorted by descending eigenvalue. - `explained_variance_ratio_` divides by the sum of all `d` eigenvalues, not only the kept ones. - Sign convention: flip each component so its largest-absolute entry is positive. - `n_components=None` keeps all `d`. A value outside `1..d` raises `ValueError`. For example: ```python X = [[12, 20], [10, 24], [8, 20], [10, 16]] p = PCA(n_components=2).fit(X) p.mean_ # [10., 20.] p.components_ # [[0., 1.], [1., 0.]] p.explained_variance_ # [32/3, 8/3] p.explained_variance_ratio_ # [0.8, 0.2] p.transform([[11, 23], [10, 20]]) # [[3., 1.], [0., 0.]] ``` ```hint Read the eigensolver's output carefully `np.linalg.eigh` suits a symmetric matrix. Check the order in which it returns the eigenvalues, and whether the eigenvectors come back as rows or as columns. ``` ### Constraints & Assumptions - `X` is array-like of shape `(n, d)` with `n ≥ 2` and finite values. - Results must match `sklearn.decomposition.PCA` (under the sign convention above) to `rtol=1e-6`. - Do not use `sklearn` in the solution. Only NumPy is allowed. ### What a Strong Answer Covers - Centring with the training mean and building the covariance with the `n - 1` denominator. - Using a symmetric eigensolver and reordering eigenvalues and eigenvector columns together into descending order. - Storing the components as rows and applying the sign convention to each one. - Computing the variance ratio over all `d` eigenvalues and validating `n_components`. - Reusing the stored training mean in `transform`. ### Follow-up Questions - Why do most libraries compute PCA from an SVD of the centred data instead of eigendecomposing the covariance? - When `d` is much larger than `n`, how can you get the components without forming the `d × d` covariance? - How would you add `inverse_transform`, and how large is the reconstruction error it leaves? - When should features be standardized before PCA, and what does that change?

Overview: Implement PCA fit and transform in NumPy by eigendecomposing the sample covariance of centred data, with sorted components, a fixed sign convention and explained variance ratios. It tests covariance with the n - 1 denominator, correct use of a symmetric eigensolver, and projecting new data with the training mean.

PracHub logo
General
Nov 25, 2026
easyMachine Learning EngineerOtherMachine Learning
0
0

Implement PCA.fit(X) and PCA.transform(X) in NumPy by eigendecomposing the sample covariance of the centred data. fit returns self. transform projects data, centred with the training mean, onto the stored components.

Requirements:

  • After fit , set mean_ , n_components_ , components_ (shape (k, d) , orthonormal rows), explained_variance_ and explained_variance_ratio_ .
  • Covariance uses the n - 1 denominator. Components are sorted by descending eigenvalue.
  • explained_variance_ratio_ divides by the sum of all d eigenvalues, not only the kept ones.
  • Sign convention: flip each component so its largest-absolute entry is positive.
  • n_components=None keeps all d . A value outside 1..d raises ValueError .

For example:

X = [[12, 20], [10, 24], [8, 20], [10, 16]]
p = PCA(n_components=2).fit(X)
p.mean_                     # [10., 20.]
p.components_               # [[0., 1.], [1., 0.]]
p.explained_variance_       # [32/3, 8/3]
p.explained_variance_ratio_ # [0.8, 0.2]
p.transform([[11, 23], [10, 20]])  # [[3., 1.], [0., 0.]]

Constraints & Assumptions

  • X is array-like of shape (n, d) with n ≥ 2 and finite values.
  • Results must match sklearn.decomposition.PCA (under the sign convention above) to rtol=1e-6 .
  • Do not use sklearn in the solution. Only NumPy is allowed.

What a Strong Answer Covers Guidance

  • Centring with the training mean and building the covariance with the n - 1 denominator.
  • Using a symmetric eigensolver and reordering eigenvalues and eigenvector columns together into descending order.
  • Storing the components as rows and applying the sign convention to each one.
  • Computing the variance ratio over all d eigenvalues and validating n_components .
  • Reusing the stored training mean in transform .

Follow-up Questions Guidance

  • Why do most libraries compute PCA from an SVD of the centred data instead of eigendecomposing the covariance?
  • When d is much larger than n , how can you get the components without forming the d × d covariance?
  • How would you add inverse_transform , and how large is the reconstruction error it leaves?
  • When should features be standardized before PCA, and what does that change?