Implement PCA and LDA from scratch and compare how well each projection separates classes
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Given a feature matrix `X` of shape (n, d) and class labels `y`, implement PCA and LDA from scratch with NumPy and SciPy, then score how well each projection separates the classes. Components are returned as rows (shape k × d), and each component's sign is flipped so that its largest-magnitude entry is positive.
Implement these functions:
- `pca_project(X, n_components)` returns `(scores, components, explained_variance_ratio)`. The components are eigenvectors of the sample covariance sorted by descending eigenvalue, `scores` is the centred `X` multiplied by `components.T`, and each ratio is an eigenvalue divided by the total variance.
- `scatter_matrices(X, y)` returns `(S_W, S_B)` as unnormalised sums, with `S_B` weighted by class size, so that `S_W + S_B` equals the total scatter.
- `lda_project(X, y, n_components)` returns `(scores, components, discriminant_ratios)`. Solve `S_B w = λ S_W w`, sort the eigenvalues in descending order, scale each direction to unit length, and project `X` centred on the global mean. The ratios are the top eigenvalues.
- `fisher_criterion(Z, y)` returns the float `trace(S_W⁻¹ S_B)` computed on the embedding `Z`. A 1-D `Z` is treated as a single column.
- `compare_projections(X, y, n_components)` returns a dict with keys `"pca_fisher"`, `"lda_fisher"` and `"pca_explained_variance_ratio"`.
Example:
```python
X = [[0, 0], [2, 0], [1, 1], [4, 2], [6, 2], [5, 3]]
y = [0, 0, 0, 1, 1, 1]
S_W, S_B = scatter_matrices(X, y)
# S_W = [[4, 0], [0, 4/3]]
# S_B = [[24, 12], [12, 6]]
lda_scores, lda_components, ratios = lda_project(X, y, 1)
# lda_components = [[2, 3]] / sqrt(13)
# ratios = [10.5]
fisher_criterion(lda_scores, y)
# 10.5
compare_projections(X, y, 1)
# {"pca_fisher": about 8.47, "lda_fisher": 10.5,
# "pca_explained_variance_ratio": about [0.948]}
```
```hint What the solver returns
Check the order in which `scipy.linalg.eigh(A, B)` returns eigenvalues, and how it scales the eigenvectors. Neither matches what the spec asks for.
```
```hint Predicting the Fisher score
The Fisher criterion does not change when you rescale or recombine the embedding directions with an invertible matrix. Use that to work out what `fisher_criterion` should return on the LDA scores before you run it.
```
### Constraints & Assumptions
- `pca_project`: `1 ≤ n_components ≤ d`, otherwise raise `ValueError`.
- `lda_project`: `1 ≤ n_components ≤ min(n_classes - 1, d)`, otherwise raise `ValueError`.
- `S_W` is non-singular for every input.
- `compare_projections` passes the same `n_components` to both methods, so the value must also satisfy the LDA bound. With two classes, only 1 is valid.
### What a Strong Answer Covers
- Scatter matrices built as unnormalised sums with the class-size weight on the between-class term, consistent with `S_W + S_B` being the total scatter.
- PCA from the sample covariance with the `n - 1` denominator, with the descending sort, the sign convention and the explained variance ratio applied as specified.
- LDA through the symmetric generalized eigenproblem, with descending order, unit-length rows, the sign flip and the `ValueError` bounds.
- A Fisher criterion computed with a linear solve that also handles 1-D embeddings.
- Why the LDA score equals the sum of its kept eigenvalues, and how it compares with the PCA score.
### Follow-up Questions
- Why is LDA limited to `n_classes - 1` components, and what are the remaining generalized eigenvalues?
- How would you change `lda_project` if `S_W` were singular, for example with more features than samples?
- Can PCA ever reach a higher Fisher criterion than LDA with the same number of components? Justify your answer.
- How do the LDA directions relate to a Gaussian classifier that shares one covariance matrix across all classes?
Overview: Implement PCA and LDA from scratch with NumPy and SciPy, then compare how well each projection separates labeled classes using the Fisher criterion. It tests scatter matrices, the generalized eigenproblem, sign conventions, and the difference between keeping variance and separating classes.