How does Lloyd's algorithm for k-means work step-by-step?
Last updated
Lloyd's algorithm alternates between assigning points to their nearest centroid and recomputing centroids as cluster means, repeating until assignments stop changing. Each step lowers the within-cluster sum of squares.
Initialize: Choose k initial centroids (random points or, better, k-means++).
Assignment step:
Assign each point to the centroid with the smallest squared Euclidean distance (a Voronoi partition).
Optimal for fixed centroids.
Update step:
Set each centroid to the mean of its assigned points.
Optimal for fixed assignments. Handle empty clusters (e.g. reseed with the farthest point).
Repeat until convergence: Stop when assignments don't change, centroid movement < tolerance, or max iterations reached.
Properties:
Cost per iteration: O(n·k·d); usually converges in few iterations.
Guaranteed to converge (finite partitions, monotone objective) but only to a local minimum, so results depend on initialization.
[lang:python]
import numpy as np
def lloyd(X, C, iters=100):
for _ in range(iters):
labels = ((X[:, None] - C[None]) ** 2).sum(-1).argmin(1) # assign
newC = np.array([X[labels == j].mean(0) for j in range(len(C))]) # update
if np.allclose(newC, C):
break
C = newC
return labels, C