Relative Contrast of Nearest-Neighbor Distances Under Growing Dimensionality
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `relative_contrast(query, points, p=2.0)`. It returns `(max - min) / min`, where `max` and `min` are the largest and smallest Minkowski-`p` distances from `query` (shape `(d,)`) to the rows of `points` (shape `(n, d)`).
Then implement `contrast_curve(dims, n_points, n_trials, seed, p=2.0)`. For each dimension `d` in `dims`, it runs `n_trials` trials on uniform random data and returns a float array holding the mean relative contrast for each `d`.
For example:
```python
q = [0, 0]; pts = [[3, 4], [1, 0], [0, 2]]
relative_contrast(q, pts) # 4.0 (5 - 1) / 1
relative_contrast(q, pts, p=1) # 6.0 (7 - 1) / 1
relative_contrast(q, pts, p=np.inf) # 3.0 (4 - 1) / 1
```
```hint Vectorize the distances
Broadcast `points - query` to get an `(n, d)` array of coordinate gaps, then reduce along axis 1. Check what the power formula does when `p` is infinite.
```
```hint Reproducibility
The expected numbers depend on the exact sequence of random draws. Think about where the generator is created and in which order the arrays are drawn.
```
### Constraints & Assumptions
- `p` is positive or `np.inf`. For `np.inf` the distance is Chebyshev: the largest absolute coordinate difference.
- If the nearest distance is exactly `0`, return `np.inf`.
- RNG: create `rng = np.random.default_rng(seed)` once. For each `d` in `dims`, in order, and for each trial, draw `query = rng.random(d)` first and then `points = rng.random((n_points, d))`.
- The output of `contrast_curve` has shape `(len(dims),)`.
### What a Strong Answer Covers
- A vectorized Minkowski distance that is correct for finite `p` and for `p = np.inf`.
- The zero nearest-distance case, which returns `np.inf` instead of dividing by zero.
- A single seeded generator with the draw order exactly as specified, and an output array of length `len(dims)`.
- The time and memory cost of the curve in terms of trials, points and dimensions.
- Why the curve falls as `d` grows, and roughly how fast.
### Follow-up Questions
- Why does the relative contrast shrink as dimension grows, and at what rate for i.i.d. coordinates?
- How does the choice of `p` change the curve? Would a fractional `p` such as 0.5 keep more contrast in high dimensions?
- What does a shrinking contrast mean in practice for k-nearest neighbors and for nearest-neighbor indexes?
- Real embeddings often have hundreds of dimensions and still return useful neighbors. Why?
Overview: Implement the relative contrast of Minkowski distances in NumPy, then a seeded experiment that averages it across growing dimensions. Tests vectorized distance code, the Chebyshev and zero-distance edge cases, reproducible random sampling, and how nearest-neighbor distances behave in high dimensions.