k-Means Clustering
A shop wants to group its customers by how they buy, without any labels saying which groups exist. A designer wants to reduce a photo to 16 colours. A sensor network wants to place 5 relay stations near the sensors they serve. All three ask the same question: where should centres go so that every point is close to one of them? k-means answers it with two alternating steps and is the most used clustering algorithm. The Machine Learning course shows it with scikit-learn; here you step through it, implement it with k-means++ seeding and learn how to choose .
The objective
Given , k-means looks for centroids and an assignment of each point to one of them that minimise the inertia, the within-cluster sum of squared distances:
Lloyd's algorithm alternates two steps, each of which can only lower :
- assign: each point joins its nearest centroid (best for fixed centroids);
- update: each centroid moves to the mean of its points (the mean minimises the sum of squared distances, Expectation, Variance and Summary Statistics).
decreases at every step and there are finitely many assignments, so the algorithm stops, but at a local minimum that depends on the starting centroids. Finding the global minimum is NP-hard.
Step through it
Ten points, , starting from the first three points as centroids (all three in the bottom-left group, a deliberately poor start). Each iteration shows an assign frame and an update frame with the inertia:
The same run in NumPy, printing the labels and the inertia after each assignment:
import numpy as np
points = np.array([[12, 20], [18, 28], [22, 15], [30, 24], [60, 70], [68, 78], [72, 64], [85, 25], [78, 18], [90, 30]], dtype=float)
centroids = points[[0, 1, 2]].copy() # start from the first three points (as the animation)
for it in range(1, 21):
d = ((points[:, None, :] - centroids[None]) ** 2).sum(axis=2)
labels = d.argmin(axis=1) # assign: nearest centroid (ties to the lower number)
inertia = d[np.arange(len(points)), labels].sum()
print(f"iteration {it}: labels {labels.tolist()} inertia {inertia:.1f}")
new = np.array([points[labels == j].mean(axis=0) if np.any(labels == j) else centroids[j] for j in range(3)])
if np.allclose(new, centroids):
break
centroids = new # update: each centroid moves to the mean of its points
print("final centroids:", centroids.round(1).tolist())iteration 1: labels [0, 1, 2, 2, 1, 1, 1, 2, 2, 2] inertia 24948.0
iteration 2: labels [0, 0, 0, 0, 1, 1, 1, 2, 2, 2] inertia 3313.6
iteration 3: labels [0, 0, 0, 0, 1, 1, 1, 2, 2, 2] inertia 582.4
final centroids: [[20.5, 21.8], [66.7, 70.7], [84.3, 24.3]]
After the first assignment the two distant groups are claimed by centroids sitting in the wrong corner, and the inertia is huge (24 948). The updates drag the centroids out, and by the third assignment every point is in its natural group (inertia 582.4). Here the poor start recovered; it does not always.
k-means++ and the library version
k-means++ (Arthur and Vassilvitskii, 2007) picks the first centre at random and each next one with probability proportional to its squared distance to the nearest centre chosen so far, so starting centres are spread out. It comes with a guarantee (expected inertia within of the optimum) and is scikit-learn's default, together with n_init restarts keeping the best run.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
X, true = make_blobs(n_samples=300, centers=4, cluster_std=1.0, random_state=1)
def kmeans_pp_init(X, k, rng):
"""k-means++: each new centre is drawn with probability proportional to D(x)^2."""
centres = [X[rng.integers(len(X))]]
for _ in range(k - 1):
d2 = np.min(((X[:, None] - np.array(centres)[None]) ** 2).sum(axis=2), axis=1)
centres.append(X[rng.choice(len(X), p=d2 / d2.sum())])
return np.array(centres)
def kmeans(X, init, max_iter=100):
C = init.copy()
for it in range(max_iter):
labels = ((X[:, None] - C[None]) ** 2).sum(axis=2).argmin(axis=1)
new = np.array([X[labels == j].mean(axis=0) for j in range(len(C))])
if np.allclose(new, C):
break
C = new
inertia = ((X - C[labels]) ** 2).sum()
return labels, C, inertia, it + 1
rng = np.random.default_rng(0)
init = kmeans_pp_init(X, 4, rng)
labels, C, inertia, iters = kmeans(X, init)
sk = KMeans(n_clusters=4, init=init, n_init=1).fit(X)
print("ours: inertia", round(inertia, 2), " iterations", iters)
print("sklearn: inertia", round(sk.inertia_, 2), " iterations", sk.n_iter_)
print("same assignments:", bool(np.all(labels == sk.labels_)))
for blob in range(4):
bad = X[true == blob][:4] # a poor start: all four centres inside one blob
print(f"start with 4 centres in blob {blob}: inertia {kmeans(X, bad)[2]:.2f}")ours: inertia 575.49 iterations 5
sklearn: inertia 575.49 iterations 5
same assignments: True
start with 4 centres in blob 0: inertia 2129.88
start with 4 centres in blob 1: inertia 575.49
start with 4 centres in blob 2: inertia 575.49
start with 4 centres in blob 3: inertia 575.49
Started from the same k-means++ centres, the from-scratch version and KMeans take the same 5 iterations to the same clustering. Starting with all four centres inside one blob, three of four runs still reach the good solution (575.49), but one is stuck at a local minimum almost four times worse (2129.88). That is why n_init restarts exist.
Choosing k
k-means needs as input, and the inertia always falls as grows (with it is 0), so it cannot choose by itself. Two common aids: the elbow of the inertia curve, and the silhouette score, which compares for each point the mean distance to its own cluster with the mean distance to the nearest other cluster, , averaged over points (1 is ideal, 0 is on a border).
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=1.0, random_state=1)
print(" k inertia silhouette")
for k in range(2, 8):
km = KMeans(n_clusters=k, n_init=10, random_state=0).fit(X)
print(f"{k:2d} {km.inertia_:8.1f} {silhouette_score(X, km.labels_):.3f}") k inertia silhouette
2 2203.4 0.706
3 1115.8 0.582
4 575.5 0.630
5 507.6 0.555
6 455.1 0.505
7 402.6 0.390
The data was generated with 4 blobs. The inertia shows a clear elbow at (big drops before, small after). The silhouette, however, prefers : two pairs of blobs lie close together, and at the coarse level two groups are the cleanest description. Neither number is "the truth"; they answer different questions. Choose with the criteria, a look at the clusters, and what the grouping is for. More on this in Evaluating and Comparing Clusterings.
Hyperparameters
| Hyperparameter | Effect |
|---|---|
n_clusters () |
the number of clusters, chosen by you |
init |
"k-means++" (default) or "random" or given centres |
n_init |
restarts; the run with the lowest inertia is kept |
max_iter, tol |
stopping rules |
MiniBatchKMeans |
updates centres from small batches; for very large data |
Strengths, weaknesses, when to use it
k-means is simple, fast ( per iteration), scales to millions of points and gives centroids that summarise each group. It needs in advance, finds only convex, roughly round clusters of similar spread (it is the hard-assignment limit of a Gaussian mixture with equal spherical covariances), depends on feature scaling, is pulled by outliers, and assigns every point to a cluster. Use it for compact groups (customer segments on scaled features, colour quantisation, vector quantisation, initialising other methods); use DBSCAN for irregular shapes and noise.
Pitfalls
- Unscaled features. Inertia is a squared Euclidean distance; a feature in dollars swamps one in years.
- One run. A single unlucky start can be far from the best; keep
n_initabove 1. - Reading clusters as real categories. k-means always returns groups, even in data without any structure.
Practice
- Prove that the update step cannot increase .
Answer
With assignments fixed, splits into one term per cluster, . Its gradient in is , zero at the mean, and the term is convex, so the mean is its minimum: moving the centroid there cannot increase it.
- In k-means++, the current centres are at distance 1 from point P and distance 3 from point Q. How much more likely is Q to be picked as the next centre?
Answer
Probabilities are proportional to : versus , so Q is 9 times as likely as P.
Test yourself
What does k-means minimise?
- The number of clusters
- The sum of squared distances from points to their cluster's centroid
- The distance between centroids
- The silhouette score
Why does scikit-learn run k-means several times (n_init)?
- To average the centroids
- Lloyd's algorithm finds a local minimum that depends on the start; restarts keep the best
- To choose
- To scale the data
Which data set is hard for k-means?
- Three round, well-separated blobs
- Two interleaving half-moons
- Four blobs of equal size
- Colour values of an image
The inertia falls from 1115.8 at to 575.5 at and then only to 507.6 at . What does that suggest?
- k = 5 is best because the inertia is lowest
- An elbow at k = 4
- The data has no clusters
- k-means failed