Calinski-Harabasz Index from Dispersions
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Given a feature matrix `X` (shape `(n, d)`) and cluster `labels`, implement `between_within_dispersion(X, labels)` returning the float tuple `(B, W)`, and `calinski_harabasz_score(X, labels)` returning $\frac{B / (k - 1)}{W / (n - k)}$ as a float.
$$B = \sum_c n_c \, \lVert \mu_c - \mu \rVert^2 \qquad W = \sum_c \sum_{x \in c} \lVert x - \mu_c \rVert^2$$
Here $n_c$ is the size of cluster $c$, $\mu_c$ is its centroid and $\mu$ is the overall mean. $B$ sums cluster size times the squared distance from the centroid to the overall mean, and $W$ sums the squared distance of every point to its own centroid.
- `k` is the number of distinct labels. Raise `ValueError` unless ${2 \le k \le n - 1}$.
- If `W == 0`, return `1.0`.
Example:
```python
X = [[0, 0], [0, 2], [4, 0], [4, 2]]
labels = [0, 0, 1, 1]
between_within_dispersion(X, labels) # (16.0, 4.0)
calinski_harabasz_score(X, labels) # (16/1) / (4/2) = 8.0
```
```hint Group by label value
Do not assume the labels run from 0 to k-1. Group rows by their distinct label values, and compute the overall mean once from all rows.
```
### Constraints & Assumptions
- `X` may be integer-typed: treat it as float.
- Labels are arbitrary hashable values (ints, negative ints or strings). The result must not depend on label values.
- `len(labels) == n`.
- Results must match `sklearn.metrics.calinski_harabasz_score` to `1e-7` relative tolerance.
### What a Strong Answer Covers
- Correct between and within dispersion from the overall mean and per-cluster centroids, computed in floating point.
- Grouping by distinct label values so that arbitrary, negative or string labels give the same result.
- The `ValueError` check on `k` before any division, and the `1.0` return when `W` is zero.
- Why the two terms are divided by `k - 1` and `n - k`, and the cost of the computation.
### Follow-up Questions
- What kinds of cluster shapes does this index favor, and when would you distrust a high score?
- How would you use the score to pick the number of clusters, and why can it not score `k = 1`?
- How does feature scaling change the score?
- How would you compute `B` and `W` without a Python loop over clusters?
Overview: Implement the Calinski-Harabasz clustering index in Python by computing between-cluster and within-cluster dispersion from centroids and the overall mean. Tests the degrees-of-freedom normalization, input validation on the cluster count, label-independent grouping and agreement with scikit-learn.