Multi-Class Fisher LDA From Scratch
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement `scatter_matrices(X, y)`, which returns the unnormalised within-class and between-class scatter matrices `(S_W, S_B)`:
$$S_W = \sum_c \sum_{i \in c} (x_i - \mu_c)(x_i - \mu_c)^\top, \qquad S_B = \sum_c n_c (\mu_c - \mu)(\mu_c - \mu)^\top$$
Here $\mu_c$ and $n_c$ are the mean and size of class $c$, and $\mu$ is the overall mean. Also implement a `FisherLDA` class with `fit`, `transform` and `fit_transform` that projects data onto the top discriminant directions of the generalized eigenproblem $S_B w = \lambda (S_W + \text{reg} \cdot I) w$.
```python
def scatter_matrices(X, y): ...
class FisherLDA:
def __init__(self, n_components=None, reg=1e-6): ...
def fit(self, X, y): ...
def transform(self, X): ...
def fit_transform(self, X, y): ...
```
Requirements:
- With `n_components=None`, use `k = min(C - 1, d)`, where `C` is the number of classes and `d` the number of features. A value outside `[1, min(C - 1, d)]`, or fewer than 2 classes, raises `ValueError`.
- `scalings_` (shape `(d, k)`) holds the eigenvectors sorted by descending eigenvalue and normalised so that `W.T @ (S_W + reg * I) @ W = I`. Flip each column's sign so its largest-magnitude entry is positive.
- Set `eigenvalues_` (the top `k`), `classes_`, `mean_` and `means_` (one class mean per entry of `classes_`). `fit` returns `self`.
- `explained_variance_ratio_ = eigenvalues_ / sum(top min(C - 1, d) eigenvalues)`.
- `transform(X) = (X - mean_) @ scalings_`, where `mean_` is the overall training mean.
Example:
```python
X = [[1, 2], [3, 4], [5, 0], [7, 2]]
y = [0, 0, 1, 1]
scatter_matrices(X, y)
# S_W = [[4, 4], [4, 4]]
# S_B = [[16, -8], [-8, 4]]
```
```hint Pick the right solver
The left matrix is symmetric and the right matrix is symmetric positive definite once the ridge is added. Look for a solver that takes that pair directly, and check what normalization it gives the eigenvectors.
```
```hint Count the useful directions
Work out the rank of $S_B$ from the number of classes. It tells you how many eigenvalues can be nonzero and why the default `k` is what it is.
```
```hint Make the output deterministic
Eigensolvers return eigenvalues in a fixed order that may not be the one you need, and each eigenvector's sign is arbitrary. Both have to be pinned down before two runs can be compared.
```
### Constraints & Assumptions
- `X` has shape `(n, d)`. Labels `y` may be ints or strings.
- `S_W` may be singular (for example, with duplicated features). `reg` is non-negative with default `1e-6`.
- `numpy` and `scipy` are allowed. `sklearn` is not.
### What a Strong Answer Covers
- Scatter matrices that match the unnormalised definitions and reproduce the worked example.
- How the regularized generalized eigenproblem is solved, and how `scalings_` ends up with the required normalization.
- A deterministic result: eigenvalue order and the per-column sign rule.
- Validation of the class count and of `n_components`.
- How many directions carry signal and why, and what happens when `S_W` is singular.
### Follow-up Questions
- How would you choose `reg` in practice?
- How would you scale this when `d` is much larger than `n`?
Overview: Implement multi-class Fisher linear discriminant analysis with NumPy and SciPy: build the within-class and between-class scatter matrices, solve the regularized generalized eigenproblem, and project data onto the top discriminant directions. It tests linear algebra, numerical care with singular matrices and deterministic output.