Pairwise Distance Matrix for Five Metrics and Top-k Nearest Neighbors in NumPy
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `pairwise_distances(X, Y=None, metric="euclidean", p=2.0, VI=None)`, returning the `(n_X, n_Y)` distance matrix. `Y=None` means `Y = X`, and 1-D inputs are a single row. Then implement `kneighbors(X_train, X_query, k, metric="euclidean", p=2.0, VI=None, exclude_self=False)`, returning the `k` nearest training rows for each query. With `exclude_self=True`, query row `i` may not match training row `i`.
Requirements:
- Metrics: `"manhattan"`, `"euclidean"`, `"minkowski"` ($p \ge 1$, with `p=np.inf` meaning Chebyshev), `"cosine"` (1 minus cosine similarity, clipped to [0, 2]) and `"mahalanobis"` ($\sqrt{(x - y)^\top VI \, (x - y)}$). Only `"minkowski"` uses `p`.
- Cosine: exactly one zero vector gives 1, and two zero vectors give 0.
- Mahalanobis with `VI=None`: use the pseudo-inverse of the sample covariance (`ddof=1`) of `X`, and in `kneighbors` of `X_train`.
- `kneighbors` returns `(distances, indices)`, each of shape `(n_query, k)`, sorted ascending by distance, with ties going to the lower training index and indices of dtype `int64`.
- Raise `ValueError` for an unknown metric, `p < 1`, a feature-count mismatch, `k` outside `[1, n_train]` (`[1, n_train - 1]` with `exclude_self`), or `exclude_self` with differing row counts.
Example:
```python
X_train = [[2, 2], [1, 0], [0, 1], [-1, 0], [0, -1]]
kneighbors(X_train, [[0, 0]], k=3, metric="manhattan")
# -> distances [[1., 1., 1.]], indices [[1, 2, 3]]
X = [[0], [1], [3], [7]]
kneighbors(X, X, k=2, exclude_self=True)
# -> indices [[1, 2], [0, 2], [1, 0], [2, 1]]
# distances [[1., 3.], [1., 2.], [2., 3.], [4., 6.]]
```
```hint Shared computation
Several of these metrics are the same calculation with a different exponent. Find what they share before writing five separate functions.
```
```hint Where the default covariance comes from
Look at which array `pairwise_distances` receives as its first argument when `kneighbors` calls it, and which rows a default `VI` would then be estimated from.
```
```hint Excluding the self-match
Editing the distance matrix before ranking is simpler than filtering indices after ranking. Check how that choice interacts with the allowed range of `k`.
```
### Constraints & Assumptions
- `X`, `Y`, `X_train` and `X_query` are lists or NumPy arrays of numbers, either 1-D (one row) or 2-D with shape `(n, d)`.
- `p` is a number with $p \ge 1$, or `np.inf`.
- A caller-supplied `VI` is a `(d, d)` matrix.
### What a Strong Answer Covers
- Correct formulas for all five metrics behind one dispatcher, including Chebyshev at `p=np.inf` and the zero-vector rules for cosine.
- The default `VI` estimated from the right array in each function, using the pseudo-inverse of the `ddof=1` covariance.
- Ranking with the lower-index tie rule, `exclude_self` handled so the self-match can never appear, and `int64` indices.
- Every listed `ValueError`, ideally raised before the distance matrix is built.
- Time and memory cost of the broadcast approach, and how Mahalanobis changes it.
### Follow-up Questions
- How would you scale this to ${10^6}$ training rows without materializing the full distance tensor?
- What numerical pitfalls does the GEMM-based Euclidean expansion introduce?
- What happens when the covariance is singular, and how would you get a usable `VI`?
Overview: Implement a NumPy pairwise distance function for Manhattan, Euclidean, Minkowski, cosine and Mahalanobis metrics, then a k-nearest-neighbors query with deterministic tie-breaking and optional self-exclusion. It tests broadcasting, metric edge cases, input validation and the cost of brute-force neighbor search.