Sub topic 4
Lloyd's algorithm step by step
What this chapter assumes
You should be comfortable with NumPy broadcasting, the Euclidean distance between two vectors, and the mean of a set of vectors. You should also know that a feature matrix X has one row per sample and one column per feature. The previous chapters defined the k-means objective, inertia. This chapter shows the procedure that tries to minimize it.
Lloyd's algorithm is the standard way to run k-means. It alternates two simple steps until nothing changes. Most k-means bugs come from misunderstanding what each step guarantees, so we go through them one at a time.
The loop at a glance
The algorithm keeps one piece of state, the k centroids. Labels are derived from the centroids at each pass.
Step 0: Starting centroids
The loop needs k initial centroids. The simplest choice is to pick k distinct rows of X at random. Using real data points guarantees every starting centroid lies inside the data. The later chapter on initialization covers better seeding. For now, treat the starting positions as an input that affects which answer you reach.
Step 1: Assignment
For every point, compute the distance to each centroid and give the point the label of the closest one. With n points, k centroids and d features, the work is one n × k table of distances.
import numpy as np
X = np.array([[1.0, 1.0], [1.5, 2.0], [8.0, 8.0], [9.0, 8.5]])
centroids = X[[0, 2]]
diffs = X[:, None, :] - centroids[None, :, :] # shape (n, k, d)
dists = np.linalg.norm(diffs, axis=2) # shape (n, k)
labels = dists.argmin(axis=1) # shape (n,)
print(labels) # [0 0 1 1]Three details matter here.
X[:, None, :]has shape(n, 1, d)andcentroids[None, :, :]has shape(1, k, d). Broadcasting expands both to(n, k, d). The distance is taken over the last axis,axis=2.argminon ties returns the lowest index. This makes the step deterministic, which matters for the stopping argument below.- Ranking by squared distance gives the same labels as ranking by distance, since squaring preserves order. Inertia uses squared distances, so the
sqrtinnormis wasted work when you only need labels. It is harmless in a teaching implementation.
Step 2: Update
Each centroid moves to the mean of the points currently assigned to it. This is the part that gives the algorithm its name, "k-means".
The mean is not an arbitrary choice. For a fixed set of points, the sum of squared distances to a candidate center c is smallest when c is the mean of the points. Setting the derivative of Σ‖x − c‖² to zero gives Σ(x − c) = 0, so c = mean(x). The update step is therefore the exact minimizer of inertia for the current labels.
The assignment step has the matching property. With centroids fixed, giving each point its nearest centroid minimizes each point's squared distance, and so minimizes the total.
Why inertia never goes up
Each step minimizes the same quantity over one set of unknowns while the other set is held fixed:
- Assignment holds centroids fixed and picks the best labels.
- Update holds labels fixed and picks the best centroids.
So neither step can raise inertia. Together with one more fact, this guarantees termination. There are only finitely many ways to partition n points into k groups (at most kⁿ). Inertia never increases, and the deterministic tie-breaking prevents cycling between equally good partitions. The algorithm therefore cannot revisit a partition and must stop.
What the argument does not give you is a global optimum. It guarantees a stable configuration that no single assignment or update step can improve. A later chapter deals with that gap.
A worked trace by hand
Take six one-dimensional points: 1, 2, 4, 9, 10, 12. Let k = 2 and start with centroids at 1 and 4 (the first and third points).
Iteration 1
- Assignment: 1 and 2 are closest to centroid 1. Points 4, 9, 10 and 12 are closest to centroid 4. Inertia with these centroids is 1 + 125 = 126.
- Update: cluster A is {1, 2}, with mean 1.5. Cluster B is {4, 9, 10, 12}, with mean 8.75. Inertia with the new centroids is 0.5 + 34.75 = 35.25.
Iteration 2
- Assignment with centroids 1.5 and 8.75: point 4 is now 2.5 away from 1.5 and 4.75 away from 8.75, so it switches to cluster A. Inertia drops to 18.9375.
- Update: cluster A is {1, 2, 4}, mean 2.333. Cluster B is {9, 10, 12}, mean 10.333. Inertia is 9.333.
Iteration 3
- Assignment with centroids 2.333 and 10.333: no point changes cluster.
- Update: the means are unchanged, so no centroid moves and the loop stops.
The inertia sequence 126, 35.25, 18.94, 9.33 never rises, as the argument predicts. Point 4 is the only point that changes cluster, and that change drives the second improvement.
The full implementation
This is Lloyd's algorithm in one function. It returns the labels, the centroids and the final inertia.
import numpy as np
from sklearn.datasets import make_blobs
def kmeans(X, k, n_iter=100, seed=0):
rng = np.random.default_rng(seed)
centroids = X[rng.choice(len(X), size=k, replace=False)]
for _ in range(n_iter):
# Assignment step: index of the nearest centroid for each point
dists = np.linalg.norm(X[:, None, :] - centroids[None, :, :], axis=2)
labels = dists.argmin(axis=1)
# Update step: mean of each cluster (keep old centroid if a cluster is empty)
new_centroids = np.array([
X[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
for j in range(k)
])
if np.allclose(new_centroids, centroids):
break
centroids = new_centroids
inertia = ((X - centroids[labels]) ** 2).sum()
return labels, centroids, inertia
X, _ = make_blobs(n_samples=300, centers=3, random_state=42)
labels, centroids, inertia = kmeans(X, k=3)
print(centroids.shape) # (3, 2)
print(np.bincount(labels))A few points about this code deserve attention.
X[rng.choice(...)]uses fancy indexing, which returns a copy. Later changes tocentroidsdo not modifyX.new_centroidsis built as a fresh array and compared against the old one. If you updatedcentroidsin place, the convergence test would compare an array with itself and always stop after the first pass.- The convergence test uses
np.allclose, not==. Means are floating-point numbers, and exact equality is a fragile test. - Because the loop can exit through
breakor by running out of iterations, the labels returned come from the last assignment step. The centroids are the last update. If the loop ended bybreak, they are consistent with each other. If it ended atn_iter, they may not be, so the returned inertia belongs to a labeling that has not been fully refreshed. Check convergence if it matters to you.
Tracing inertia after each step
The trace below reproduces the hand calculation and prints inertia after each of the two steps. It is a useful debugging tool: if inertia ever goes up, there is a bug.
import numpy as np
def lloyd_trace(X, centroids, n_iter=20):
centroids = centroids.astype(float).copy()
k = len(centroids)
for it in range(1, n_iter + 1):
dists = np.linalg.norm(X[:, None, :] - centroids[None, :, :], axis=2)
labels = dists.argmin(axis=1)
sse_assign = (dists[np.arange(len(X)), labels] ** 2).sum()
new = np.array([
X[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j]
for j in range(k)
])
sse_update = ((X - new[labels]) ** 2).sum()
print(f"iter {it}: assign {sse_assign:.2f} update {sse_update:.2f}")
if np.allclose(new, centroids):
break
centroids = new
return labels, centroids
X = np.array([[1.0], [2.0], [4.0], [9.0], [10.0], [12.0]])
labels, centroids = lloyd_trace(X, X[[0, 2]])
print(labels, centroids.ravel())The output is:
iter 1: assign 126.00 update 35.25
iter 2: assign 18.94 update 9.33
iter 3: assign 9.33 update 9.33
[0 0 0 1 1 1] [ 2.33333333 10.33333333]The assign value on each line is the inertia after that iteration's assignment, measured against the centroids it started with. The update value is the inertia after the centroids move.
Stopping rules
There are three common ways to decide the loop is finished.
| Rule | Meaning | Trade-off |
|---|---|---|
| Labels unchanged | No point switched cluster in the assignment step | Exact and cheap. The strictest sign of convergence |
| Centroid shift below a tolerance | Centroids moved less than a small threshold | Stops earlier, saving iterations. The result may differ slightly from the exact fixed point |
| Maximum iterations | A hard cap on passes | Protects against slow convergence. Gives no guarantee the loop converged |
Our implementation uses a centroid test plus an iteration cap. scikit-learn's KMeans also supports a label-based check and a tol setting on centroid movement, along with max_iter.
Empty clusters
If no point is assigned to a centroid, its mean is undefined, and X[labels == j].mean(axis=0) returns nan with a runtime warning. Empty clusters are uncommon with sensible starts, but they do happen, especially with a large k or duplicated points.
Our code keeps the old centroid, which is simple and safe. Other implementations move the empty centroid to the point farthest from its assigned centroid. That choice often lowers inertia faster, because it splits a spread-out cluster.
Cost per iteration
Each assignment step computes n × k distances in d dimensions, which is O(nkd) work. The update step is O(nd). The total cost is that of one iteration multiplied by the number of iterations, which is usually modest but has no tight general bound. The broadcast difference array has shape (n, k, d), so memory also grows with n·k·d. For large data, this array is the first thing to hurt. Production implementations compute distances in chunks or with the expansion ‖x‖² − 2x·c + ‖c‖² to avoid building it.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Wrong axis in `np.linalg.norm` | Shape error, or distances computed across the wrong dimension | Use `axis=2` on the `(n, k, d)` difference array |
| Updating `centroids` in place before comparing | Loop always exits after one pass | Build `new_centroids`, compare, then assign |
| Comparing floats with `==` | Loop runs to `n_iter` despite no real change | Use `np.allclose` or a tolerance |
| Ignoring empty clusters | `nan` centroids, then errors or garbage labels | Keep the old centroid or relocate it |
| Using unscaled features | One large-valued column decides every assignment | Standardize first (covered in the scaling chapter) |
| Treating one run as the answer | Different seeds give different inertia | Restart several times and keep the lowest inertia |
Exercises
Exercise
In the worked trace, the inertia after the iteration 1 assignment step is 126, and after the update step it is 35.25. Why can the update step never raise inertia, and which property of the mean is responsible?
Show answer
For a fixed cluster, the sum of squared distances to a center c is minimized when c is the mean of the cluster's points (setting the derivative Σ(x − c) to zero gives c = mean). The update step moves each centroid to exactly that minimizer, so the sum for each cluster, and therefore the total inertia, can only stay the same or fall.
Exercise
Suppose you change the line if np.allclose(new_centroids, centroids): break to compare centroids with itself, after executing centroids = new_centroids first. What happens, and why does the original ordering avoid the problem?
Show answer
The test would always be true, because it compares the same array with itself, so the loop would stop after the first pass whatever the data. The original ordering compares the freshly computed new_centroids with the previous centroids and only then replaces them, so the test measures actual movement.
Exercise
Run lloyd_trace on the six-point data with starting centroids at the points 1 and 12 instead (X[[0, 5]]). Predict the cluster labels it ends with, and say whether the final inertia is the same as 9.33.
Show answer
Starting from 1 and 12, points 1, 2, 4 go to the first centroid and 9, 10, 12 go to the second (4 is 3 from 1 and 8 from 12; 9 is 3 from 12 and 8 from 1). The means are 2.333 and 10.333, so the run ends with labels [0 0 0 1 1 1] and the same inertia of 9.33. Different starts reach the same answer here, but that is not guaranteed on harder data.