Sub topic 5
Why it stops, and why the answer is only a local minimum
This chapter assumes you know the assign and update steps of Lloyd's algorithm from the previous chapter. It also assumes you know that inertia is the sum of squared distances from each point to its assigned centroid. Here you will see why the loop always ends, and why ending does not mean you found the best clustering.
Inertia never goes up
Write the objective as J(labels, centroids), the sum over all points of the squared distance to the centroid of the point's cluster. Each step of Lloyd's algorithm can only lower J or leave it unchanged.
- Assignment step. The centroids are held fixed. Each point moves to its nearest centroid. A point's squared distance to its new centroid is at most its distance to the old one, so J cannot rise.
- Update step. The labels are held fixed. For one cluster, the point that minimizes the sum of squared distances to its members is their mean. Moving a centroid to the mean therefore cannot raise J.
So J is non-increasing across iterations. It is also bounded below by 0.
Why the loop must stop
There are only k^n ways to assign n points to k clusters. This number is huge but finite. Once the labels are fixed, the update step produces exactly one set of centroids. And J never rises, so the algorithm cannot return to a worse labeling. A labeling that repeats must give the same J. That means no further change is possible, and the loop reaches a fixed point where the assignments stop changing.
In practice, the number of iterations is usually small, often tens. The worst case can be much larger, but you rarely meet it on real data.
Watching inertia fall
The code below runs Lloyd's algorithm by hand and records inertia after each pass. You can confirm that it never increases.
import numpy as np
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=1.5, random_state=3)
rng = np.random.default_rng(1)
k = 4
centroids = X[rng.choice(len(X), size=k, replace=False)]
history = []
for step in range(50):
dists = np.linalg.norm(X[:, None, :] - centroids[None, :, :], axis=2)
labels = dists.argmin(axis=1)
history.append(((X - centroids[labels]) ** 2).sum())
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
for i, value in enumerate(history):
print(f"pass {i}: inertia = {value:.2f}")
assert all(a >= b - 1e-9 for a, b in zip(history, history[1:]))
print("inertia never increased")The assert uses a tiny tolerance because floating-point sums can differ in the last digits.
Stopping is not the same as being optimal
The argument above proves that the algorithm reaches a point where neither step can improve J. This is a local minimum. It does not prove that no other clustering has a lower J. The global minimum is the best of all k^n labelings, and finding it is NP-hard in general.
A local minimum can be bad. Suppose there are three true groups, and the starting centroids put two in one group and one between the other two. Assignment and update steps then both look fine locally. No single step moves a centroid across the gap to where it is needed. The algorithm stops with one real group split in two and two real groups merged.
Common errors
- Treating the result as the answer. The labels from one run depend on the starting centroids. Two runs with different seeds can disagree, and both are valid fixed points.
- Comparing runs by labels. Cluster numbers are arbitrary. Cluster 0 in one run may match cluster 2 in another. Compare inertia, or use a permutation-invariant score such as the adjusted Rand index.
- Ignoring empty clusters. If a cluster loses all its points, its mean is undefined. The code keeps the old centroid, which is a simple fix. Libraries use other fixes, such as moving the centroid to the point farthest from its current centroid.
- Setting
toltoo loosely. scikit-learn stops when centroid movement is below a tolerance, not only when labels stop changing. A loose tolerance can stop earlier than a strict fixed point.
What to do about it
Because the result depends on the start, the usual remedy is to run the algorithm several times from different starting points and keep the run with the lowest inertia. The next chapter covers how to choose those starting points.
Exercise
Lloyd's algorithm has stopped because no label changed in the last pass. A colleague says this proves the clustering has the lowest possible inertia for this k. Is that correct? Explain using both parts of the argument: why it stopped, and what that guarantees.
Show answer
No. The algorithm stops because inertia never increases and the number of possible labelings is finite, so it reaches a state where neither the assignment step nor the update step can improve it. That is a local minimum. It only shows that no single assignment or update step helps. A different labeling elsewhere in the space may have lower inertia, which is why the result depends on the starting centroids and why you run several restarts and keep the lowest inertia.
Exercise
You run k-means twice on the same data with different seeds. The first run has inertia 812.4 and the second has inertia 1,020.7. Cluster 0 in the first run contains almost the same points as cluster 2 in the second. Which run would you keep, and is the label mismatch a problem?
Show answer
Keep the first run, since it has the lower inertia for the same k and data. The label mismatch is not a problem. Cluster numbers are arbitrary names assigned by the starting order of the centroids, so matching clusters can carry different numbers across runs.