Consensus Clustering via Co-Association Matrix
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Implement consensus clustering using NumPy only. `consensus_clustering` runs `n_runs` k-means fits on random subsamples, builds a co-association matrix, then hierarchically clusters `1 - coassoc` and returns `(labels, coassoc, Z)`. Write these five functions:
```python
def kmeans_lloyd(X, init_centroids, max_iter=100, tol=1e-8):
"""Return (labels, centroids, inertia)."""
def co_association(label_runs):
"""Return the (n, n) co-association matrix."""
def linkage_from_distance(D, method="average"):
"""Return the (n - 1, 4) linkage matrix of a square distance matrix."""
def cut_linkage(Z, n_clusters):
"""Return one flat cluster label per point."""
def consensus_clustering(X, k, n_runs=50, subsample_frac=0.8, seed=0,
method="average", n_clusters=None):
"""Return (labels, coassoc, Z)."""
```
Each function has to follow these rules:
- `kmeans_lloyd`: ties go to the lowest centroid index, empty clusters keep their previous centroid, and iteration stops when the largest centroid shift is at most `tol`. Recompute labels and inertia (sum of squared distances) from the final centroids.
- `co_association`: `label_runs` has one row per run and one column per point, and label `-1` means the point was not sampled in that run. Entry `(i, j)` is the number of runs where `i` and `j` share a cluster divided by the number of runs where both were sampled, `0` if they were never co-sampled. The diagonal is `1`.
- `linkage_from_distance`: return a SciPy-compatible `(n-1, 4)` matrix with rows `[a, b, dist, size]`. The cluster created at step `s` (counting from 0) gets id `n + s`. Support `single`, `complete` and `average`; any other method raises `ValueError`. When several pairs tie for the smallest distance, merge the pair `(a, b)` with `a < b` that comes first in lexicographic order.
- `cut_linkage`: apply the first `n - n_clusters` merges and number labels by first appearance (point 0 gets `0`). `n_clusters` outside `[1, n]` raises `ValueError`.
- `consensus_clustering`: follow the exact draw order below, then cut at `n_clusters` (which defaults to `k`).
The draw order for each run is fixed:
```python
m = max(k, floor(subsample_frac * n))
rng = np.random.default_rng(seed)
for r in range(n_runs):
idx = np.sort(rng.choice(n, size=m, replace=False))
init = rng.choice(m, size=k, replace=False)
labels_r = kmeans_lloyd(X[idx], X[idx][init], max_iter=100, tol=1e-8)[0]
# runs[r, idx] = labels_r, all other points stay -1
```
Example:
```python
C = co_association([[0, 0, 1, -1],
[1, -1, 1, 0],
[0, 1, 1, 0]])
# C[0, 1] = 0.5 co-sampled in runs 0 and 2, same cluster in run 0
# C[0, 2] = 1/3 co-sampled in all three runs, same cluster in run 1
# C[1, 3] = 0.0 co-sampled once (run 2), different clusters
Z = linkage_from_distance(1 - C, "average")
# [[0, 1, 0.5, 2], (0, 1), (0, 3) and (1, 2) tie at 0.5; (0, 1) comes first
# [2, 4, 7/12, 3], distance from {0, 1} to point 2 is (2/3 + 1/2) / 2
# [3, 5, 5/6, 4]]
cut_linkage(Z, 2) # [0, 0, 0, 1]
```
```hint Two counts per pair
For each pair, count the runs where both points were sampled separately from the runs where they also share a label. Two unsampled points both carry `-1`, and that must not count as a match.
```
```hint Updating distances after a merge
You do not need the original points to update distances after a merge. The new cluster's distance to any other cluster follows from the two old distances and the cluster sizes.
```
```hint One generator, one order
Every random draw comes from the same generator, in the order shown. One extra or reordered call changes every later run.
```
### Constraints & Assumptions
- NumPy only: no SciPy or scikit-learn in the implementation.
- `X` has shape `(n, d)`. `D` is a square, symmetric distance matrix with a zero diagonal.
- Inside `consensus_clustering`, k-means always runs with `max_iter=100` and `tol=1e-8`.
### What a Strong Answer Covers
- A Lloyd's loop that follows the tie, empty-cluster and stopping rules, with labels and inertia recomputed from the final centroids.
- A co-association matrix that divides only by co-sampled runs, gives never-co-sampled pairs `0` and sets the diagonal to `1`.
- Agglomerative merging with correct single, complete and size-weighted average updates, SciPy-style ids and rows, and the stated tie rule.
- A cut that replays exactly `n - n_clusters` merges and renumbers by first appearance, with the `ValueError` checks in every function that needs them.
- The pinned draw order from one generator, and the time and memory cost of each stage.
### Follow-up Questions
- How would you choose `k` and `n_clusters` using the co-association matrix?
- The co-association matrix and the naive linkage are quadratic and cubic in `n`. How would you scale this to tens of thousands of points?
- Why subsample the points at all, instead of rerunning k-means on the full data with different seeds?
- Why does average linkage usually behave better than single linkage on `1 - C`?
Overview: Implement consensus clustering in NumPy by running k-means on random subsamples, building a co-association matrix, and applying agglomerative clustering to one minus that matrix before cutting the tree. Tests Lloyd's algorithm details, linkage distance updates, SciPy-style linkage output and reproducible random draws.