PCA Denoising Across Component Counts
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement the five NumPy functions below to denoise images with PCA. Fit PCA on the noisy data, reconstruct it from the top `k` components, and score each reconstruction by its MSE against the clean images.
- `add_gaussian_noise(X, sigma, seed)`: return `X + sigma * np.random.default_rng(seed).standard_normal(X.shape)`.
- `fit_pca(X)`: return `(mean, components, explained_variance, explained_variance_ratio)` with `min(n, d)` rows in descending-variance order. Variance uses `n - 1`. Flip each component's sign so that its largest-absolute loading is positive. If total variance is 0, the ratio is all zeros.
- `pca_reconstruct(X, mean, components, k)`: project the centred `X` onto the top `k` components and map back. Raise `ValueError` if `k < 0` or `k` exceeds the number of components.
- `denoising_errors(X_clean, X_noisy, ks)`: fit PCA on `X_noisy` and return a float array of shape `(len(ks),)` holding the MSE of each rank-`k` reconstruction against `X_clean`.
- `best_denoising_k(X_clean, X_noisy, ks)`: return the `int` `k` with the lowest error. Ties go to the smallest `k`.
For example:
```python
Xn = add_gaussian_noise(X_clean, 0.5, 1) # X_clean: (200, 64)
mean, comps, ev, ratio = fit_pca(Xn) # comps: (64, 64), ratio sums to 1
pca_reconstruct(Xn, mean, comps, 0) # every row == mean
pca_reconstruct(Xn, mean, comps, 64) # == Xn, up to floating-point rounding
# X_clean has rank 3, with signal well above the noise level:
best_denoising_k(X_clean, Xn, [0, 1, 2, 3, 4, 10, 64]) # -> 3
```
```hint Where the components come from
Centre the data first. The thin SVD of the centred matrix gives the principal directions directly, and the squared singular values turn into variances once you divide by the right count.
```
```hint Which error moves which way
The error against the noisy data can only go down as `k` grows. Ask what each extra component adds once the signal directions are already covered, and measure against the clean images to see it.
```
### Constraints & Assumptions
- `X` is a 2-D float array of shape `(n, d)` with `n ≥ 2`.
- `X_clean` and `X_noisy` have the same shape, and `ks` is non-empty.
- Explained variance must match `sklearn.decomposition.PCA`.
- Use only NumPy. scikit-learn may be used only to check your results.
### What a Strong Answer Covers
- Centring before the SVD and dividing by `n - 1`, so the explained variance matches scikit-learn.
- A deterministic sign convention for the components and a safe ratio when the total variance is zero.
- Correct behaviour at the edge ranks `k = 0` and `k = min(n, d)`, plus the range check that raises `ValueError`.
- Fitting once on the noisy data, scoring against the clean data, and applying the smallest-`k` tie rule.
- How the error against the clean data changes as `k` grows, why it behaves that way, and which `k` it points to in the example.
### Follow-up Questions
- How would you choose `k` when no clean reference images are available?
- Why does the rank-`k` reconstruction error on the training data equal the sum of the discarded squared singular values?
- What changes if the noise is not isotropic, for example when some pixels are much noisier than others?
- How would you run this on millions of images that do not fit in memory?
Overview: Implement PCA denoising in NumPy: add seeded Gaussian noise, fit PCA by SVD with scikit-learn compatible variances, reconstruct from the top k components, and pick the k with the lowest error against the clean images. It tests centring, sign conventions, edge ranks and how the component count trades signal against noise.