Scalable Top-k PCA via Subspace Iteration

Quick Overview

Implement top-k PCA with randomized subspace iteration in NumPy without forming the covariance matrix or taking a full SVD, plus transform and inverse transform. Tests block power methods, Rayleigh-Ritz extraction, PCA conventions and matching exact PCA to a tight tolerance.

Scalable Top-k PCA via Subspace Iteration

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Implement `top_k_pca(X, n_components, n_iter=100, n_oversamples=5, seed=0)` using power iteration with deflation or randomized subspace iteration. Do not form the `d x d` covariance matrix and do not take a full SVD of `X`. Also implement `pca_transform(X, components, mean)` and `pca_inverse_transform(Z, components, mean)`. Requirements: - Return a dict with `components` (`k x d`, orthonormal rows), `explained_variance`, `explained_variance_ratio` and `mean`. - Center on the column mean. Variances use the `n - 1` denominator and are sorted in descending order. - Each ratio is the variance divided by the total variance (`sum(Xc**2) / (n - 1)`). - Flip each component's sign so that its largest-magnitude entry is positive. - `n_components` outside `[1, min(n, d)]` raises `ValueError`. Transforms use the given `mean`. Example: ```python X = [[3,5],[1,6],[-1,5],[1,4]] top_k_pca(X, 2) # components = [[1,0],[0,1]], explained_variance = [8/3, 2/3] # explained_variance_ratio = [0.8, 0.2], mean = [1, 5] res = top_k_pca(X, 1) pca_transform([[4,7],[1,5]], res["components"], res["mean"]) # [[3],[0]] pca_inverse_transform([[3],[0]], res["components"], res["mean"]) # [[4,5],[1,5]] ``` ```hint Avoiding the covariance The covariance only ever has to act on a thin block of vectors. Work out how to compute that product from the centred data alone, and in which order to multiply. ``` ```hint Keeping the block healthy Repeated multiplication pushes every column of the block toward the top direction. Think about what has to happen to the block between multiplications. ``` ```hint From a subspace to eigenpairs A block that spans the top subspace still does not hold the individual eigenvectors. A small eigenproblem inside that subspace recovers them. ``` ### Constraints & Assumptions - `d` can be up to about 2000 with `n ≪ d` (wide matrices). - Results must match exact PCA (for example scikit-learn with `svd_solver="full"`) to about `1e-7` and must not depend on `seed`. - Test spectra have distinct leading eigenvalues. ### What a Strong Answer Covers - How the covariance is applied to a block of vectors without being formed, and what each iteration costs. - Re-orthonormalization during the iteration and why it is needed. - Recovering eigenvalues and eigenvectors from the converged subspace in descending order, with `n - 1` variances, ratios against the total variance, and the sign convention. - Why the result stops depending on the seed once it converges, and what controls the convergence rate. - Input validation and transforms that use the given mean. ### Follow-up Questions - Why do oversampling and more iterations improve accuracy, and how do they trade off cost? - How would you handle data that does not fit in memory? - Why re-orthonormalize with QR every iteration instead of only at the end?

Overview: Implement top-k PCA with randomized subspace iteration in NumPy without forming the covariance matrix or taking a full SVD, plus transform and inverse transform. Tests block power methods, Rayleigh-Ritz extraction, PCA conventions and matching exact PCA to a tight tolerance.

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

Implement top_k_pca(X, n_components, n_iter=100, n_oversamples=5, seed=0) using power iteration with deflation or randomized subspace iteration. Do not form the d x d covariance matrix and do not take a full SVD of X. Also implement pca_transform(X, components, mean) and pca_inverse_transform(Z, components, mean).

Requirements:

  • Return a dict with components ( k x d , orthonormal rows), explained_variance , explained_variance_ratio and mean .
  • Center on the column mean. Variances use the n - 1 denominator and are sorted in descending order.
  • Each ratio is the variance divided by the total variance ( sum(Xc**2) / (n - 1) ).
  • Flip each component's sign so that its largest-magnitude entry is positive.
  • n_components outside [1, min(n, d)] raises ValueError . Transforms use the given mean .

Example:

X = [[3,5],[1,6],[-1,5],[1,4]]
top_k_pca(X, 2)
# components = [[1,0],[0,1]], explained_variance = [8/3, 2/3]
# explained_variance_ratio = [0.8, 0.2], mean = [1, 5]

res = top_k_pca(X, 1)
pca_transform([[4,7],[1,5]], res["components"], res["mean"])  # [[3],[0]]
pca_inverse_transform([[3],[0]], res["components"], res["mean"])  # [[4,5],[1,5]]

Constraints & Assumptions

  • d can be up to about 2000 with n ≪ d (wide matrices).
  • Results must match exact PCA (for example scikit-learn with svd_solver="full" ) to about 1e-7 and must not depend on seed .
  • Test spectra have distinct leading eigenvalues.

What a Strong Answer Covers Guidance

  • How the covariance is applied to a block of vectors without being formed, and what each iteration costs.
  • Re-orthonormalization during the iteration and why it is needed.
  • Recovering eigenvalues and eigenvectors from the converged subspace in descending order, with n - 1 variances, ratios against the total variance, and the sign convention.
  • Why the result stops depending on the seed once it converges, and what controls the convergence rate.
  • Input validation and transforms that use the given mean.

Follow-up Questions Guidance

  • Why do oversampling and more iterations improve accuracy, and how do they trade off cost?
  • How would you handle data that does not fit in memory?
  • Why re-orthonormalize with QR every iteration instead of only at the end?