v9.1.1
Menu

Chapter 8: Clustering

Week 15-16

Discover hidden structure in unlabeled data through unsupervised learning. Master K-Means for partitioning, hierarchical methods for building cluster trees, density-based DBSCAN for arbitrary shapes, and learn to evaluate cluster quality without ground truth.

Topics
3
Demos
4
Min read
26

Chapter Overview

Clustering is the quintessential unsupervised learning task: finding natural groupings in data without any labels to guide us. Unlike supervised learning where we have ground truth, clustering must discover structure purely from the data itself.

The applications are everywhere: segmenting customers by behavior, grouping similar documents, detecting anomalies that don't fit any cluster, compressing images by grouping similar colors, and exploring high-dimensional data by identifying natural categories.

Different clustering algorithms make different assumptions about what constitutes a "cluster." K-Means assumes clusters are spherical and roughly equal-sized. Hierarchical methods build trees that can be cut at any level. Density-based methods like DBSCAN find clusters of arbitrary shape and automatically identify outliers.

Choosing the right algorithm and parameters requires understanding these assumptions and evaluating results. Unlike classification, we can't simply measure accuracy. Instead, we use metrics like silhouette score that measure how well-separated clusters are, or domain knowledge to assess whether discovered groups are meaningful.

This chapter covers:

  • K-Means: Fast partitioning algorithm that iteratively assigns points to nearest centroids
  • Hierarchical: Bottom-up or top-down methods that produce dendrograms showing cluster relationships
  • DBSCAN: Density-based algorithm that finds clusters of any shape and identifies noise points
  • Evaluation: Metrics like silhouette score and methods like the elbow plot to assess clustering quality

Chapter Roadmap

Click any topic to jump in

Interactive demo
1
K-Means Clustering

Partition data into K spherical clusters by iterating between point assignment and centroid updates.

AlgorithmInertia (WCSS)Choosing KLimitations
Beyond spherical clusters

Hierarchical structure and arbitrary-shape density clusters

2
Hierarchical Clustering

Build a dendrogram by progressively merging clusters — cut at any level for different granularities.

Agglomerative ClusteringLinkage MethodsDendrogramAdvantages
3
DBSCAN

Find clusters of arbitrary shape using density, and automatically identify noise points as outliers.

Core PointsBorder PointsNoise PointsParameters

Topics

3 topics in this chapter

The previous chapter, Support Vector Machines, closed the book on supervised learning for now: every algorithm so far learned from labeled examples. Often there are no labels at all. A retailer has millions of purchase histories but no list of customer types; a biologist has gene expression profiles but no known cell categories. Can an algorithm discover groups on its own, using nothing but the similarity between points? This chapter, Clustering, studies that question with three families of methods that define a cluster in very different ways.

K-Means, the oldest and most widely used, defines a cluster by its center: every point belongs to the nearest of K centroids. This topic starts with the algorithm itself, Lloyd's alternation between assigning points and moving centers. We then define inertia, the within-cluster sum of squares that K-Means minimizes, and use it with the silhouette score to choose K. The topic closes with the method's limitations, including its sensitivity to initialization and its preference for round, equally sized clusters.

Definition

K-Means clustering partitions nn points into KK clusters by choosing centroids μ1,…,μK\mu_1, \ldots, \mu_K and an assignment c(i)c(i) of each point that together minimize the total within-cluster sum of squared distances from each point to its own centroid, ∑i∥xi−μc(i)∥2\sum_i \lVert x_i - \mu_{c(i)} \rVert^2. Lloyd's algorithm finds a local minimum by alternating nearest-centroid assignment and centroid averaging.

In this topic

  1. 1Algorithm
  2. 2Inertia (WCSS)
  3. 3Choosing K
  4. 4Limitations
1 of 4
Algorithm

Lloyd's algorithm alternates two steps. Assignment: give each point to its nearest centroid, measured by Euclidean distance. Update: move each centroid to the mean of the points assigned to it. Each step can only lower or keep the objective, the total squared distance from points to their centroids, so the algorithm converges, usually in a few dozen iterations, each costing O(nKd)O(nKd) for nn points in dd dimensions. It converges to a local minimum, not necessarily the global one, so the starting centroids matter. Random initialization can place two centroids in one true cluster; k-means++ spreads the starting centroids out and is scikit-learn's default.

Mathematical Intuition

K-Means alternates between two steps that each reduce the objective J=∑i=1n∣∣xi−μc(i)∣∣2J = \sum_{i=1}^{n}||x_i - \mu_{c(i)}||^2. The assignment step finds the optimal cluster for each point given fixed centroids (minimum distance). The update step finds the optimal centroid for each cluster given fixed assignments (the mean). Since each step decreases or maintains JJ, and JJ is bounded below by 0, the algorithm must converge. However, it converges to a local minimum — the result depends on initialization, which is why K-Means++ matters.

Example:

K=2, centroids μ₁=(0,0), μ₂=(5,5). Point x=(1,2). Which cluster does it belong to?

2 of 4
Inertia (WCSS)

∑i=1n∣∣xi−μc(i)∣∣2\sum_{i=1}^{n} ||x_i - \mu_{c(i)}||^2

Inertia, also called the within-cluster sum of squares (WCSS), adds up the squared distance from every point to its assigned centroid: the formula above, where μc(i)\mu_{c(i)} is the centroid of point ii's cluster. It is exactly the objective K-Means minimizes, and lower means tighter clusters. Two cautions. First, inertia always falls as K grows, reaching zero when every point is its own cluster, so it cannot pick K by itself. Second, squaring makes it sensitive to outliers: one far point can pull a centroid toward it. Inertia also depends on feature scale, so standardize features before clustering, as with SVMs.

Mathematical Intuition

Inertia J=∑i=1n∣∣xi−μc(i)∣∣2J = \sum_{i=1}^{n}||x_i - \mu_{c(i)}||^2 is the total within-cluster sum of squares. It decomposes as J=TSS−BSSJ = \text{TSS} - \text{BSS}, where TSS is the total scatter and BSS is the between-cluster scatter. Minimizing inertia is equivalent to maximizing BSS — pushing clusters apart. The inertia always decreases with KK (adding a cluster center can only reduce distances), reaching 0 when K=nK = n. This monotonic decrease is why the elbow method looks for diminishing returns rather than an absolute minimum.

Example:

Cluster 1: points {(0,0), (1,1)}, centroid (0.5, 0.5). Calculate inertia for this cluster.

3 of 4
Choosing K

Because inertia always decreases with K, choosing K needs a different criterion. The elbow method plots inertia against K and picks the point where further clusters stop paying off. It is subjective, and many datasets show no clear elbow. The silhouette score is more principled: for each point, aa is the mean distance to points in its own cluster and bb the mean distance to points in the nearest other cluster, and s=(b−a)/max⁡(a,b)s = (b - a)/\max(a, b) ranges from −1-1 to 11. Average it over points and pick the K with the highest value. The gap statistic compares inertia with that of random data. Domain knowledge often matters most.

Mathematical Intuition

The elbow method plots inertia J(K)J(K) versus KK and identifies the point of maximum curvature. Mathematically, this is where the second derivative J′′(K)J''(K) is maximized — the transition from steep decline to gradual decline. The silhouette score s(i)=(b(i)−a(i))/max⁡(a(i),b(i))s(i) = (b(i) - a(i))/\max(a(i), b(i)) provides a complementary view: a(i)a(i) is the mean intra-cluster distance (cohesion) and b(i)b(i) is the mean nearest-cluster distance (separation). Values near +1+1 indicate well-clustered points; near 00 means boundary points; near −1-1 means likely misassigned.

Example:

Inertia values: K=1→1000, K=2→400, K=3→350, K=4→340, K=5→335. Where's the elbow?

4 of 4
Limitations

K-Means makes strong implicit assumptions. Assigning each point to its nearest centroid splits space into convex regions, so clusters are effectively assumed to be round, similar in size, and similar in spread. Elongated, ring-shaped, or crescent clusters get cut apart, and a dense small cluster next to a sparse large one is mishandled. K must be chosen in advance. Results depend on initialization, which is why scikit-learn runs several starts and keeps the best. Every point must belong to some cluster, so outliers distort centroids. Gaussian mixture models relax the shape assumption, and DBSCAN, later in this chapter, handles arbitrary shapes and noise.

Mathematical Intuition

K-Means assumes clusters are isotropic Gaussians (spherical, equal variance). The Voronoi cell assignment c(i)=arg⁡min⁡k∣∣xi−μk∣∣2c(i) = \arg\min_k ||x_i - \mu_k||^2 creates convex, polygonal decision boundaries — it cannot capture non-convex cluster shapes like crescents or rings. The objective ∑∣∣xi−μc(i)∣∣2\sum||x_i - \mu_{c(i)}||^2 treats all directions equally, so elongated clusters get split along their major axis. For non-spherical clusters, consider Gaussian Mixture Models (which model covariance) or density-based methods like DBSCAN.

Example:

Data has two crescent-moon shaped clusters. Will K-Means work with K=2?

Theory Exercise

Problem:

K-Means is run twice on the same data with different random initializations and produces two noticeably different clusterings with different inertia values. Why does this happen, and how would you make the result more reliable?

Hints:
  • What kind of minimum does K-Means converge to?
  • How does the starting position of centroids affect the outcome?
  • What does scikit-learn's n_init parameter do, and what is K-Means++?

Coding Exercise

Problem:

Generate three blob clusters, then use the elbow method (inertia vs K) and the silhouette score to confirm the correct number of clusters. Print the inertia and silhouette for K = 2..6.

Hints:
  • make_blobs(n_samples=..., centers=3) gives a labeled-looking dataset, but cluster on X only
  • Loop K from 2 to 6, fit KMeans(n_clusters=K, n_init=10, random_state=0), record km.inertia_
  • silhouette_score(X, km.labels_) measures separation — the best K maximizes it