Implement Spectral Clustering From Scratch in NumPy
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: hard
Interview Round: Other
Given points `X` with shape `(n, d)`, implement the five functions below so that `spectral_clustering(X, k, gamma)` returns an integer label array of length `n`.
```python
import numpy as np
from scipy.linalg import eigh
def rbf_affinity(X, gamma):
"""Return the n x n RBF affinity matrix."""
def normalized_laplacian(W):
"""Return the symmetric normalized Laplacian of W."""
def spectral_embedding(L, k):
"""Return the row-normalized n x k spectral embedding."""
def kmeans(X, init_centroids, max_iter=300, tol=1e-8):
"""Return (labels, centroids, inertia)."""
def spectral_clustering(X, k, gamma=1.0):
"""Return cluster labels for X."""
```
Each function has to follow these rules.
- `rbf_affinity` returns `W[i, j] = exp(-gamma * ||x_i - x_j||²)` with a zero diagonal.
- `normalized_laplacian` returns `L = I - D^{-1/2} W D^{-1/2}`, symmetric. A zero-degree node uses `0` for `d^{-1/2}`, which gives it an identity row.
- `spectral_embedding` takes the eigenvectors of the `k` smallest eigenvalues, flips each one so its largest-magnitude entry is positive, then scales the rows to unit norm. Zero rows stay as they are.
- `kmeans` runs Lloyd iterations from `init_centroids`. A distance tie goes to the lowest centroid index, an empty cluster keeps its centroid, and the loop stops when the largest centroid shift is at most `tol`. It returns `(labels, centroids, inertia)`, where the labels are reassigned to the final centroids and `inertia` is the sum of squared distances as a float.
- `spectral_clustering` builds the embedding, picks initial centroids by farthest-point selection starting at row `0`, runs `kmeans`, then relabels the clusters in order of first appearance (`0, 1, 2, ...`).
Two `kmeans` calls show the expected output. The second one shows the tie and empty-cluster rules:
```python
X = [[0, 0], [1, 0], [0, 1], [10, 10], [11, 10]]
kmeans(X, [[0, 0], [10, 10]])
# labels = [0, 0, 0, 1, 1]
# centroids = [[1/3, 1/3], [10.5, 10.0]]
# inertia = 11/6
kmeans([[1, 0]], [[0, 0], [2, 0]])
# labels = [0] (tie goes to the lowest index)
# centroids = [[1, 0], [2, 0]]
# inertia = 0.0
```
In the second call the point is at distance 1 from both centroids, so it joins centroid 0. Centroid 1 never gets a member and stays at `[2, 0]`.
```hint Pairwise distances
All pairwise squared distances come out of one broadcast over a new axis. Decide what the diagonal of the affinity should be after you exponentiate.
```
```hint Eigenvector order and sign
Check the order in which your eigensolver returns eigenvalues. An eigenvector is only defined up to sign, which is why the spec fixes one.
```
```hint Exact ties
`np.argmin` already returns the first index on a tie. Ask whether your distance formula keeps two equal distances exactly equal in floating point.
```
### Constraints & Assumptions
- `1 ≤ k ≤ n`, `gamma > 0`, and all values are finite.
- `numpy` and `scipy.linalg` are allowed. `sklearn` is not.
- Dense `n × n` matrices are acceptable here. Scaling to larger inputs is a follow-up.
### What a Strong Answer Covers
- A vectorized affinity and Laplacian that stay symmetric and handle zero-degree nodes as specified.
- An embedding built from the `k` smallest eigenvectors, with the sign rule applied before row normalization and zero rows left alone.
- A Lloyd loop that follows the tie, empty-cluster and stopping rules, then reassigns labels to the final centroids and returns inertia as a float.
- Deterministic farthest-point seeding from row 0 and relabeling by first appearance.
- The time and memory cost of the dense pipeline and which step dominates.
### Follow-up Questions
- How would you scale this beyond a few thousand points?
- How would you choose `gamma` and `k` automatically?
- Why row-normalize the embedding before k-means?
- What happens when `k` is larger than the number of distinct input points?
Overview: Implement spectral clustering in NumPy from five parts: an RBF affinity matrix, the symmetric normalized Laplacian, a sign-fixed and row-normalized spectral embedding, a deterministic Lloyd's k-means, and farthest-point seeding. It tests linear algebra, careful handling of ties and degenerate inputs, and reasoning about cost at scale.