PCA Transformer with Whitening and Reconstruction

Quick Overview

Implement principal component analysis from scratch in NumPy as a transformer class with fit, transform and inverse_transform, optional whitening, and a reconstruction error helper. It tests SVD-based PCA, a deterministic sign convention, variance bookkeeping and numerical edge cases.

PCA Transformer with Whitening and Reconstruction

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: medium

Interview Round: Other

Implement a `PCA` class with `fit`, `transform`, `fit_transform` and `inverse_transform`, using NumPy only, with optional whitening. Also implement `reconstruction_error(X, n_components)`, which returns the mean squared error between `X` and its rank-k reconstruction as a Python `float`. The class must meet these requirements: - `fit` sets `mean_`, `components_` (shape `(k, d)`, orthonormal rows, in descending order of variance), `explained_variance_` (computed with `ddof=1`), `explained_variance_ratio_` and `n_components_`, and returns `self`. - Sign convention: each component's largest-magnitude entry is positive. - `n_components=None` means `min(n, d)`. A value outside `[1, min(n, d)]`, or fewer than two samples (`n < 2`), raises `ValueError`. - With `whiten=True`, `transform` divides the scores by `sqrt(max(explained_variance_, eps))`, and `inverse_transform` undoes that scaling. - `transform` and `inverse_transform` reuse the training mean on new data. - `explained_variance_ratio_` is relative to the total variance summed over all components, kept or discarded, and is all zeros when that total is 0. Example: ```python X = [[2, 0], [0, 1], [-2, 0], [0, -1]] p = PCA().fit(X) p.components_ # [[1, 0], [0, 1]] p.explained_variance_ # [8/3, 2/3] p.explained_variance_ratio_ # [0.8, 0.2] p.transform([[1, 1]]) # [[1, 1]] ``` ```hint Where the axes come from Center with the training mean, then decompose the centered matrix itself. Work out how its singular values relate to variances computed with ddof=1. ``` ```hint Deterministic signs A singular vector and its negation are equally valid, and solvers do not agree on which one they return. Apply the sign rule to each kept row after slicing. ``` ### Constraints & Assumptions - NumPy only, no scikit-learn or SciPy. - `X` is a 2D array-like of numbers with shape `(n, d)`. Plain Python lists must work, as in the example. - Data passed to `transform` has the same `d` columns as the training data, and scores passed to `inverse_transform` have `k` columns. - The constructor is `PCA(n_components=None, whiten=False, eps=1e-12)`. ### What a Strong Answer Covers - How the principal axes and their variances come out of a decomposition of the centered data, including the `ddof=1` scaling. - A sign rule applied to each kept component so the output does not depend on the solver. - Validation of `n_components` and the sample count, and the variance ratio when the total variance is zero. - Whitening and its exact inverse, and what the `eps` floor protects against. - The reconstruction error computation and the cost of `fit` and `transform`. ### Follow-up Questions - Why use SVD of the centered data instead of eigendecomposing the covariance matrix? - How does reconstruction error relate to the discarded eigenvalues? - How would you scale this to data too large for a full SVD?

Overview: Implement principal component analysis from scratch in NumPy as a transformer class with fit, transform and inverse_transform, optional whitening, and a reconstruction error helper. It tests SVD-based PCA, a deterministic sign convention, variance bookkeeping and numerical edge cases.

General logo
General
Nov 25, 2026
mediumMachine Learning EngineerOtherMachine Learning
0
0

Implement a PCA class with fit, transform, fit_transform and inverse_transform, using NumPy only, with optional whitening. Also implement reconstruction_error(X, n_components), which returns the mean squared error between X and its rank-k reconstruction as a Python float.

The class must meet these requirements:

  • fit sets mean_ , components_ (shape (k, d) , orthonormal rows, in descending order of variance), explained_variance_ (computed with ddof=1 ), explained_variance_ratio_ and n_components_ , and returns self .
  • Sign convention: each component's largest-magnitude entry is positive.
  • n_components=None means min(n, d) . A value outside [1, min(n, d)] , or fewer than two samples ( n < 2 ), raises ValueError .
  • With whiten=True , transform divides the scores by sqrt(max(explained_variance_, eps)) , and inverse_transform undoes that scaling.
  • transform and inverse_transform reuse the training mean on new data.
  • explained_variance_ratio_ is relative to the total variance summed over all components, kept or discarded, and is all zeros when that total is 0.

Example:

X = [[2, 0], [0, 1], [-2, 0], [0, -1]]
p = PCA().fit(X)
p.components_                # [[1, 0], [0, 1]]
p.explained_variance_        # [8/3, 2/3]
p.explained_variance_ratio_  # [0.8, 0.2]
p.transform([[1, 1]])        # [[1, 1]]

Constraints & Assumptions

  • NumPy only, no scikit-learn or SciPy.
  • X is a 2D array-like of numbers with shape (n, d) . Plain Python lists must work, as in the example.
  • Data passed to transform has the same d columns as the training data, and scores passed to inverse_transform have k columns.
  • The constructor is PCA(n_components=None, whiten=False, eps=1e-12) .

What a Strong Answer Covers Guidance

  • How the principal axes and their variances come out of a decomposition of the centered data, including the ddof=1 scaling.
  • A sign rule applied to each kept component so the output does not depend on the solver.
  • Validation of n_components and the sample count, and the variance ratio when the total variance is zero.
  • Whitening and its exact inverse, and what the eps floor protects against.
  • The reconstruction error computation and the cost of fit and transform .

Follow-up Questions Guidance

  • Why use SVD of the centered data instead of eigendecomposing the covariance matrix?
  • How does reconstruction error relate to the discarded eigenvalues?
  • How would you scale this to data too large for a full SVD?