Sub topic 4
Lloyd's algorithm step by step
This chapter assumes you can read NumPy array code, know the Euclidean distance and the mean of a set of vectors, and understand a feature matrix with one row per sample. It also assumes you know the inertia objective from the previous chapter: the sum of squared distances from each point to its assigned centroid.
The idea in one loop
Lloyd's algorithm is the standard way to run k-means. It minimizes inertia by alternating between two simple steps:
- Assignment step. Hold the centroids fixed. Give each point the label of its nearest centroid.
- Update step. Hold the labels fixed. Move each centroid to the mean of the points assigned to it.
Each step can only keep inertia the same or lower it. The assignment step gives every point its closest centroid, which cannot increase the point's squared distance. The update step uses the mean, which is the point that minimizes the sum of squared distances to a set of points. Because inertia never rises, the loop settles down.
A hand trace
Take six one-dimensional points: 1, 2, 3, 10, 11, 12. Let k = 2 and start with centroids at 1 and 2.
| Iteration | Assignments | New centroids |
|---|---|---|
| 1 | 1 goes to the first centroid. 2, 3, 10, 11, 12 go to the second. | 1 and 7.6 |
| 2 | 1, 2, 3 go to the first. 10, 11, 12 go to the second. | 2 and 11 |
| 3 | Same assignments as iteration 2. | 2 and 11 (no change) |
In iteration 1, point 2 sits at distance 0 from the second centroid, and point 3 is at distance 1 from it and 2 from the first. The second centroid ends up at (2 + 3 + 10 + 11 + 12) / 5 = 7.6. That is a poor position, but the next assignment step corrects it. After iteration 3 nothing changes, so the algorithm stops. The final inertia is (1 + 0 + 1) + (1 + 0 + 1) = 4.
The NumPy implementation
import numpy as np
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 = np.array([[1.0], [2.0], [3.0], [10.0], [11.0], [12.0]])
labels, centroids, inertia = kmeans(X, k=2)
print(labels)
print(centroids.ravel())
print(inertia)For this data the centroids come out as 2 and 11, in either order, and the inertia is 4.0. The order depends on which points the seed picks first.
How the vectorized assignment works
X has shape (n, d) and centroids has shape (k, d). Indexing with None adds an axis, so X[:, None, :] has shape (n, 1, d) and centroids[None, :, :] has shape (1, k, d). Broadcasting subtracts them into an (n, k, d) array of difference vectors. np.linalg.norm(..., axis=2) collapses the feature axis to give an (n, k) matrix of distances. argmin(axis=1) then picks the nearest centroid for each row.
This approach is easy to read but allocates n * k * d numbers. For large data, libraries compute the distances in blocks or with matrix products instead.
Details that cause bugs
- Empty clusters. If no point is nearest to a centroid, the mean of an empty set is undefined, and NumPy would return
nanwith a warning. The code keeps the old centroid in that case. Scikit-learn instead relocates an empty cluster's centroid to a distant point. - Stopping rule.
np.allclosecompares the centroids with a small tolerance. Comparing labels between iterations also works. Without either check, you would always run alln_iteriterations. - Initial centroids. The code picks
kdistinct data points at random. Choosing the same point twice would create two identical centroids, and one of them would get an empty cluster. Sampling withreplace=Falseavoids this. - Cost per iteration. Each iteration costs about O(n · k · d) operations. The number of iterations is usually small, but there is no tight general bound.
Exercise
In the hand trace above, the second centroid moves to 7.6 in iteration 1. Starting from that state, which points change their assignment in iteration 2, and why does the algorithm still need iteration 3?
Show answer
Points 2 and 3 move from the second centroid to the first. With centroids at 1 and 7.6, point 2 is 1 away from the first and 5.6 from the second, and point 3 is 2 away from the first and 4.6 from the second. The update at the end of iteration 2 then moves the centroids to 2 and 11. Iteration 3 is needed to confirm that the assignments, and so the centroids, no longer change. The algorithm cannot know it has converged until it sees a pass with no movement.