Skip to content
Lambdian

k-means clustering

Find k groups by alternating between assigning points to centroids and moving centroids to means.

Animated explanation

The idea

You have customer data and no labels, and you suspect there are a few kinds of customers. k-means makes that concrete: choose kk, scatter kk centroids, then repeat two steps until nothing changes. Assign every point to its nearest centroid. Move every centroid to the average of its points.

Each step lowers the total squared distance from points to their centroids, so the loop always finishes. The result partitions space into kk convex cells (a Voronoi diagram). It is fast and simple, and it assumes clusters are roughly round, similar in size, and that you know kk.

Initialisation matters

k-means finds a local minimum. Random starting centroids can put two in one blob and none in another. k-means++ picks the first centroid at random and each next one with probability proportional to its squared distance from the nearest centroid already chosen. Run several restarts (n_init) and keep the lowest inertia.

Choosing k

Inertia always decreases with kk, so it cannot choose kk alone. Use the elbow of the inertia curve, the silhouette score (how much closer each point is to its own cluster than to the next), the gap statistic, or simply the number of groups that is useful to the business.

When it fails

Non-convex shapes (rings, moons), clusters of very different size or density, and outliers all break k-means; and features must be scaled, since it uses Euclidean distance. Alternatives: GMMs (elliptical, soft), DBSCAN (arbitrary shape, noise), spectral clustering (graph structure). Mini-batch k-means scales to millions of points.

The algorithm, step by step

  1. 1
    Standardise features. Choose kk and initialise centroids with k-means++.
  2. 2
    Assign each point to the nearest centroid.
  3. 3
    Move each centroid to the mean of its assigned points.
  4. 4
    Repeat until assignments stop changing (or inertia improves by less than a tolerance).
  5. 5
    Repeat from several initialisations; keep the lowest inertia.

The maths

Objective (inertia)

J({ci},{μk})=∑i∥xi−μci∥2J(\{c_i\}, \{\boldsymbol\mu_k\}) = \sum_i \lVert\mathbf{x}_i - \boldsymbol\mu_{c_i}\rVert^2

Assignment

ci=arg⁡min⁡k∥xi−μk∥2c_i = \arg\min_k \lVert\mathbf{x}_i - \boldsymbol\mu_k\rVert^2

Update

μk=1∣Ck∣∑i∈Ckxi\boldsymbol\mu_k = \frac{1}{|C_k|}\sum_{i\in C_k}\mathbf{x}_i

Silhouette of point i

si=bi−aimax⁡(ai,bi)s_i = \frac{b_i - a_i}{\max(a_i, b_i)}
aia_i: mean distance to its own cluster; bib_i: to the nearest other cluster.

Strengths and weaknesses

Strengths

  • Simple, fast (linear in n per iteration)
  • Scales to huge data (mini-batch)
  • Easy to explain: prototypes

Weaknesses

  • Must choose k
  • Assumes round, similar-sized clusters; sensitive to scale and outliers
  • Local minima: needs good initialisation

Reach for it when…

Quick segmentation of numeric data with compact clusters, vector quantisation, or initialising more complex models.

Check your understanding

Question 1

Q1Why does k-means always terminate?

Question 2

Q2Data forms two concentric rings. k-means with k = 2 will…

Question 3

Q3What does k-means++ change?

Lambdian Lab

k-means with k-means++

Implement the full algorithm.

  • kmeans_pp(X, k, rng): k-means++ initial centroids.
  • assign(X, C) → labels; update(X, labels, C) → new centroids (keep a centroid in place if its cluster is empty).
  • kmeans(X, k, n_init, iters, seed) → (centroids, labels, inertia) of the best run.
  • elbow(X, ks, seed) → list of inertias.
Open the labPython + NumPy + scikit-learn runs in your browser. Sign-in keeps your code and attempts.