Implement k-means from scratch with NumPy, then adapt it to data that arrives as a stream you cannot store.
Answer
Model answer, written in a candidate's voice
In short
- k-means++: seed first centroid randomly, then pick remaining centroids with probability proportional to squared distance to nearest chosen centroid.
- Vectorised distances: compute all pairwise squared distances with broadcasting or the ||x||^2 + ||c||^2 - 2x·c identity, not Python loops.
- Iterate assignment (argmin cluster) and update (cluster means), stopping when max centroid shift or assignment change is below tolerance.
- Handle empty clusters by reinitialising them from a high-distance point or a random sample, never dividing by zero.
- Streaming: keep only centroids and per-cluster counts; assign each point/batch to nearest centroid and update c_j <- c_j + (x - c_j)/n_j.
- For drift, decay counts/centroids (e.g. n_j <- rho*n_j before increment) so recent data dominates while old clusters are not frozen.
In full
I’d start with a clean batch NumPy implementation: initialise with k-means++ by choosing the first centroid at random and then sampling each remaining centroid with probability proportional to its squared distance to the nearest already-chosen centroid. Distances are computed vectorised, either by broadcasting X against centroids or by using ||x||^2 + ||c||^2 - 2x·c, then assignment is argmin over clusters and the update is the mean of points in each cluster. I’d stop when the largest centroid shift or the fraction of changed assignments falls below a tolerance, and I’d guard empty clusters by reinitialising them from a far-from-centroid point or a random sample rather than dividing by zero. For streaming, I’d keep only centroids and per-cluster counts, assign each incoming point or mini-batch to the nearest centroid, and update c_j <- c_j + (x - c_j)/n_j with n_j incremented per cluster. To handle drift, I’d decay the effective counts before the increment, e.g. n_j <- rho*n_j + 1, so recent observations dominate while the model does not forget too abruptly. I’d validate the batch version against a reference implementation and the streaming version by checking that centroids track a known drifting distribution without storing the raw stream.
What a strong answer covers
- k-means++ initialisation.
- Vectorised distance computation.
- Assignment and update steps, with a convergence check.
- Handling empty clusters.
- Streaming: online or mini-batch updates with per-cluster counts (step size 1/n) and decay for drift.
Common mistakes
- Python loops over points.
- No empty-cluster handling.