K-Means Nearest-Centroid Assigner With Outlier Cutoff
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `CentroidAssigner`, a scikit-learn transformer. `fit` runs Lloyd's k-means and stores a distance cutoff. `predict` assigns new rows to their nearest centroid, or `-1` when they lie beyond the cutoff.
The constructor is:
```python
CentroidAssigner(n_clusters=3, init=None, max_iter=100, tol=1e-6, quantile=99.0)
```
Requirements:
- Initial centroids are a copy of `init`, or the first `n_clusters` rows of `X` if `init` is `None`. A non-2-D `X`, or initial centroids of the wrong shape, raises `ValueError`.
- Stop when the largest centroid shift is at most `tol`, or after `max_iter` iterations. An empty cluster keeps its previous centroid.
- Set `cluster_centers_`, `labels_`, `inertia_` (sum of squared nearest distances), `n_iter_` and `threshold_`.
- `threshold_` is `np.percentile` of the training points' Euclidean distances to their nearest centroid, taken at `quantile`.
- `transform` returns an `(n, k)` matrix of Euclidean distances to every centroid.
- In `predict`, ties go to the lowest centroid index, and a distance strictly greater than `threshold_` maps to `-1`.
- The estimator must work with `clone` and inside a `Pipeline`.
Example:
```python
X = [[0, 0], [0, 2], [10, 0], [10, 2]]
init = [[0, 0], [10, 0]]
m = CentroidAssigner(n_clusters=2, init=init, tol=0.0).fit(X)
# cluster_centers_ = [[0, 1], [10, 1]], inertia_ = 4.0, threshold_ = 1.0
m.predict([[0, 1.5], [5, 1], [10, 1], [10, 2], [0, 3]])
# -> [0, -1, 1, 1, -1]
```
Every training point ends at distance 1 from its centroid, so the cutoff is 1.0. The row `[5, 1]` is 5 away from both centroids, takes index 0 on the tie, and is then flagged because 5 is above the cutoff. The row `[10, 2]` sits exactly on the cutoff and keeps label 1.
```hint Final assignment
When the loop stops, check whether the labels you are holding were computed against the centroids you are about to store.
```
```hint Matching units
`inertia_` is a sum of squared distances, while `threshold_` and the comparison in `predict` use plain Euclidean distances. Decide where the square root goes so training and prediction compare the same quantity.
```
### Constraints & Assumptions
- `X` is a numeric array-like of shape `(n_samples, n_features)`. When `init` is given, it should have shape `(n_clusters, n_features)`.
- Distances are Euclidean. `quantile` uses the 0 to 100 scale of `np.percentile`.
- NumPy and scikit-learn are available.
### Clarifying Questions to Ask
- Should `labels_` hold the plain nearest-centroid labels of the training rows, or should the `-1` cutoff apply to them too?
- Should `predict` and `transform` reject input whose feature count differs from the training data?
- What should `fit` do when `init` is `None` and `X` has fewer rows than `n_clusters`?
### What a Strong Answer Covers
- A Lloyd loop that follows the stated initialization, stopping rule and empty-cluster rule.
- Fitted attributes computed from the final centroids, with `inertia_` in squared distance and `threshold_` in Euclidean distance.
- The lowest-index tie rule and the strict `>` comparison in `predict`, checked against the example.
- An `__init__` that only stores its arguments, so `clone`, `get_params` and `Pipeline` work.
- Input validation, plus the time and memory cost of the distance computation.
### Follow-up Questions
- How would you choose a per-cluster threshold instead of a global one?
- How would you scale `predict` to millions of rows?
- How should the threshold be monitored after deployment?
Overview: Implement a scikit-learn style transformer that fits k-means with Lloyd's algorithm, stores a percentile distance cutoff, and labels far-away rows as outliers. It tests the k-means update loop, tie-breaking, fitted-attribute conventions, and compatibility with clone and Pipeline.