Automatic DBSCAN Eps via Knee Detection
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement three functions that pick DBSCAN's `eps` automatically from the k-distance curve.
- `k_distances(X, k)` returns, as an ascending 1-D array, each point's Euclidean distance to its k-th nearest other point. The point itself is excluded, and a duplicate of the point counts as another point at distance 0.
- `find_knee(values)` takes an ascending array of length n and returns the index i maximizing `x_norm - y_norm`, where `x_norm = i / (n - 1)` and `y_norm = (v[i] - v[0]) / (v[-1] - v[0])`. Ties go to the lowest index. If n < 2 or the curve is flat (`v[-1] == v[0]`), return 0.
- `select_eps(X, k)` returns the k-distance at the knee as a `float`.
Example:
```python
X = [[0], [1], [2], [3], [4], [10], [20]]
k_distances(X, 1) # [1, 1, 1, 1, 1, 6, 10]
find_knee([1, 1, 1, 1, 1, 6, 10]) # 4
select_eps(X, 1) # 1.0
k_distances([[0, 0], [1, 0], [3, 0], [7, 0]], 2) # [2, 3, 3, 6]
```
```hint Excluding the point itself
Each point's distance row contains its own 0. Make sure the point's distance to itself is not counted as one of its k neighbors, while a separate duplicate point still is.
```
```hint Reading the knee score
After normalizing, the curve starts at (0, 0) and ends at (1, 1). Think about what `x_norm - y_norm` measures relative to the straight line between those endpoints.
```
### Constraints & Assumptions
- `X` is a 2-D array of shape `(n, d)`; a non-2-D `X` raises `ValueError`.
- `k` must be an integer from 1 to n - 1; anything else raises `ValueError` (from `k_distances`, and so from `select_eps`).
- `find_knee` receives values sorted in ascending order.
### What a Strong Answer Covers
- Excluding each point from its own neighbor list while still counting duplicates at distance 0
- Picking the k-th nearest distance per point, then sorting the results, with validation of `X` and `k`
- The knee score, what it measures geometrically, and the tie, flat-curve and short-input rules
- Why the knee of the k-distance curve is a reasonable `eps` for DBSCAN, and when it misleads
- Time and memory cost of the all-pairs approach and what to use for large n
### Follow-up Questions
- How would you compute the k-distances for a million points?
- How should k relate to DBSCAN's `min_samples` parameter?
- What goes wrong when the clusters have very different densities?
- A single extreme outlier sits at the end of the curve. How does it affect the chosen `eps`, and how would you guard against it?
Overview: Implement k-distance computation and a knee detector that picks DBSCAN's eps automatically from the sorted k-distance curve. It tests nearest-neighbor distances with self-exclusion, normalized knee scoring, tie handling and why the knee separates dense points from noise.