Sub topic 3
What k-means minimizes: inertia
This chapter assumes you know basic NumPy indexing, Euclidean distance, and the idea of a feature matrix with samples as rows. The previous chapter covered distance and centroids. Here you will see the single number that k-means tries to make small, and why both steps of the algorithm lower it.
The objective in one formula
k-means splits n points into k clusters. Each cluster C_j has a centroid mu_j. The objective is the sum of squared distances from every point to the centroid of its own cluster:
inertia = sum over j of ( sum over x in C_j of ||x - mu_j||^2 )This quantity goes by several names: inertia, within-cluster sum of squares (WCSS), and sum of squared errors (SSE). scikit-learn calls it inertia_. A low value means points sit close to their centroids. A high value means the clusters are spread out.
k-means searches over two things at once: how points are assigned to clusters, and where the centroids are. Inertia scores any such pair.
Computing inertia by hand
With NumPy, centroids[labels] builds an array that gives each point its own centroid. Subtract, square, and sum.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=200, centers=3, random_state=0)
def inertia(X, labels, centroids):
return ((X - centroids[labels]) ** 2).sum()
km = KMeans(n_clusters=3, n_init=10, random_state=0).fit(X)
print(inertia(X, km.labels_, km.cluster_centers_))
print(km.inertia_)The two printed values agree up to floating-point rounding. Note that the formula uses the squared distance, not the distance itself. Squaring penalizes far-away points more heavily, so one distant point costs more than several nearby ones.
Why the mean is the right centroid
Suppose a cluster holds three one-dimensional points: 1, 2, and 6. The table shows the squared-error cost for three candidate centers.
| Center | Cost calculation | Total |
|---|---|---|
| 2 | 1 + 0 + 16 | 17 |
| 3 (the mean) | 4 + 1 + 9 | 14 |
| 4 | 9 + 4 + 4 | 17 |
The mean gives the smallest total. This holds in general. For a fixed set of points, the center that minimizes the sum of squared distances is their mean. That is the reason the update step moves each centroid to the mean of its points. The rule is derived from the objective, not chosen by convention.
The same logic explains the assignment step. For fixed centroids, each point adds the least to the total when it joins the cluster with the nearest centroid.
How each step affects inertia
Lloyd's algorithm, which the next chapter covers in detail, alternates two moves. Each move either lowers inertia or leaves it unchanged.
- Assignment step. Centroids stay fixed. Moving a point to a closer centroid shrinks that point's term. No point moves to a farther one.
- Update step. Assignments stay fixed. The mean minimizes each cluster's sum, so replacing a centroid with the mean cannot raise it.
Inertia is bounded below by zero and can only go down, so the algorithm must stop. The chapter on convergence returns to this point and to what "stop" means.
Reading inertia correctly
Inertia is useful, but it has traps that cause common errors.
- It always falls as
krises. Withk = n, every point is its own centroid and inertia is zero. You cannot pickkby choosing the smallest inertia. Later chapters handle this with the elbow method and the silhouette score. - It is not scale-free. Multiplying every feature by 10 multiplies inertia by 100. Compare inertia only between runs on the same data with the same scaling.
- It depends on units. A feature measured in meters instead of millimeters changes which features dominate the sum. The scaling chapter covers the fix.
- It assumes round clusters. Inertia measures distance to a single center. It rewards compact, roughly spherical groups and says little about elongated or ring-shaped ones.
The objective is not convex
Inertia is a function of both the assignments and the centroids, and it has many local minima. Lloyd's algorithm reliably reaches one of them, but not necessarily the lowest. Two runs from different starting centroids can end with different inertia values on the same data. That is why scikit-learn runs several starts (n_init) and keeps the run with the lowest inertia_. Initialization and restarts get their own chapter.
Summary of the objective
- Inertia is the total squared distance from each point to its assigned centroid.
- The mean minimizes squared distance, so the update step uses it.
- The nearest centroid minimizes each point's term, so the assignment step uses it.
- Each step lowers or keeps inertia, so the algorithm stops, but possibly at a local minimum.
Exercise
A cluster contains the one-dimensional points 2, 4, and 9. What is its centroid, and what is its contribution to inertia?
Show answer
The centroid is the mean, (2 + 4 + 9) / 3 = 5. The squared distances are (2-5)^2 = 9, (4-5)^2 = 1, and (9-5)^2 = 16. The cluster contributes 9 + 1 + 16 = 26 to inertia.
Exercise
You fit KMeans with k=3 and k=6 on the same scaled data. The k=6 model has lower inertia. Can you conclude that k=6 is the better choice?
Show answer
No. Inertia never increases as k grows, so k=6 would usually score lower even if three clusters describe the data well. You need a criterion that accounts for this, such as the elbow method or the silhouette score.