Lesson 2 of 8 · No Labels
Clustering Overview
How clustering works: k-means and k-means++, inertia, the elbow method, silhouette scores, hierarchical clustering, DBSCAN, Gaussian mixtures and scaling.
- 20 min read
- Intermediate
- Reviewed
- Run k-means step by step, and explain what k-means++ and n_init add
- Choose the number of clusters with inertia, the elbow method and the silhouette score
- Explain agglomerative clustering, linkage and the dendrogram
- Use DBSCAN for clusters of any shape with noise, and Gaussian mixtures for soft assignments
- Scale features before clustering, and pick a method that suits the data
The idea in plain words
Clustering puts similar examples into the same group. To a clustering algorithm, every example is a point with one coordinate per feature, and "similar" usually means "close together": the smaller the distance between two points, the more alike the two examples are.
There are many clustering algorithms because there are many ideas of what a group is. This lesson tours the four main families: centroid-based (k-means: points around a centre), hierarchical (agglomerative clustering: branches of a tree of merges), density-based (DBSCAN: crowded regions) and model-based (Gaussian mixtures: overlapping bell-shaped clouds).
k-means, step by step
k-means describes each cluster by its centre, the centroid, and works like this:
- Start: choose k, the number of clusters, and place k starting centres.
- Assign: give every point to its nearest centre.
- Update: move every centre to the mean (average position) of the points assigned to it.
- Repeat steps 2 and 3 until the assignments stop changing.
Here is the whole algorithm in a few lines of NumPy, on 8 points, from a deliberately poor start:
import numpy as np
# 8 points, two features each
X = np.array([[1, 2], [2, 1], [1.5, 1.8], [8, 8], [1, 0.6], [9, 9.5], [8.5, 7], [7, 9]])
centres = X[[0, 2]].copy() # 1. start: two of the points as centres (a poor start, on purpose)
for step in range(1, 10):
# 2. assign every point to its nearest centre
distances = np.array([[np.linalg.norm(x - c) for c in centres] for x in X])
groups = distances.argmin(axis=1)
inertia = np.sum(distances.min(axis=1) ** 2)
print(f"step {step}: groups {groups}, inertia {inertia:.1f}")
# 3. move every centre to the mean of its points
new_centres = np.array([X[groups == k].mean(axis=0) for k in range(2)])
if np.allclose(new_centres, centres): # 4. stop when nothing moves
break
centres = new_centres
print("final centres:", np.round(centres, 2).tolist())step 1: groups [0 1 1 1 1 1 1 1], inertia 356.9 step 2: groups [0 0 0 1 0 1 1 1], inertia 80.9 step 3: groups [0 0 0 1 0 1 1 1], inertia 7.9 final centres: [[1.38, 1.35], [8.12, 8.38]]
Both starting centres were in the bottom-left group, so at step 1 one centre grabbed almost every point. After one update the centres moved apart, the assignments became sensible, and at step 3 nothing changed, so the algorithm stopped with one centre in each group.
Better starts: k-means++ and n_init
k-means always finishes, but where it finishes depends on where it started. A bad start can leave it stuck with two centres sharing one real group while another centre sits between two groups. scikit-learn has two fixes built in. k-means++, the default init, chooses spread-out starting centres: the first is a random point, and each next one is picked at random, with points far from the centres chosen so far much more likely to be picked. n_init runs k-means several times from different starts and keeps the run with the lowest inertia.
The program below clusters data with 10 real groups, five times with purely random starts and five times with k-means++:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
X, _ = make_blobs(n_samples=400, centers=10, cluster_std=0.5, random_state=2) # 10 real groups
for init in ["random", "k-means++"]:
scores = [KMeans(n_clusters=10, init=init, n_init=1, random_state=seed).fit(X).inertia_
for seed in range(5)]
print(f"init={init:<10} five single runs, inertia: {np.round(scores).astype(int).tolist()}")
best = KMeans(n_clusters=10, n_init=10, random_state=0).fit(X) # k-means++ by default
print(f"k-means++, best of n_init=10 runs: inertia {best.inertia_:.0f}")init=random five single runs, inertia: [402, 1122, 403, 283, 396] init=k-means++ five single runs, inertia: [193, 193, 193, 193, 283] k-means++, best of n_init=10 runs: inertia 193
Random starts finished at very different places, all of them worse than the best solution (193). k-means++ found it in four runs out of five, and keeping the best of 10 runs found it too. That's why this course writes n_init=10: it costs ten times the work, but protects you from an unlucky start.
How many clusters? The elbow and the silhouette
k-means needs k before it starts. Inertia alone can't choose it, because more clusters always means smaller distances: with one cluster per point, inertia would be 0. The elbow method computes inertia for a range of k and looks for the elbow, the k after which adding a cluster barely helps. The silhouette score measures how much closer each point is to its own cluster than to the next nearest one:
a = average distance from a point to the other points in its own cluster
b = average distance from the point to the points of the nearest other cluster
silhouette of the point = (b − a) ÷ (the larger of a and b)
silhouette score = the average over all points: from −1 (wrong clusters) to 1 (well separated)from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=300, centers=4, cluster_std=1.0, random_state=8) # 4 real groups
print(" k inertia silhouette")
for k in range(2, 9):
model = KMeans(n_clusters=k, n_init=3, random_state=0).fit(X)
print(f"{k:>2} {model.inertia_:9.0f} {silhouette_score(X, model.labels_):12.2f}")k inertia silhouette 2 6479 0.63 3 3541 0.65 4 653 0.78 5 587 0.67 6 529 0.56 7 479 0.44 8 436 0.44
Inertia falls steeply up to k = 4 (from 6479 to 653), then only slowly (587, 529, …): the elbow is at 4. The silhouette score agrees, peaking at 0.78 for k = 4. (n_init=3 keeps this loop quick.) On real data the two guides often disagree or show no clear winner. Then let the purpose decide: a marketing team may prefer 4 segments it can act on over 7 that score slightly better.
Agglomerative (hierarchical) clustering
Agglomerative clustering builds clusters from the bottom up. Every point starts as its own cluster, and the two closest clusters are merged, again and again, until only one is left. The linkage decides what "closest clusters" means:
- single: the distance between their two closest points. Follows long or curved shapes, but one stray point can chain two clusters together.
- complete: the distance between their two farthest points. Gives compact clusters.
- average: the average distance over all pairs of points, one from each cluster.
- ward (scikit-learn's default): merges the pair that increases inertia the least. Gives compact clusters of similar size, like k-means.
The program below records every merge for six points, A to F, using average linkage:
import numpy as np
from sklearn.cluster import AgglomerativeClustering
names = ["A", "B", "C", "D", "E", "F"]
X = np.array([[1, 1], [1.5, 1.2], [5, 5], [5.2, 6], [6, 5.4], [12, 3]]) # six points on a map
tree = AgglomerativeClustering(n_clusters=None, distance_threshold=0, linkage="average").fit(X)
groups = [[name] for name in names] # every point starts as its own group
for (i, j), d in zip(tree.children_, tree.distances_):
groups.append(groups[i] + groups[j]) # each merge makes a new, bigger group
print(f"merge {'+'.join(groups[i]):<6} with {'+'.join(groups[j]):<6} at distance {d:.2f}")merge A with B at distance 0.54 merge D with E at distance 1.00 merge C with D+E at distance 1.05 merge A+B with C+D+E at distance 6.04 merge F with A+B+C+D+E at distance 8.60
Drawn as a tree, with the height of each join showing the distance at which the merge happened, this history is a dendrogram:
merge distance (not to scale)
8.60 ┌──────────┴───────────┐
6.04 ┌────┴────┐ │
cut - - │ - - - - │ - - - - - - - - │ - 3 groups
1.05 │ ┌──┴───┐ │
1.00 │ │ ┌─┴─┐ │
0.54 ┌─┴─┐ │ │ │ │
A B C D E FThe dashed cut crosses three branches, so it gives three clusters: A+B, C+D+E and F. A big jump in merge distance, here from 1.05 to 6.04, is a sign of natural groups, much like the elbow in k-means. In scikit-learn, AgglomerativeClustering(n_clusters=3, linkage="average").fit_predict(X) makes this cut, and distance_threshold cuts at a chosen height instead. Agglomerative clustering compares every pair of points, so it suits datasets of up to some tens of thousands of rows, and it has no predict for new points.
DBSCAN: clusters of any shape, plus noise
DBSCAN (density-based spatial clustering of applications with noise) sees clusters as crowded regions. It needs two settings: eps, the radius of a point's neighbourhood, and min_samples, how many points (counting the point itself) must lie within eps for the point to count as a core point, deep inside a crowd. Core points that are within eps of each other join the same cluster, and points near a core point join its cluster too. Every other point is noise and gets the label -1. You never choose the number of clusters: it follows from the data. The program below compares k-means and DBSCAN on two crescent-shaped groups with six stray points:
import numpy as np
from sklearn.cluster import DBSCAN, KMeans
from sklearn.datasets import make_moons
from sklearn.metrics import adjusted_rand_score
X, moon = make_moons(n_samples=200, noise=0.06, random_state=0) # two curved groups
stray = np.random.default_rng(1).uniform([-1.5, -1], [2.5, 1.5], size=(6, 2)) # 6 stray points
X_all = np.vstack([X, stray])
kmeans = KMeans(n_clusters=2, n_init=10, random_state=0).fit_predict(X_all)
print(f"k-means, k=2: agreement with the moons {adjusted_rand_score(moon, kmeans[:200]):.2f}")
for eps in [0.1, 0.2, 0.3]:
labels = DBSCAN(eps=eps, min_samples=5).fit_predict(X_all)
n_clusters = len(set(labels) - {-1}) # -1 means noise, not a cluster
print(f"DBSCAN eps={eps}: {n_clusters:>2} clusters, {np.sum(labels == -1):>2} noise points, "
f"agreement {adjusted_rand_score(moon, labels[:200]):.2f}")k-means, k=2: agreement with the moons 0.26 DBSCAN eps=0.1: 18 clusters, 61 noise points, agreement 0.06 DBSCAN eps=0.2: 2 clusters, 5 noise points, agreement 1.00 DBSCAN eps=0.3: 1 clusters, 4 noise points, agreement 0.00
The agreement is the adjusted Rand index from the previous lesson, comparing each result with the true moons (1 means a perfect match). k-means can only draw a straight border between two centres, so it cuts both crescents in half (0.26). DBSCAN with eps = 0.2 follows the curves exactly (1.00) and marks 5 of the 6 stray points as noise. But eps matters a lot: at 0.1, the neighbourhoods are too small and the moons shatter into 18 pieces; at 0.3, they are big enough to bridge the gap, and everything becomes one cluster. DBSCAN also struggles when clusters have very different densities; HDBSCAN, also in scikit-learn, handles that better and needs no eps.
Gaussian mixtures: soft assignments
The methods so far give each point exactly one cluster, a hard assignment. A Gaussian mixture model assumes the data is a mix of several bell-shaped (Gaussian) clouds, each with its own centre, spread and tilt, and gives every point a probability of belonging to each cloud: a soft assignment.
import numpy as np
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
# two overlapping groups, centred at x = 0 and x = 4
X, _ = make_blobs(n_samples=300, centers=[[0, 0], [4, 0]], cluster_std=1.2, random_state=0)
gmm = GaussianMixture(n_components=2, random_state=0).fit(X)
left, right = np.argsort(gmm.means_[:, 0]) # which component is the left one
points = np.array([[-1.0, 0.0], [1.5, 0.0], [2.0, 0.0], [2.5, 0.0], [5.0, 0.0]])
for point, p in zip(points, gmm.predict_proba(points)):
print(f"x = {point[0]:4.1f}: left group {p[left]:.2f}, right group {p[right]:.2f}")x = -1.0: left group 1.00, right group 0.00 x = 1.5: left group 0.77, right group 0.23 x = 2.0: left group 0.42, right group 0.58 x = 2.5: left group 0.14, right group 0.86 x = 5.0: left group 0.00, right group 1.00
Points deep inside a group are certain (1.00), while points near the middle, where the clouds overlap, get split probabilities such as 0.42 and 0.58. predict still returns the most likely cluster, and predict_proba adds how sure the model is. That helps when groups overlap: a customer who is 55% "bargain hunter" deserves different treatment from one who is 99%.
Why scaling matters
Clustering runs on distances, so a feature measured in big numbers outweighs one measured in small numbers. Below, customers come in two age groups, while income (in the tens of thousands) has nothing to do with age:
import numpy as np
from sklearn.cluster import KMeans
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import StandardScaler
rng = np.random.default_rng(0)
age = np.concatenate([rng.normal(25, 3, 100), rng.normal(60, 5, 100)]) # two age groups
income = rng.normal(50_000, 15_000, 200) # unrelated to age
X = np.column_stack([age, income])
for name, model in [("unscaled", KMeans(n_clusters=2, n_init=10, random_state=0)),
("scaled", make_pipeline(StandardScaler(), KMeans(n_clusters=2, n_init=10, random_state=0)))]:
groups = model.fit_predict(X)
for g in range(2):
print(f"{name:<8} group {g}: average age {age[groups == g].mean():4.1f}, "
f"average income {income[groups == g].mean():6.0f}")unscaled group 0: average age 44.4, average income 62547 unscaled group 1: average age 41.1, average income 37991 scaled group 0: average age 59.7, average income 49415 scaled group 1: average age 25.2, average income 47930
Without scaling, a 35-year age gap counts the same as a difference of 35 in income, which is nothing next to income gaps of thousands, so k-means simply splits customers into lower and higher incomes, and both groups have an average age in the forties. The two real age groups are invisible. After StandardScaler, both features count equally and k-means finds the 25-year-olds and the 60-year-olds. Scale before k-means, agglomerative clustering and DBSCAN. The exception is features that already share one unit, such as the pixel values of an image.
Choosing a method
| Method | You choose | Cluster shapes | Outliers | New points |
|---|---|---|---|---|
| k-means | k | Round, similar sizes | Forced into a cluster | predict |
| Agglomerative | k or a cut height, and the linkage | Depends on the linkage | Forced into a cluster | No predict |
| DBSCAN | eps and min_samples | Any shape, similar densities | Labelled -1 | No predict |
| Gaussian mixture | Number of components | Ovals that may overlap | Forced into a cluster, but score_samples rates them unlikely | predict and predict_proba |
A good habit is to start with k-means on scaled features, check the elbow and the silhouette, and look at the members of each cluster. Try DBSCAN when the clusters look curved or stretched, or when outliers matter. Use agglomerative clustering on smaller datasets when the hierarchy itself is useful, and a Gaussian mixture when groups overlap and you need to know how sure each assignment is.
Common mistakes
Practice
Use the silhouette score to choose the number of clusters: try every k from 2 to 7 and report the best one.
from sklearn.cluster import KMeans
from sklearn.datasets import make_blobs
from sklearn.metrics import silhouette_score
X, _ = make_blobs(n_samples=250, centers=5, cluster_std=0.9, random_state=7)
# For every k from 2 to 7:
# cluster X with KMeans(n_clusters=k, n_init=3, random_state=0)
# print its silhouette score, rounded to 2 decimals, like: k=2: 0.56
# Then print the k with the highest score, like: best k: 2
best_k = None
print("best k:", best_k)
Your data has two crescent-shaped groups and a few stray points. Which method suits it best?
Summary
- k-means alternates two steps, assigning points to the nearest centre and moving each centre to the mean of its points, which lowers inertia. k-means++ and
n_initprotect it from bad starts. - Choose k with the elbow in inertia and the silhouette score (−1 to 1, higher is better), then check that the clusters make sense.
- Agglomerative clustering merges the closest clusters step by step. The linkage defines "closest", and cutting the dendrogram gives the clusters.
- DBSCAN finds crowded regions of any shape and labels sparse points as noise (-1), controlled by eps and min_samples. Gaussian mixtures give soft, probabilistic assignments.
- Scale features before clustering, and choose the method by the shape of the clusters, the noise, and whether you need
predictor probabilities.
Next: Dimensionality Reduction Overview.
Finished reading? Tick it off to track your progress.