Silhouette-Driven Customer Segmentation Pipeline
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: medium
Interview Round: Other
Implement `segment_customers(X, k_values, random_state=0, n_init=10)`. Standardize `X` with `StandardScaler`, fit `KMeans(n_clusters=k, n_init=n_init, random_state=random_state)` for each distinct k, and score each fit with `silhouette_score` on the standardized data. Refit the best k and return a dict.
Requirements:
- Return keys: `"k"` (int), `"silhouette"` (float, score of the chosen k), `"labels"` (int array, shape `(n_samples,)`), `"scores"` (dict k → float).
- Choose the highest silhouette, with ties broken by the smallest k.
- Renumber the final labels by first appearance: the first sample is `0`, the next new cluster is `1`, and so on.
- Raise `ValueError` for an empty `k_values`, for any k outside `2 <= k <= n_samples - 1`, or for an `X` that is not 2-D.
Example with 90 points in three tight, well-separated blobs of 30 points each:
```python
import numpy as np
rng = np.random.default_rng(0)
centers = np.array([[0.0, 0.0], [10.0, 0.0], [0.0, 10.0]])
X = np.vstack([c + 0.1 * rng.standard_normal((30, 2)) for c in centers])
res = segment_customers(X, range(2, 7))
res["k"] # 3
res["labels"][[0, 30, 60]] # array([0, 1, 2]) (first sample is always 0)
sorted(res["scores"]) # [2, 3, 4, 5, 6]
```
```hint Tie-breaking
Look for one sort key that puts the higher score first and the smaller k second, so a single comparison applies both rules.
```
```hint Valid k range
Check what `silhouette_score` requires of the number of distinct labels. The allowed range of k follows from that.
```
### Constraints & Assumptions
- `X` is numeric with shape `(n_samples, n_features)`, passed as a NumPy array or a list of lists.
- `k_values` is any iterable of integers and may repeat a value. Each distinct k is fitted once, and `scores` has one entry per distinct k.
- The same `random_state` and `n_init` are used for every fit in the sweep and for the refit.
### What a Strong Answer Covers
- Validation of the shape of `X` and of every k before any model is fitted.
- One scaling step whose output is used for both clustering and scoring.
- A deterministic choice of k that follows the tie rule.
- First-appearance relabeling and the exact return types.
- The cost of the sweep, in particular the quadratic silhouette step.
### Follow-up Questions
- How would you profile the resulting segments for a business audience?
- Silhouette is `O(n²)`. How would you scale k selection to millions of customers?
- Why refit the final model instead of reusing the sweep fit, and when could they differ?
Overview: Implement a k-means customer segmentation function that standardizes the features, sweeps a list of cluster counts and keeps the count with the highest silhouette score. It tests scikit-learn habits, input validation, deterministic tie-breaking and canonical cluster labels.