Gaussian and Sparse Random Projection
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement six functions using NumPy only. Together they compute the Johnson-Lindenstrauss target dimension, build seeded Gaussian and Achlioptas sparse projection matrices of shape `(n_components, n_features)`, project data, and measure how well pairwise distances are preserved.
Use these signatures:
```python
def jl_min_dim(n_samples, eps): ...
def gaussian_random_matrix(n_components, n_features, seed): ...
def sparse_random_matrix(n_components, n_features, density=1.0 / 3.0, seed=0): ...
def random_project(X, method, n_components, seed, density=1.0 / 3.0): ...
def pairwise_distortion(X, Y): ...
def fraction_within_bound(X, Y, eps): ...
```
Below, `k = n_components` and `d = n_features`. The functions behave as follows:
- `jl_min_dim` returns `int(4·ln(n) / (eps²/2 - eps³/3))` (truncated), where `n = n_samples`. It raises `ValueError` unless `0 < eps < 1` and `n_samples > 0`.
- Both matrix builders use `rng = np.random.default_rng(seed)` and raise `ValueError` on non-positive dimensions. The Gaussian builder returns `rng.standard_normal((k, d)) / sqrt(k)`.
- The sparse builder draws `u = rng.random((k, d))` and sets `s = sqrt(1/(density·k))`. An entry is `+s` where `u < density/2`, `-s` where `density/2 ≤ u < density`, and `0` elsewhere. It raises `ValueError` unless `0 < density ≤ 1`.
- `random_project` returns `X @ R.T`, where `method` is `"gaussian"` or `"sparse"`. Any other value raises `ValueError`.
- `pairwise_distortion` returns a 1-D array of squared-distance ratios `‖yᵢ - yⱼ‖² / ‖xᵢ - xⱼ‖²` for pairs `i < j` in `pdist` order. Mismatched row counts raise `ValueError`.
- `fraction_within_bound` returns the `float` fraction of ratios in `[1 - eps, 1 + eps]` (inclusive, with no range check on `eps`).
Example:
```python
jl_min_dim(100, 0.5) # 221
jl_min_dim(50, 0.5) # 187
X = [[0, 0], [1, 0], [0, 2]]
Y = [[0], [2], [1]]
pairwise_distortion(X, Y) # [4.0, 0.25, 0.2] pairs (0,1), (0,2), (1,2)
fraction_within_bound(X, Y, 0.5) # 0.0
```
In the second example the pairs have squared distances 1, 4 and 5 in `X` and 4, 1 and 1 in `Y`, so none of the three ratios falls inside `[0.5, 1.5]`.
```hint Pair order
`pdist` lists pairs row by row: (0, 1), (0, 2), and so on, then (1, 2). Look for a NumPy index helper that produces the same order so every pair difference comes from one vectorized step.
```
```hint Seeded output
The expected matrices depend on the exact draws. Create the generator inside each builder and draw the whole `(k, d)` array in one call with the shape given, or the same seed will produce different numbers.
```
### Constraints & Assumptions
- `X` is a 2-D array of shape `(n_samples, n_features)`, and `Y` must have the same number of rows.
- Only NumPy is available (no SciPy or scikit-learn).
- `seed` is any value `np.random.default_rng` accepts.
- `density` defaults to 1/3.
### What a Strong Answer Covers
- The JL formula with truncation and the input checks the spec asks for.
- Seeded Gaussian and sparse builders that reproduce the exact draws, and the reason for each scale factor.
- Pairwise ratios in `pdist` order without Python loops, and the inclusive band test.
- Time and memory cost of the projection and of the pairwise step.
- Degenerate inputs: duplicate rows in `X`, fewer than two rows, and a target dimension at or above `n_features`.
### Follow-up Questions
- Why is the sparse matrix scaled by `sqrt(1/(density·k))`?
- How would you pick `density` for very high-dimensional sparse input?
- Why does `jl_min_dim` not depend on the original feature count?
Overview: Implement Gaussian and Achlioptas sparse random projection in NumPy, along with the Johnson-Lindenstrauss target dimension and a check of how well pairwise distances survive the projection. It tests seeded matrix construction, the scaling that preserves squared lengths, and vectorized pairwise distance ratios.