How Lloyd’s algorithm runs k-means

Short answer: Lloyd’s algorithm is the standard k-means iteration. Assign every point to the nearest of k centers, then replace each center by the mean of the points assigned to it. Repeat until the assignment stops changing or a step budget runs out. Each step decreases the sum of squared distances, so the loop reaches a local minimum. It does not reach the global minimum. k-means++ chooses the first centers far apart and is the usual initialization.


What the problem actually asks

The k-means objective partitions points into k clusters and places each center at the mean of its cluster, minimizing the within-cluster sum of squares. The joint problem is NP-hard. Lloyd’s algorithm alternates the two easy pieces: the best assignment given the centers is the nearest center, and the best center given the assignment is the mean. Either piece alone is optimal for the other piece held fixed. The pair of pieces is only locally optimal.

A bad initialization puts two centers in one clump and none in another. The iteration cannot move a center across an empty gap if no point is assigned to it. Empty clusters need a documented restart rule.


What the algorithm guarantees

Each full iteration costs O(n·k·d) distance computations in d dimensions and does not increase the objective. The number of iterations until exact convergence can be exponential in contrived cases and is small on typical data. The result depends on the start. k-means++ samples the next center with probability proportional to the squared distance to the nearest chosen center and has a proven approximation factor in expectation relative to the optimal objective. It is still not an exact solver.

The objective uses squared Euclidean distance. Substituting cosine distance or a median, which is k-medians, changes the update. The mean is the minimizer of squared error. The median is the minimizer of absolute error. Using a mean with an absolute-error objective, or a median with squared error, optimizes the wrong center.


The working steps

  1. Initialize k distinct centers, preferably with k-means++: choose the first uniformly, and each later center with probability proportional to its squared distance to the closest already chosen center.
  2. Assign each point to the nearest center under Euclidean distance.
  3. Replace each center by the coordinate-wise mean of its assigned points. If a center received no points, reseed it, for example at a random point, or the run is stuck.
  4. Repeat the assignment and the update until the assignment is unchanged or the objective drop is negligible.
  5. Run several random restarts if k-means++ is not used, and keep the lowest objective. The iteration itself does not escape a bad basin.

The descent is local. A lower objective from a different start is possible and common. The algorithm is not DBSCAN, which finds dense regions without a preset k and without using means. It is not a Gaussian mixture, which uses soft assignments and the EM algorithm. Squared Euclidean k-means has a spherical-cluster bias.


Approaches that look simpler and fail

Approach Why it fails when the center is updated with a median under squared error
Replace the center by a coordinate-wise median while scoring squared error The mean is the unique minimizer of the sum of squares. A median optimizes a different objective, and the alternation may not descend on the k-means score.
Promise the global minimum after one Lloyd run The objective decreases to a local minimum that depends on initialization. k-means++ improves the start and does not exhaust the search.
Leave an empty cluster in place Its center never receives a gradient from any point. The effective number of clusters has dropped. Reseed or accept the smaller k explicitly.
Use k-means on a distance that is not squared Euclidean and keep the mean update The mean step is derived from squared error. Another distance needs the center that actually minimizes that distance.

Density-connected clusters without a preset k are DBSCAN. Soft Gaussian clusters are expectation-maximization. Lloyd’s algorithm is hard k-means with a mean update.


A working example

This Python fragment alternates assignment and the mean. Points 0, 1 and 10, 11 with k = 2 move to centers near 0.5 and 10.5. It prints those centers rounded, 0.5 10.5.

points = [0.0, 1.0, 10.0, 11.0]
centers = [0.0, 10.0]
for _ in range(5):
    groups = [[] for _ in centers]
    for p in points:
        groups[min(range(2), key=lambda i: abs(p - centers[i]))].append(p)
    centers = [sum(g) / len(g) for g in groups]
assert abs(centers[0] - 0.5) < 1e-9 and abs(centers[1] - 10.5) < 1e-9
print(f"{centers[0]:.1f}", f"{centers[1]:.1f}")

Where it is used

K-means, Lloyd’s algorithm, is the clustering in scikit-learn and the color quantization that builds a palette. Customer segmentation uses the same alternation of assign and average. DBSCAN is the density clusterer that does not ask for k and can leave noise out.


When you can drop this algorithm

Drop a single random initialization when the objective will be treated as the truth. Use k-means++ or several restarts and keep the best objective. Remember the result is local.


Why this stays published

We publish this so a search for k-means returns Lloyd’s alternation, the local minimum it reaches, and the role of k-means++. Lloyd’s algorithm alternates nearest-center assignment and mean updates, which descends the k-means objective to a local minimum and does not promise the global one.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *