Build an embedding compressor with PCA and random projection, and measure cosine similarity error
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `EmbeddingCompressor(n_components=256, method="pca", seed=0)` with `fit`, `transform` and `inverse_transform`, supporting `method="pca"` and `method="random"` (Gaussian random projection). Also implement `cosine_similarity_error(X, Z, pairs=None)`, which returns the mean absolute difference between pairwise cosine similarities in `X` and `Z` as a Python `float`. A typical use is shrinking high-dimensional embeddings before cosine similarity search and checking how much the similarities move.
Requirements:
- PCA: centre by `mean_`, take the SVD, and store `components_` with shape `(k, d)` sorted by variance, each row sign-flipped so its largest-magnitude entry is positive. `explained_variance_` uses `n - 1`, and `explained_variance_ratio_` divides by the total variance (matching scikit-learn). `transform` returns `(X - mean_) @ components_.T`.
- Random: `R = np.random.default_rng(seed).standard_normal((d, k)) / sqrt(k)` and `components_ = R.T`. There is no centring, and `transform` returns `X @ R`.
- `inverse_transform` (PCA only) returns `Z @ components_ + mean_`. On `"random"` it raises `ValueError`.
- Raise `ValueError` on an unknown method, a PCA `k` outside `[1, min(n, d)]`, a random `k < 1`, or a row-count mismatch in `cosine_similarity_error`.
- `pairs=None` means all pairs `i < j`. Otherwise `pairs` is an `(m, 2)` list of row indices. Floor each product of norms at `1e-12`.
- `fit` returns `self`. Use NumPy only (no scikit-learn).
Example:
```python
X = [[1, 0], [0, 1], [1, 1]]
Z = [[1, 0], [1, 1], [1, 1]]
cosine_similarity_error(X, Z) # 0.3333 (1/3)
cosine_similarity_error(X, Z, pairs=[[0, 1]]) # 0.7071 (1/sqrt(2))
```
Over the three pairs, the cosines in `X` are 0, 0.7071 and 0.7071 and the cosines in `Z` are 0.7071, 0.7071 and 1, so the mean absolute difference is (0.7071 + 0 + 0.2929) / 3 = 1/3.
```hint Sign and order
`np.linalg.svd` returns singular values in descending order, but the sign of each singular vector is arbitrary. Make sure the flip is deterministic and applies to every row you keep.
```
```hint The random scaling
For a fixed vector `x`, work out the expected squared norm of `x @ R`. The `1/sqrt(k)` factor should make the answer simple.
```
### What a Strong Answer Covers
- A PCA fit through the thin SVD of centred data, with the deterministic sign flip, the `n - 1` variance and the ratio against total variance.
- A random projection with the exact seed, shape and `1/sqrt(k)` scaling, and no centring.
- `transform` and `inverse_transform` that follow each method's rules, plus every `ValueError` case.
- A vectorised cosine error over the default or given pairs, with the norm floor.
- When each method preserves cosine similarities better, and why the scaling keeps random projection unbiased.
### Follow-up Questions
- When does PCA preserve cosine similarities better than random projection, and when would random projection be the better choice?
- How would you fit PCA on millions of 1536-dimensional embeddings that do not fit in memory?
- Should embeddings be L2-normalized before or after compression for cosine search?
Overview: Implement an embedding compressor in NumPy that supports PCA and Gaussian random projection, then measure how well each one preserves pairwise cosine similarities. It tests SVD-based PCA details, random projection scaling, and vectorised similarity evaluation.