K-Means++ Centroid Initialization
Role: Machine Learning Engineer
Category: Machine Learning
Difficulty: easy
Interview Round: Other
Implement `kmeans_plusplus_init(X, k, seed)` that selects `k` initial centroids from the rows of `X` (shape `(n, d)`) using k-means++ seeding. Return a tuple `(centers, indices)`: `centers` is a `(k, d)` float array equal to `X[indices]`, and `indices` is a length-`k` int array in selection order.
The random draws are pinned to this order:
1. Create `rng = np.random.default_rng(seed)`. The first index is `rng.integers(n)`.
2. Each next index is `rng.choice(n, p=d2 / d2.sum())`, where `d2[i]` is the squared Euclidean distance from row `i` to its nearest chosen centroid.
3. If `d2.sum() <= 0`, fall back to `rng.integers(n)`.
For example:
```python
X = [[0.0, 0.0], [3.0, 4.0]]
centers, indices = kmeans_plusplus_init(X, 2, seed=0)
# indices is a permutation of [0, 1]: the second draw puts probability 1 on the point not yet chosen
```
```hint Updating distances
When one centroid is added, each point's distance to its nearest centroid can only stay the same or shrink. Use that to avoid recomputing distances to every earlier centroid.
```
### Constraints & Assumptions
- `1 <= k <= n`, otherwise raise `ValueError`.
- Draws must follow the exact order above, because indices are compared exactly against a reference.
- `X` may be a list or an array: convert it with `np.asarray(X, dtype=float)`.
### What a Strong Answer Covers
- The exact sequence of generator calls, including the fallback when every remaining distance is zero.
- Keeping each point's squared distance to its nearest centroid up to date with an elementwise minimum.
- Why points already chosen, and exact duplicates of them, get zero probability.
- Input conversion, the range check on `k` and the return types.
- Time and space complexity in terms of $n$, $k$ and $d$.
### Follow-up Questions
- Why sample proportional to squared distance instead of plain distance?
- What does greedy k-means++ (as in scikit-learn) add?
- How would you seed k-means on a dataset where $k$ sequential passes over the data are too slow?
Overview: Implement k-means++ seeding that picks initial centroids from the rows of a data matrix, sampling each new one by squared distance to the nearest chosen centroid under a pinned random draw order. It tests incremental distance updates, reproducible NumPy sampling and edge cases such as duplicate points.