Build a Centroid-Based Point Grouper Using Numpy
Machine LearningModel answerLast updated
Write a vectorized k-means routine that groups N points into k clusters by alternating nearest-centroid assignment with mean updates, handling empty clusters and convergence.
Group Points Into Clusters
You are given a numpy array of points and a target number of groups k. Write a function that partitions the points into k clusters using the classic iterative centroid method (Lloyd's algorithm), without using any clustering library.
Signature
import numpy as np
def kmeans(points, k, max_iters=100):
# points: numpy array of shape (N, D)
# k: number of clusters
# returns: (centroids, labels)
# centroids has shape (k, D)
# labels has shape (N,), the cluster index of each point
pass
Required behavior
- Seeding: pick
kpoints from the input at random to serve as the starting centroids. - Assignment: each point goes to the centroid with the smallest Euclidean distance.
- Update: each centroid moves to the arithmetic mean of the points currently assigned to it.
- Stopping: stop when the centroids no longer move meaningfully, or after
max_itersrounds. - Empty clusters: if a cluster ends up with no points after an assignment, give it a new centroid by choosing a random point from the dataset.
Example
points = np.array([[1, 2], [1, 4], [1, 0],
[10, 2], [10, 4], [10, 0]])
k = 2
Two groups should emerge: one centered near (1, 2) and the other near (10, 2). Which group receives label 0 may vary from run to run.
Constraints
1 <= k <= NNis between 1 and 10,000
Expected in your answer
- A working, preferably vectorized, implementation.
- An explanation of why the procedure converges and what it converges to.
- Time and space complexity.
- Discussion of the edge cases: stalled centroids, empty clusters,
k == N,k == 1, duplicate points, integer input. - Brief remarks on weaknesses (initialization sensitivity, choosing
k) and how you would address them.
Hints
Hint 1
Think of the algorithm as two alternating moves that both reduce the total squared distance from points to their assigned centroids: reassign points with centroids fixed, then recompute centroids with assignments fixed.
Hint 2
Avoid looping over points and centroids in Python. Compute an (N, k) matrix of squared distances with array operations (for example expanding ||x - c||^2 into three terms), then take argmin along axis 1. Squared distances give the same nearest centroid as true distances.
Hint 3
For the update, count points per cluster with bincount and accumulate sums with np.add.at, since plain fancy-index += drops repeated indices. Counts of zero identify empty clusters to re-seed.
Hint 4
Cast the input to float, and after the loop run one more assignment so the returned labels match the returned centroids, even if you exited because of max_iters.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
K-means alternates two steps, and each one lowers the same objective, the within-cluster sum of squared distances (inertia):
$$J = \sum_{i=1}^{N} \lVert x_i - \mu_{c_i} \rVert^2$$
- Assignment: with centroids fixed, send each point to its nearest centroid. This minimizes each point's term independently, so J cannot go up.
- Update: with assignments fixed, set each centroid to the mean of its points. The mean is the minimizer of the sum of squared distances (set the gradient to zero), so J cannot go up.
Repeat until centroids stop moving or max_iters is reached.
Why it terminates
J never increases, and there are only finitely many ways to partition N points into k groups, so the process must settle. It reaches a local optimum, not necessarily the global one; the global problem is NP-hard. That is why initialization matters.
Re-seeding an empty cluster is safe as well: an empty cluster contributes zero to J, so moving its centroid onto a data point leaves the cost unchanged, and the next assignment can only improve it.
Vectorization
Comparing squared distances picks the same nearest centroid as comparing true distances, so skip the square root. The naive broadcast points[:, None, :] - centroids[None] builds an N x k x D tensor. Instead expand
$$\lVert x - c \rVert^2 = \lVert x \rVert^2 - 2,x\cdot c + \lVert c \rVert^2$$
which needs only a matrix multiply and an (N, k) result.
Code
import numpy as np
def _assign(points, centroids):
p_sq = np.sum(points ** 2, axis=1, keepdims=True) # (N, 1)
c_sq = np.sum(centroids ** 2, axis=1) # (k,)
d2 = p_sq - 2.0 * points @ centroids.T + c_sq # (N, k)
np.maximum(d2, 0.0, out=d2) # remove tiny negatives
return np.argmin(d2, axis=1)
def kmeans(points, k, max_iters=100):
points = np.asarray(points, dtype=float)
if points.ndim == 1:
points = points[:, None]
n, d = points.shape
if not 1 <= k <= n:
raise ValueError("k must satisfy 1 <= k <= N")
rng = np.random.default_rng()
centroids = points[rng.choice(n, size=k, replace=False)].copy()
for _ in range(max_iters):
labels = _assign(points, centroids)
counts = np.bincount(labels, minlength=k)
sums = np.zeros((k, d))
np.add.at(sums, labels, points)
new_centroids = np.empty_like(centroids)
nonempty = counts > 0
new_centroids[nonempty] = sums[nonempty] / counts[nonempty, None]
empty = np.flatnonzero(~nonempty)
if empty.size:
new_centroids[empty] = points[rng.integers(0, n, size=empty.size)]
converged = np.allclose(new_centroids, centroids, rtol=0.0, atol=1e-8)
centroids = new_centroids
if converged:
break
labels = _assign(points, centroids) # keep labels consistent with centroids
return centroids, labels
On the example, the centroids converge to (1, 2) and (10, 2), with the first three points in one cluster and the last three in the other.
Complexity
With N points, k clusters, D dimensions and I iterations:
- Time: O(N·k·D) per iteration for distances plus O(N·D) for the update, so O(I·N·k·D) overall.
- Space: O(N·k) for the distance matrix and O(k·D) for centroids.
Edge cases
- Stalled centroids: test with
np.allcloseon old versus new centroids (or check that labels are unchanged) and break out early. - Empty clusters: detect with
counts == 0and re-seed with random data points. - Stale labels: if the loop ends because
max_itersran out, the labels came from the previous centroids, so do one final assignment. k == N: every point becomes its own centroid, J = 0, and it converges at once.k == 1: the single centroid is the global mean.- Integer input: cast to float, otherwise means are truncated.
- Duplicate points: two centroids may coincide;
argminties go to the lowest index, so the other becomes empty and is re-seeded. That is fine. - Floating-point error: the expansion trick can yield tiny negative squared distances. Clip at zero.
Common mistakes
- Using
sums[labels] += points, which silently loses repeated indices; usenp.add.at. - Dividing by a zero count and producing NaN centroids.
- Seeding with duplicate indices (sample without replacement).
- Allocating the full N x k x D difference tensor and running out of memory.
- Comparing floating-point centroids with
==instead of a tolerance.
Follow-ups
Initialization (k-means++). Poor seeds can put two centroids in one true cluster and none in another, giving slow or bad convergence. K-means++ picks the first centroid uniformly, then each next one with probability proportional to D(x)², the squared distance to the nearest chosen centroid. This spreads seeds out and gives an expected O(log k) approximation to optimal J. In practice, also run several restarts and keep the lowest-inertia result.
Choosing k. Inertia always falls as k grows, so it can't be minimized directly. Use the elbow method (look for where the drop flattens), the average silhouette score (cohesion versus separation), or the gap statistic.
Limitations. K-means assumes roughly spherical, similarly sized clusters, is sensitive to feature scale (standardize first) and to outliers (consider k-medoids or a Gaussian mixture model). For very large N, mini-batch k-means trades a little quality for much better speed.