Sub topic 5
Why it stops, and why the answer is only a local minimum
This chapter assumes you can read the NumPy version of Lloyd's algorithm from the previous chapter. It also assumes you know the inertia formula, which is the sum of squared distances from each point to its assigned centroid. Here you will see why that loop always terminates, what it terminates at, and why that is not necessarily the best clustering.
The two steps never make things worse
Write the inertia as a function of two things: the assignment of points to clusters, and the centroid positions. Lloyd's algorithm alternates between improving one while holding the other fixed.
- Assignment step. The centroids are fixed. Each point moves to its nearest centroid. Each point's squared distance can only stay the same or shrink, so the inertia cannot go up.
- Update step. The assignments are fixed. Each centroid moves to the mean of its points. For a fixed set of points, the mean is the single location that minimizes the sum of squared distances to those points. Moving a centroid there cannot increase the inertia.
The second claim is the property that ties k-means to the squared Euclidean distance. For a cluster with points x_i and any candidate center c, the sum of squared distances to c equals the sum of squared distances to the mean, plus n times the squared distance between c and the mean. The extra term is zero only when c is the mean.
Put together, the inertia is a non-increasing sequence:
Why the loop must terminate
A non-increasing sequence is not enough on its own, because it could creep downward forever. Two more facts close the gap.
- For n points and k clusters there are at most k^n ways to assign points to clusters. That number is huge but finite.
- Once the assignment is fixed, the centroids are fully determined, because each is the mean of its cluster. So the inertia after an update step depends only on the partition.
Now suppose the algorithm revisits a partition it has seen before. Between the two visits the inertia was non-increasing, and it is the same at both ends, so it was constant throughout. The algorithm only moves to a different partition when an assignment step strictly lowers the inertia. This holds provided ties are broken consistently, for example by always picking the lowest centroid index. So a constant inertia means the partition did not change, and the algorithm has stopped. Therefore no partition is ever visited twice, and the algorithm must stop after finitely many iterations.
The finite bound is far too loose to be practical. In practice k-means converges in tens of iterations on well-behaved data. Worst-case constructions exist that need super-polynomially many iterations, but you will rarely meet them.
Watching it happen
The following function is Lloyd's algorithm instrumented to record the inertia after each half-step. It checks the monotonic property directly.
import numpy as np
from sklearn.datasets import make_blobs
def inertia_of(X, centroids, labels):
return ((X - centroids[labels]) ** 2).sum()
def kmeans_trace(X, k, n_iter=100, seed=0):
rng = np.random.default_rng(seed)
centroids = X[rng.choice(len(X), size=k, replace=False)]
labels = None
history = [] # one (after_assign, after_update) pair per iteration
for _ in range(n_iter):
dists = np.linalg.norm(X[:, None, :] - centroids[None, :, :], axis=2)
new_labels = dists.argmin(axis=1)
after_assign = inertia_of(X, centroids, new_labels)
centroids = np.array([
X[new_labels == j].mean(axis=0) if np.any(new_labels == j) else centroids[j]
for j in range(k)
])
after_update = inertia_of(X, centroids, new_labels)
history.append((after_assign, after_update))
if labels is not None and np.array_equal(new_labels, labels):
break
labels = new_labels
return new_labels, centroids, history
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=1.5, random_state=1)
labels, centroids, history = kmeans_trace(X, k=4)
previous = np.inf
for i, (a, u) in enumerate(history, start=1):
assert a <= previous + 1e-9, "assignment step increased inertia"
assert u <= a + 1e-9, "update step increased inertia"
previous = u
print(f"iter {i:2d} after assign={a:9.2f} after update={u:9.2f}")
print("iterations used:", len(history))The assertions pass for any data and any seed, because they restate the argument above. The small tolerance only absorbs floating-point rounding. The exact numbers depend on the data and on which points were picked as starting centroids. The last iteration shows the same inertia after assign and after update, because nothing moved.
What "stopped" means in practice
There are several reasonable ways to decide the loop is done. Libraries differ in which they use.
| Criterion | Meaning | Trade-off |
|---|---|---|
| Labels unchanged | No point switched clusters in the last assignment step. | Exact and safe. It is the true fixed point. |
| Centroids unchanged (`np.allclose`) | Centroids moved less than a small tolerance. | Cheap, but depends on the tolerance and the data scale. |
| Inertia change below `tol` | Relative improvement is negligible. | Stops early on slow tails. The result may sit slightly short of the fixed point. |
| `max_iter` reached | A hard cap on iterations. | A safety net. Hitting it means the result may not be converged. |
scikit-learn declares strict convergence when the labels do not change between two iterations. It also stops when the squared shift of the centroids falls below tol, which is scaled by the average variance of the features. Otherwise it stops at max_iter (default 300). After fitting, compare n_iter_ with max_iter. If they are equal, the cap ended the run, and you should raise max_iter or investigate the data.
A fixed point is not the best clustering
Termination guarantees a stationary point of the inertia. It does not guarantee the global minimum. The inertia, viewed as a function of the partition, has many valleys, and Lloyd's algorithm slides downhill into whichever valley the starting centroids sit in. Neither step can climb out, because each step only ever accepts changes that lower or keep the inertia.
A one-dimensional example makes this exact. Take six points in three obvious pairs: 0 and 1, 10 and 11, 20 and 21. The best 3-clustering is one pair per cluster, with inertia 3. Start instead with centroids at 0, 1 and 10.
import numpy as np
from sklearn.cluster import KMeans
X = np.array([[0.0], [1.0], [10.0], [11.0], [20.0], [21.0]])
starts = {
"bad start (0, 1, 10)": np.array([[0.0], [1.0], [10.0]]),
"good start (0, 10, 20)": np.array([[0.0], [10.0], [20.0]]),
}
for name, init in starts.items():
km = KMeans(n_clusters=3, init=init, n_init=1, algorithm="lloyd").fit(X)
centers = np.sort(km.cluster_centers_.ravel())
print(f"{name}: inertia={km.inertia_:.1f} centers={centers} iterations={km.n_iter_}")The bad start produces centroids at 0, 1 and 15.5 with inertia 101. Here is why it stops there. The point at 0 belongs to the first centroid, and the point at 1 belongs to the second. The remaining four points, 10, 11, 20 and 21, are all closer to the third centroid at 15.5 than to the one at 1. The update step leaves every centroid where it is, so nothing changes. The algorithm has converged, and its answer is about 34 times worse than the optimum. The good start reaches inertia 3.
How much it matters on real data
On clean, well-separated blobs, most starts reach the same answer or an equivalent one. The trouble appears when the number of clusters is large, when clusters are close together, or when the starting points land two to a cluster while another cluster gets none. The following experiment runs plain random initialization 20 times, with a single start each, and collects the final inertia.
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=600, centers=6, cluster_std=1.2, random_state=3)
results = []
for seed in range(20):
km = KMeans(
n_clusters=6, init="random", n_init=1, algorithm="lloyd", random_state=seed
).fit(X)
results.append((round(km.inertia_, 1), km.n_iter_))
distinct = sorted({inertia for inertia, _ in results})
print("distinct final inertias:", len(distinct))
print("best:", distinct[0], " worst:", distinct[-1])
print("iterations per run:", sorted(n for _, n in results))Typically you see several distinct inertia values, so some runs end in worse valleys. The iteration counts are all small and all below max_iter, so every run converged. All of the final answers are fixed points, but they are not equally good. The next chapter covers the standard remedies, smarter seeding with k-means++ and keeping the best of several restarts.
Edge cases at the fixed point
- Empty clusters. If no point is closest to a centroid, the mean of an empty set is undefined. The NumPy version in this tutorial keeps the old centroid, which cannot raise the inertia. Libraries may instead relocate the empty centroid to a far-away point. That is also a valid improvement, because it lowers the inertia and guarantees k nonempty clusters.
- Ties. A point equidistant from two centroids must be assigned to one of them.
argminalways picks the lowest index, which makes the rule deterministic. Without a fixed rule, labels could flip back and forth even though the inertia is constant, and the "labels unchanged" test might never fire. - Duplicate points. If you ask for more clusters than there are distinct points, some clusters must be empty or share a location. Inertia can reach zero, and extra clusters add no information.
- Floating-point noise. Comparing centroids with exact equality can fail because of rounding. Use a tolerance such as
np.allclose, or compare integer labels, which are exact. - Different fixed points from reordered data. Shuffling the rows can change which points the initialization picks, and so can change which local minimum you reach. Fix a random seed when you need reproducibility.
Summary of the reasoning
- Each assignment step and each update step is non-increasing in inertia.
- The inertia after an update depends only on the partition, and there are finitely many partitions.
- Consistent tie-breaking prevents cycling, so the algorithm halts.
- The halting point is a stationary point. It is a local minimum with respect to both steps, and it need not be the global minimum.
- Where the loop ends depends on where it starts.
Exercise
In the six-point example, the bad start leaves centroids at 0, 1 and 15.5 with inertia 101. Verify the inertia by hand, and explain why a single extra Lloyd iteration cannot improve it.
Show answer
The point 0 sits on its centroid and the point 1 sits on its centroid, so both contribute 0. The other four points belong to the centroid at 15.5. Their squared distances are (10-15.5)^2 = 30.25, (11-15.5)^2 = 20.25, (20-15.5)^2 = 20.25 and (21-15.5)^2 = 30.25. The sum is 101. In the assignment step, each of those four points is closer to 15.5 than to 1 (for example 5.5 versus 9 for the point at 10), and the points at 0 and 1 stay with their own centroids. So no label changes. In the update step, each centroid is already the mean of its points: 0, 1, and (10+11+20+21)/4 = 15.5. Nothing moves, so the state is a fixed point.
Exercise
Suppose a run ends with niter equal to max_iter. Can you conclude the algorithm failed, and what should you do?
Show answer
No, but you cannot conclude it converged either. The cap stopped the loop, so the labels may still have been changing. The inertia is still non-increasing, so the result is usable but may not be a fixed point. Raise max_iter and refit, or check whether a larger tol would be acceptable. If the run still hits the cap, look at the data for problems such as unscaled features or very many clusters.
Exercise
Why does the proof of termination rely on the update step using the mean, and what would break if you used the median instead while still measuring squared distances?
Show answer
The mean is the exact minimizer of the sum of squared distances for a fixed set of points. That is what guarantees the update step cannot raise the inertia. The median minimizes the sum of absolute distances, not squared ones. With squared distances, moving a centroid to the median could increase the inertia, so the non-increasing argument fails and convergence is no longer guaranteed. A median-based method such as k-medians pairs it with absolute (L1) distance, which restores the argument.