Sub topic 3
What k-means minimizes: inertia
This chapter assumes you can read basic NumPy, know the mean and Euclidean distance of vectors, and treat a dataset as a matrix with samples in rows and features in columns. Earlier chapters covered what clustering is and how distance and centroids work. Here you will learn the single number that k-means tries to make small, why that number takes the form it does, and how to compute and interpret it.
The objective in one line
k-means has an explicit objective function. Given k clusters, it picks an assignment of points to clusters and a centroid for each cluster so that the total squared distance from each point to its own centroid is as small as possible. That total is called inertia. Other names for it are the within-cluster sum of squares (WCSS) and the sum of squared errors (SSE).
With cluster C_j holding the points assigned to centroid mu_j, the objective is:
J = sum over j = 1..k of ( sum over x in C_j of ||x - mu_j||^2 )
Read it from the inside out:
x - mu_jis the vector from a point to its centroid.||...||^2is that vector's squared length, so each feature's difference is squared and then summed.- The inner sum adds this up over every point in one cluster.
- The outer sum adds up the clusters.
Inertia is zero only if every point sits exactly on its centroid. It grows as clusters become more spread out. A small inertia means tight clusters, and a large one means loose clusters.
The unknowns are of two kinds. The labels are discrete: which cluster each point belongs to. The centroids are continuous: where each cluster center sits. k-means searches over both at once.
Computing inertia by hand
The function below computes inertia directly from the definition. It then checks the result against the value scikit-learn stores in inertia_.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=300, centers=3, random_state=42)
km = KMeans(n_clusters=3, n_init=10, random_state=42).fit(X)
def inertia(X, labels, centroids):
"""Sum of squared distances from each point to its assigned centroid."""
diffs = X - centroids[labels] # centroids[labels] has one row per point
return float((diffs ** 2).sum())
print(inertia(X, km.labels_, km.cluster_centers_))
print(km.inertia_)The two printed numbers agree up to floating-point rounding. The expression centroids[labels] uses integer-array indexing to build a matrix with the same shape as X. Row i of that matrix is the centroid of point i's cluster. After that, inertia is one subtraction, one square, and one sum.
Inertia is a sum, not a mean. Doubling the number of points in each cluster roughly doubles inertia, even if the clusters look the same. Dividing by len(X) gives the mean squared distance to the centroid, which is easier to compare across dataset sizes. The inertia_ attribute does not divide.
Why the centroid is the mean
The algorithm moves each centroid to the mean of its points. This choice is forced by the objective, not a convention. Fix the points in one cluster and ask which center c minimizes f(c) = sum of ||x_i - c||^2.
- Take the gradient with respect to
c:-2 * sum of (x_i - c). - Set it to zero:
sum of x_i = n * c, soc = (1/n) * sum of x_i. - The second derivative is
2n, which is positive, so this point is a minimum and not a maximum.
The mean is therefore the exact minimizer of the squared-distance sum for a fixed cluster. Any other center gives a larger sum for that cluster.
The squaring matters here. If you minimized plain (unsquared) distances, the best center would be the geometric median, which has no closed form. If you used absolute differences per feature (L1 distance), the best center would be the per-feature median. That variant is k-medians. Squared Euclidean distance is the choice that makes the update step a one-line average.
The other half: nearest-centroid assignment
Now fix the centroids and ask which assignment minimizes J. Each point contributes its own term, and the terms are independent. The best move is to give each point to the centroid with the smallest squared distance. Minimizing squared distance and minimizing distance pick the same centroid, so the square root is never needed.
The objective explains the two steps of Lloyd's algorithm:
| Step | What is held fixed | What is optimized | Exact answer |
|---|---|---|---|
| Assignment | Centroids | Labels | Nearest centroid for each point |
| Update | Labels | Centroids | Mean of each cluster |
Each step is the exact optimum for its own half of the problem. Neither step can increase J. The next chapter on Lloyd's algorithm builds on this.
Inertia as a share of total variance
Inertia has a useful decomposition. Take the grand mean m of all the data. The total sum of squares around m splits into two parts:
total SS = within-cluster SS + between-cluster SS
- Within-cluster SS is inertia.
- Between-cluster SS is
sum over j of n_j * ||mu_j - m||^2, which measures how far the cluster centroids sit from the grand mean, weighted by cluster size.
The total is fixed by the data. So when the within part shrinks, the between part grows by the same amount. Minimizing inertia is the same as maximizing the separation between centroids, weighted by cluster size. The identity holds exactly when each centroid is the mean of its own cluster. The code below recomputes the centroids from the labels so the identity can be checked.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=300, centers=3, random_state=42)
k = 3
labels = KMeans(n_clusters=k, n_init=10, random_state=42).fit_predict(X)
# Centroids recomputed as exact cluster means
centroids = np.array([X[labels == j].mean(axis=0) for j in range(k)])
grand_mean = X.mean(axis=0)
counts = np.bincount(labels, minlength=k)
total = ((X - grand_mean) ** 2).sum()
within = ((X - centroids[labels]) ** 2).sum()
between = (counts * ((centroids - grand_mean) ** 2).sum(axis=1)).sum()
print(f"total={total:.1f} within={within:.1f} between={between:.1f}")
print("identity holds:", np.isclose(total, within + between))
print(f"share of variance explained: {between / total:.3f}")The last line gives a ratio between 0 and 1. It tells you what fraction of the data's total spread the clusters account for. This is the same idea as R-squared in regression. A value near 1 means the centroids capture most of the structure. A value near 0 means the clusters explain little.
There is a second identity worth knowing. A cluster's within-cluster sum of squares equals (1/n_j) times the sum of squared distances over all unordered pairs of points inside it. Minimizing inertia therefore also pushes each cluster to have small pairwise distances between its members. It is a statement about compactness, not only about distance to a center.
How inertia behaves as k changes
Inertia depends strongly on k, and this limits what you can do with it. The loop below fits several values of k and prints the result.
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, _ = make_blobs(n_samples=300, centers=3, random_state=42)
for k in range(1, 7):
km = KMeans(n_clusters=k, n_init=10, random_state=42).fit(X)
print(f"k={k} inertia={km.inertia_:.1f}")You will see these properties:
| Property | What it means in practice |
|---|---|
| Falls as k grows | More centroids can only bring points closer. The best inertia at `k+1` is never worse than at `k`. |
| Equals total SS at k=1 | One centroid at the grand mean leaves all the variance unexplained. |
| Reaches 0 at k=n | Every point becomes its own cluster. This is useless as a clustering. |
| Scale dependent | Changing the units of a feature changes inertia, so values from different datasets are not comparable. |
| Sum, not mean | Inertia grows with the number of samples. |
The first property is the main trap. You cannot choose k by picking the smallest inertia, because the minimum is always at the largest k you try. Inertia only judges one fit at a fixed k, or the trend across several values of k. The chapter on choosing k shows how to read that trend.
The "best inertia never worse" statement refers to the globally best fit. A single run of k-means can land on a poor local solution, so a particular fit at k+1 may occasionally have higher inertia than a good fit at k. Using several restarts (n_init) reduces this problem.
Gotchas and edge cases
Inertia is in the units you clustered. If you scale features before fitting, inertia_ is measured in scaled space. Comparing it with an inertia computed on raw data is meaningless. When you fit a pipeline, model[-1].inertia_ refers to the scaled features, and cluster_centers_ is also in scaled coordinates.
Squaring amplifies outliers. A point that is 10 units from its centroid contributes 100. A point 1 unit away contributes 1. One far-away point can pull a centroid toward it and increase inertia far more than many ordinary points. If outliers are present, they can dominate the objective. Removing them, clipping them, or using a method based on medians may suit the data better.
Empty clusters. If no point is assigned to a centroid, the cluster contributes zero to inertia, but the mean of an empty set is undefined. Implementations handle this differently. The NumPy version in this tutorial keeps the old centroid. scikit-learn relocates the empty centroid to a point that is far from its current centroid. Either way, the algorithm effectively runs with fewer than k useful clusters for that iteration.
Duplicate points. If your data has fewer than k distinct points, some clusters must be empty or share identical points. scikit-learn warns about this case. Check the number of distinct rows with len(np.unique(X, axis=0)) before choosing a large k.
Low inertia does not mean a good clustering. Inertia says the clusters are compact around their means. It does not say the clusters match meaningful groups. Long, curved, or differently sized groups can give a modest inertia while being split in the wrong places. The chapter on limitations covers these shapes.
Different runs, different inertia. The objective is non-convex, so the final value depends on the starting centroids. When comparing two settings, compare the best inertia over several restarts, not a single run. scikit-learn's n_init parameter does this and keeps the fit with the lowest inertia.
Summary of what the objective tells you
- k-means minimizes the sum of squared Euclidean distances from points to their assigned centroids.
- The squared distance is what makes the mean the exact best center for a fixed cluster.
- The nearest-centroid rule is the exact best assignment for fixed centroids.
- Inertia plus between-cluster spread equals the total spread of the data, so inertia can be turned into a fraction of variance explained.
- Inertia always falls as
krises, depends on units and sample count, and is sensitive to outliers.
Exercise
A one-dimensional dataset has four points: 1, 2, 9, 10. Two clusters are formed: {1, 2} and {9, 10}. Compute the inertia, the total sum of squares around the grand mean, and the between-cluster sum of squares. Check that total = within + between.
Show answer
The centroids are 1.5 and 9.5. Each point is 0.5 from its centroid, so each contributes 0.25, and inertia = 4 0.25 = 1.0. The grand mean is 5.5, and the squared deviations are 20.25, 12.25, 12.25, 20.25, so total = 65. Between-cluster SS = 2 (1.5 - 5.5)^2 + 2 (9.5 - 5.5)^2 = 2 16 + 2 * 16 = 64. Then within + between = 1 + 64 = 65, which equals the total.
Exercise
You fit k-means on two features: income in dollars (values around 50,000) and age in years (values around 40). Why is the resulting inertia almost entirely determined by income, and what would you change?
Show answer
Squared differences in income are in the millions or more, while squared differences in age are in the tens or hundreds. The income term dominates the sum, so the centroids and assignments mostly reflect income. Standardize the features (for example with StandardScaler) before fitting, so each feature contributes on a comparable scale. The inertia will then be measured in scaled units.
Exercise
A colleague fits k-means for k = 2 to 10 and reports that k = 10 is best because it has the lowest inertia. What is wrong with this reasoning?
Show answer
Inertia never increases as k grows, so the largest k will always look best. At k equal to the number of points, inertia is zero. Inertia alone cannot select k. Use it as a trend, as in the elbow method, or combine it with another criterion such as the silhouette score.