TExcelTAD

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 kk 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 kk.

The objective

Given kk, k-means looks for centroids μ1,…,μk\boldsymbol{\mu}_1, \dots, \boldsymbol{\mu}_k and an assignment of each point to one of them that minimise the inertia, the within-cluster sum of squared distances:

J=∑i=1n∥xi−μc(i)∥2J = \sum_{i=1}^{n} \lVert \mathbf{x}_i - \boldsymbol{\mu}_{c(i)} \rVert^2

Lloyd's algorithm alternates two steps, each of which can only lower JJ:

  1. assign: each point joins its nearest centroid (best c(i)c(i) for fixed centroids);
  2. update: each centroid moves to the mean of its points (the mean minimises the sum of squared distances, Expectation, Variance and Summary Statistics).

JJ 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, k=3k = 3, 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:

python · try it yourself
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 D(x)2D(\mathbf{x})^2 to the nearest centre chosen so far, so starting centres are spread out. It comes with a guarantee (expected inertia within O(log⁡k)O(\log k) of the optimum) and is scikit-learn's default, together with n_init restarts keeping the best run.

python · try it yourself
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 kk as input, and the inertia always falls as kk grows (with k=nk = n it is 0), so it cannot choose kk by itself. Two common aids: the elbow of the inertia curve, and the silhouette score, which compares for each point the mean distance aa to its own cluster with the mean distance bb to the nearest other cluster, s=(b−a)/max⁡(a,b)s = (b - a)/\max(a, b), averaged over points (1 is ideal, 0 is on a border).

python · try it yourself
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 k=4k = 4 (big drops before, small after). The silhouette, however, prefers k=2k = 2: 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 kk 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 (kk) 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 (O(nkd)O(nkd) per iteration), scales to millions of points and gives centroids that summarise each group. It needs kk 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_init above 1.
  • Reading clusters as real categories. k-means always returns kk groups, even in data without any structure.

Practice

  1. Prove that the update step cannot increase JJ.
Answer

With assignments fixed, JJ splits into one term per cluster, ∑i∈Cj∥xi−μj∥2\sum_{i \in C_j} \lVert \mathbf{x}_i - \boldsymbol{\mu}_j \rVert^2. Its gradient in μj\boldsymbol{\mu}_j is −2∑i∈Cj(xi−μj)-2\sum_{i \in C_j}(\mathbf{x}_i - \boldsymbol{\mu}_j), zero at the mean, and the term is convex, so the mean is its minimum: moving the centroid there cannot increase it.

  1. 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 D2D^2: 99 versus 11, so Q is 9 times as likely as P.

Test yourself

What does k-means minimise?

  1. The number of clusters
  2. The sum of squared distances from points to their cluster's centroid
  3. The distance between centroids
  4. The silhouette score

Why does scikit-learn run k-means several times (n_init)?

  1. To average the centroids
  2. Lloyd's algorithm finds a local minimum that depends on the start; restarts keep the best
  3. To choose kk
  4. To scale the data

Which data set is hard for k-means?

  1. Three round, well-separated blobs
  2. Two interleaving half-moons
  3. Four blobs of equal size
  4. Colour values of an image

The inertia falls from 1115.8 at k=3k = 3 to 575.5 at k=4k = 4 and then only to 507.6 at k=5k = 5. What does that suggest?

  1. k = 5 is best because the inertia is lowest
  2. An elbow at k = 4
  3. The data has no clusters
  4. k-means failed