Davies-Bouldin Index From Scratch
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `davies_bouldin_index(X, labels)` using only NumPy. `X` is an `(n, d)` array and `labels` assigns each row to a cluster. Return the Davies-Bouldin index as a Python `float`, matching `sklearn.metrics.davies_bouldin_score`.
- Scatter $s_i$: mean Euclidean distance of cluster $i$'s points to its centroid $c_i$ (the mean of those points).
- Index: mean over $i$ of $\max_{j\ne i} (s_i + s_j) / \lVert c_i - c_j \rVert$.
- If all scatters are zero (or all centroid distances are zero), return `0.0`.
- Raise `ValueError` if the number of distinct labels is outside $[2, n - 1]$, or if `X` is not 2-D or `labels` is not 1-D of length $n$.
Example:
```python
X = [[0, 0], [2, 0], [10, 0], [12, 0]]
labels = [0, 0, 1, 1]
davies_bouldin_index(X, labels) # 0.2
```
Both clusters have scatter 1, and their centroids $(1, 0)$ and $(11, 0)$ are 10 apart, so each cluster's worst ratio is $(1 + 1) / 10 = 0.2$ and their mean is 0.2.
```hint Watch the zeros
The centroid distance matrix has zeros on its diagonal, and two different clusters can share a centroid. Decide what the ratio should be in each case before you take a row maximum, and compare your choice with what sklearn returns.
```
### Constraints & Assumptions
- Labels may be arbitrary integers (for example `42` or `-3`). The result must not depend on label names.
- Clusters may be unbalanced in size. Values are finite.
- Results must match sklearn within `rtol=1e-7`.
### What a Strong Answer Covers
- Input validation for the rank of `X`, the rank and length of `labels`, and the allowed number of clusters.
- Grouping rows by their distinct label values so arbitrary integers work and renaming labels leaves the result unchanged.
- Scatter as the mean unsquared Euclidean distance to the centroid, and the pairwise centroid distance matrix.
- How self-pairs, coincident centroids and the all-zero cases are handled so each row maximum matches sklearn.
- Time and space complexity in terms of $n$, $d$ and $k$.
### Follow-up Questions
- How would you compute the index for a dataset too large to fit in memory, streaming over the rows?
- Can the Davies-Bouldin index be used to choose the number of clusters, and what kind of clusters does it favor?
- What would the index report for two interleaved half-moon clusters that DBSCAN separates correctly, and why?
- How does this index compare with the silhouette score in cost and in what it measures?
Overview: Implement the Davies-Bouldin clustering index with NumPy alone and match scikit-learn's davies_bouldin_score on arbitrary integer labels. Tests per-cluster scatter and centroid distances, handling of zero distances and coincident centroids, and careful input validation.