Ward Linkage, Cophenetic Correlation and Distance Cut
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement three helpers on a feature matrix `X` of shape `(n, d)` using `scipy.cluster.hierarchy`. `ward_linkage(X)` returns the Ward linkage matrix, `cophenetic_correlation(X, Z)` scores how faithfully `Z` preserves pairwise distances, and `cut_at_distance(Z, threshold)` returns flat cluster labels.
Requirements:
- `ward_linkage`: Euclidean Ward linkage, shape `(n-1, 4)`, identical to `linkage(X, method="ward")`.
- `cophenetic_correlation`: Pearson correlation between cophenetic distances and Euclidean `pdist(X)`, returned as a Python `float`.
- `cut_at_distance`: cut with `fcluster` using `criterion="distance"` (merges at height ≤ `threshold` are joined).
- Relabel clusters to `0..k-1` in order of first appearance, returned as an int `ndarray` of length `n`.
Example:
```python
X = [[0.0], [1.0], [10.0], [11.0]]
Z = ward_linkage(X)
# Z[2] == [4, 5, 10*sqrt(2), 4]
cut_at_distance(Z, 0.5) # [0, 1, 2, 3]
cut_at_distance(Z, 1.0) # [0, 0, 1, 1]
cut_at_distance(Z, 20.0) # [0, 0, 0, 0]
```
```hint Relabelling the cut
`fcluster` numbers clusters from 1, and that numbering does not follow sample order. Look for a NumPy call that tells you the first index at which each raw label appears.
```
### Constraints & Assumptions
- `X` is numeric with shape `(n, d)` and `n >= 2`. The example passes a list of lists, so convert the input to a float array.
- All distances are Euclidean. SciPy defines Ward linkage correctly only for Euclidean distances.
- `threshold` is a non-negative float on the same scale as the merge heights in column 2 of `Z`.
### What a Strong Answer Covers
- Builds the tree with `linkage(..., method="ward")` on Euclidean distances and explains what the four columns of `Z` hold.
- Compares the cophenetic distances with `pdist(X)` and returns only the coefficient from `cophenet`, as a plain `float`.
- Handles the inclusive cut, where a threshold equal to a merge height joins those points, and checks it on the example at `1.0`.
- Relabels the raw `fcluster` ids to `0..k-1` by first appearance without changing which points share a cluster.
- States the quadratic time and memory cost that comes from the pairwise distance matrix.
### Follow-up Questions
- How would you cut the tree into exactly `k` clusters instead of at a distance?
- Why is the cophenetic correlation usually lower for Ward linkage than for average linkage?
- How does this scale for large `n`, and what would you do once the distance matrix no longer fits in memory?
Overview: Implement Ward linkage, cophenetic correlation and a distance-based cut with scipy.cluster.hierarchy on a feature matrix. It tests reading a linkage matrix, the threshold rule of fcluster, deterministic relabelling of cluster ids and the quadratic cost of hierarchical clustering.