Clustering: k-means, hierarchical and density-based

Group similar rows without labels, and understand what each algorithm assumes about the shape of a group.

Lesson 48 of 6614 minIntermediate

You will learn to

  • Explain how k-means, hierarchical clustering and DBSCAN form groups
  • Know why scaling matters for clustering
  • Describe clusters in business terms

Before this lesson

Intuition

Walk into a shop and you can usually tell who belongs together: students, families, business customers. Nobody gave you labels. You noticed similarity in what people bought, how much they spent, how old they looked.

Clustering is that skill for data. Given rows described by numbers, it groups rows that are similar to each other and different from the rest. There is no target column to predict, so this is unsupervised learning. Typical uses are customer segments, groups of similar products, and a first look at data you do not yet understand.

The key word is similar, and an algorithm needs it as a number: usually distance. Rows that are close are similar. That has two consequences. Columns on large scales dominate distances, so you must scale first. And different algorithms disagree about what a "group" is, so you choose by the shape of groups you expect.

Picture it

k-means: round groupsx = CentroidDensity-based: any shape
Left: k-means splits points into round groups around centroids (crosses). Right: a dense blob inside a ring. A density-based method follows the dense regions and finds both; k-means would cut the ring into pieces.

The three families in short:

  • k-means needs you to choose the number of clusters kk. It places kk centroids, assigns each row to the nearest one, moves each centroid to the mean of its rows, and repeats until nothing changes. Fast, and best for compact, similarly sized, round groups.
  • Hierarchical (agglomerative) starts with every row as its own cluster and repeatedly merges the two closest clusters. You get a tree and can cut it at any level.
  • Density-based (DBSCAN, OPTICS) grows clusters from dense regions. You do not choose the number of clusters; you choose how close is "dense". Points in no dense region are labelled noise.

The math

k-means minimises the within-cluster sum of squares, the total squared distance from each row to the centroid of its cluster CjC_j:

J=∑j=1k∑xi∈Cj∥xi−μj∥2,μj=1∣Cj∣∑xi∈CjxiJ = \sum_{j=1}^{k}\sum_{x_i \in C_j}\lVert x_i - \mu_j \rVert^2, \qquad \mu_j = \frac{1}{|C_j|}\sum_{x_i \in C_j} x_i

Each assignment step and each update step lowers JJ or leaves it unchanged, so the loop ends. It may end in a local minimum, which is why implementations restart from several initial centroids.

Distance is usually Euclidean: d(x,z)=∑c(xc−zc)2d(x, z) = \sqrt{\sum_c (x_c - z_c)^2}. A column with a large range contributes large terms. Scaling (for example, standardising each column to mean 0 and spread 1) puts every column on a comparable footing.

DBSCAN has two settings: a radius ε\varepsilon and a minimum number of neighbours minPts\text{minPts}. A row with at least minPts\text{minPts} rows within ε\varepsilon is a core row; clusters are chains of core rows and their neighbours.

Worked example

k-means by hand. Six one-dimensional values: 1, 2, 4, 9, 10, 12, with k=2k = 2 and starting centroids 1 and 12.

  1. Assign each value to the nearer centroid. 1, 2 and 4 go to centroid 1 (4 is 3 away from 1 and 8 away from 12). 9, 10 and 12 go to centroid 12.
  2. Update the centroids: the means are 7 / 3 = 2.333 and 31 / 3 = 10.333.
  3. Assign again. 4 is 1.67 from 2.333 and 6.33 from 10.333; 9 is 6.67 from 2.333 and 1.33 from 10.333. Nothing changes: done.

The within-cluster sum of squares is (1.78 + 0.11 + 2.78) + (1.78 + 0.11 + 2.78) = 4.67 + 4.67 = 9.33.

Why scaling matters. Three customers, with age and income:

CustomerAgeIncome
A3040,000
B6041,000
C3180,000

Unscaled, the distance from A to B is the square root of 30 squared plus 1,000 squared, about 1,000. From A to C it is about 40,000. Age is invisible: B, 30 years older, looks 40 times closer to A than C does. Now divide each column by an illustrative spread (15 years and 20,000 dollars). A to B becomes about 2.0006 and A to C about 2.0011: about equal, because B is far in age and C is far in income. Both columns now count.

How mlflow does it

  • Clustering is one of the tasks of a pipeline: there is no target column.
  • The catalog has these algorithms: k-means (kmeans), agglomerative or hierarchical (hclust), DBSCAN (dbscan), OPTICS (optics), Birch (birch), affinity propagation (ap), mean shift (meanshift), spectral (sc) and k-modes (kmodes, for categorical columns).
  • The Customer segmentation use case sets this up for you: it picks Age, Income, SpendingScore and Savings from the jewellery sample data, applies Standardise to them, and trains k-means and hierarchical clustering.
  • Plots for clustering runs include cluster sizes, the elbow curve, silhouette plots and a 2-D embedding. See Evaluating clusters and the Clustering task page.

Common mistakes

  • Clustering unscaled columns. The column with the largest numbers wins. Add a scaler to the pipeline.
  • Believing the clusters are "real". k-means always returns kk clusters, even for uniform random data. Check that they are stable and meaningful.
  • Using k-means on non-round shapes. Rings, crescents and elongated groups call for density-based or hierarchical methods.
  • Mixing numeric and categorical columns carelessly. Euclidean distance on one-hot columns is awkward; consider k-modes for categorical data or encode with care.
  • Naming clusters by their number. "Cluster 3" helps nobody. Describe each by its average columns: for example "young, high spenders, low savings".
  • Forgetting outliers. A few extreme rows pull centroids. Check outliers first, or use a density-based method that labels them as noise.

Try it in mlflow

Try the Customer segmentation use case

  1. Open Use cases and choose Customer segmentation.
  2. Create the pipeline: it uses the jewellery sample data (Age, Income, SpendingScore, Savings) with Standardise on the numeric columns and the k-means and hierarchical algorithms.
  3. Run it and open the best model candidate.
  4. Look at the cluster sizes and the 2-D embedding, then try to give each cluster a short name a marketer would understand.
Open in mlflow

Read in the docs

Check your understanding

  1. 1. Customers are described by age (years, 20 to 70) and income (dollars, 20,000 to 120,000). You run k-means without scaling. What happens?
  2. 2. Your data has a dense blob inside a ring of points, plus a few scattered points far away. Which algorithm family fits best?
  3. 3. What does hierarchical clustering give you that k-means does not?