Run k-means to convergence and re-seed empty clusters
Why it matters k-means is used for customer segmentation, vector quantisation and IVF indexes in vector databases, and the empty-cluster rule is a common production bug.
A full k-means loop repeats assign and update until the centers stop moving. Real implementations also need a rule for a cluster that loses all its points.
Write kmeans_fit(X, init_centers, max_iter=100). Each iteration: assign every point to its nearest center by squared Euclidean distance (lowest center index on ties), then recompute each center as the mean of its points. If a cluster is empty, move its center onto a point that is far from its own center: sort points by their squared distance to their assigned center, largest first (stable), and give the empty clusters (in index order) the points in that order. Stop when the new centers equal the old ones exactly or after max_iter iterations. Return (centers, labels, n_iter, inertia) where labels and inertia (sum of squared distances to the nearest center) are computed from the final centers and n_iter counts the iterations run.
def kmeans_fit(X, init_centers, max_iter=100)Example
X [[0, 0], [0, 1], [5, 5], [6, 5]], init_centers [[0, 0], [5, 5]] gives centers [[0, 0.5], [5.5, 5]], labels [0, 0, 1, 1], n_iter 2 and inertia 1.0.
Understand the idea
k-means alternates two easy steps. Assign: each point joins the nearest center. Update: each center moves to the average of its points. Each step can only lower the total squared distance (the inertia), so the loop settles down, usually in a few iterations.
Worked example: points (0, 0), (0, 1), (5, 5), (6, 5) with centers (0, 0) and (5, 5). The first two points join center 0 and the last two join center 1. The new centers are (0, 0.5) and (5.5, 5). Repeating gives the same assignment and the same centers, so we stop. Inertia = 0.25 + 0.25 + 0.25 + 0.25 = 1.
Empty clusters happen when a center starts far from every point. A good fix is to move it to the point that is currently served worst, the one farthest from its own center, so the dead center becomes useful.
Rule: repeat { labels = argmin_k ||x - c_k||^2; c_k = mean of its points } until the centers stop changing.
Vector databases use k-means to build IVF indexes, and marketers use it to segment customers.
Shapes and data flow
X (n, d), C (K, d) -> d2 (n, K) -> labels (n,)