Chapter 8: Clustering
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.
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
K-Means Clustering
Partition data into K spherical clusters by iterating between point assignment and centroid updates.
Hierarchical structure and arbitrary-shape density clusters
Hierarchical Clustering
Build a dendrogram by progressively merging clusters — cut at any level for different granularities.
DBSCAN
Find clusters of arbitrary shape using density, and automatically identify noise points as outliers.
K-Means partitions data into K clusters by iteratively assigning points to the nearest centroid and updating centroids to be the mean of assigned points.
Key assumption: Clusters are spherical and roughly equal-sized.
In this topic
Algorithm
- Initialize K centroids randomly. 2) Assign each point to nearest centroid. 3) Update centroids to mean of assigned points. 4) Repeat until convergence.
K-Means alternates between two steps that each reduce the objective . 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 , and 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.
K=2, centroids μ₁=(0,0), μ₂=(5,5). Point x=(1,2). Which cluster does it belong to?
Inertia (WCSS)
Within-cluster sum of squares. Lower is better, but decreases with more clusters.
Inertia is the total within-cluster sum of squares. It decomposes as , 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 (adding a cluster center can only reduce distances), reaching 0 when . This monotonic decrease is why the elbow method looks for diminishing returns rather than an absolute minimum.
Cluster 1: points {(0,0), (1,1)}, centroid (0.5, 0.5). Calculate inertia for this cluster.
Choosing K
Elbow method: plot inertia vs K, pick the 'elbow'. Silhouette score: higher is better (-1 to 1).
The elbow method plots inertia versus and identifies the point of maximum curvature. Mathematically, this is where the second derivative is maximized — the transition from steep decline to gradual decline. The silhouette score provides a complementary view: is the mean intra-cluster distance (cohesion) and is the mean nearest-cluster distance (separation). Values near indicate well-clustered points; near means boundary points; near means likely misassigned.
Inertia values: K=1→1000, K=2→400, K=3→350, K=4→340, K=5→335. Where's the elbow?
Limitations
Assumes spherical clusters, sensitive to initialization and outliers, must specify K in advance.
K-Means assumes clusters are isotropic Gaussians (spherical, equal variance). The Voronoi cell assignment creates convex, polygonal decision boundaries — it cannot capture non-convex cluster shapes like crescents or rings. The objective 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.
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
Related Problems on PixelBank
Hierarchical clustering builds a tree (dendrogram) of clusters. You can cut the tree at any level to get different numbers of clusters.
Two approaches: Agglomerative (bottom-up, most common) and Divisive (top-down).
In this topic
Agglomerative Clustering
Start with each point as its own cluster. Iteratively merge the two closest clusters until one remains.
Agglomerative clustering starts with singleton clusters and performs merges. At each step, it merges the two closest clusters according to a linkage criterion, producing a binary tree (dendrogram). The time complexity is for naive implementation or with a priority queue. Unlike K-Means, it does not require specifying upfront — the full hierarchy encodes all possible values from 1 to , and any specific clustering is obtained by cutting the dendrogram at the appropriate height.
4 points: A, B, C, D. Distances: d(A,B)=2, d(A,C)=5, d(B,C)=3, d(C,D)=1. What merges first?
Linkage Methods
Single: min distance between clusters. Complete: max distance. Average: mean distance. Ward: minimizes variance increase.
Single linkage uses — it can find elongated, chain-like clusters but is sensitive to noise bridges between clusters (chaining effect). Complete linkage uses — it produces compact, spherical clusters but is sensitive to outliers. Ward's method minimizes the total within-cluster variance increase — it is equivalent to K-Means in the sense that it optimizes the same inertia objective, but in a greedy, hierarchical fashion.
Cluster X={A,B}, Cluster Y={C}. d(A,C)=3, d(B,C)=7. What's distance using single vs complete linkage?
Dendrogram
Tree visualization showing merge order and distances. Cut horizontally to get K clusters.
The dendrogram is a tree where each internal node represents a merge event at distance (height) . A horizontal cut at height produces a clustering with clusters, where is the number of branches crossing the cut line. Large vertical gaps in the dendrogram indicate natural cluster separations — the optimal cut is typically at the largest gap. The cophenetic distance between two points is the height at which they first merge; the cophenetic correlation between pairwise distances and cophenetic distances measures how well the dendrogram preserves the original distance structure.
Dendrogram has horizontal cut options at heights 5, 15, and 30. Height 5 gives 4 clusters, height 15 gives 2. What does height 30 give?
Advantages
No need to specify K upfront. Produces interpretable hierarchy. Works with any distance metric.
Hierarchical clustering produces a complete hierarchy of nested clusterings — a richer output than any flat clustering method. The dendrogram reveals multi-scale structure: cutting at different heights yields different granularities. It works with any distance metric (not just Euclidean), making it applicable to domains with custom similarity measures like edit distance for strings or Jaccard distance for sets. The deterministic nature (no random initialization) means results are reproducible without multiple restarts.
You're clustering species by genetic similarity. Why might hierarchical clustering be ideal?
Theory Exercise
Problem:
You run agglomerative clustering on the same dataset with single linkage and with complete linkage and get very different dendrograms — single linkage produces one giant straggly cluster while complete linkage gives compact balls. Explain why, and when each linkage is appropriate.
Hints:
- How does single linkage define the distance between two clusters?
- What is the 'chaining effect'?
- Which linkage favors compact clusters and which favors elongated ones?
Coding Exercise
Problem:
Run agglomerative clustering with Ward linkage on a blob dataset and reproduce the merge structure as a dendrogram using scipy's linkage and dendrogram functions. Cut the tree into 3 clusters and report the cluster sizes.
Hints:
- scipy.cluster.hierarchy.linkage(X, method='ward') returns the merge matrix Z
- fcluster(Z, t=3, criterion='maxclust') cuts the tree into a fixed number of clusters
- np.bincount on the resulting labels gives the size of each cluster
DBSCAN (Density-Based Spatial Clustering of Applications with Noise) finds clusters of arbitrary shape by grouping points in dense regions and marking sparse points as noise.
Key advantage: Automatically detects outliers and doesn't require specifying K.
In this topic
Core Points
Points with at least minPts neighbors within distance ε. These form the 'core' of clusters.
A core point has at least points within its -neighborhood: , where . Core points anchor cluster expansion — they sit in dense regions and pull nearby points into their cluster. The density threshold is in 2D (or in -D where is the volume of a -ball). Points that are density-reachable from a core point (connected through a chain of core points) belong to the same cluster.
ε=1, minPts=3. Point A has 4 neighbors within distance 1. Point B has 2 neighbors. Which are core points?
Border Points
Points within ε of a core point but don't have minPts neighbors. Part of a cluster but on the edge.
Border points are within of at least one core point but have fewer than neighbors themselves: but core point with . They sit on the periphery of dense regions. Border points can be density-reachable from multiple core points in different clusters — DBSCAN assigns them to the first cluster discovered during traversal, making border point assignment non-deterministic (order-dependent). This is the only source of non-determinism in DBSCAN.
Point B (2 neighbors) is within ε of core point A. What is B's classification?
Noise Points
Points that are neither core nor border. Marked as outliers (label = -1).
Noise points are neither core nor border: they are not within of any core point. DBSCAN labels them as , effectively treating them as outliers. The fraction of noise points depends on the density threshold set by . This built-in outlier detection is a major advantage over K-Means and hierarchical clustering, which force every point into a cluster. The noise fraction can serve as a diagnostic: too many noise points suggests is too small or is too large.
Point C is isolated—no points within ε. What happens to C?
Parameters
ε (eps): neighborhood radius. minPts: minimum points for core.
Smaller ε = more clusters, more noise. Larger minPts = fewer, denser clusters.
The parameters jointly define the density threshold. The k-distance plot (sort distances to the -th nearest neighbor in descending order) helps choose : the elbow corresponds to the boundary between dense clusters and sparse noise. The recommended for this plot. A common heuristic sets (dimensionality + 1) to ensure the density estimate is robust. DBSCAN's main limitation is a single global — it cannot handle clusters with varying densities. HDBSCAN addresses this by running DBSCAN over all values and extracting the most persistent clusters.
ε=0.5 gives 10 clusters, 50 noise points. ε=2.0 gives 2 clusters, 5 noise points. What trade-off are we seeing?
Theory Exercise
Problem:
Your dataset has varying densities: one tight cluster and one sparse cluster. Which clustering algorithm would work best and why?
Hints:
- Consider how each algorithm handles density
- What does DBSCAN assume about density?
- Think about parameter sensitivity
Coding Exercise
Problem:
Generate two interleaving half-moons and cluster them with DBSCAN, showing that it recovers the non-convex shapes that K-Means cannot. Print the number of clusters found and how many points were labeled as noise.
Hints:
- make_moons(n_samples=..., noise=0.06) creates two crescent shapes
- DBSCAN(eps=0.2, min_samples=5).fit_predict(X) returns labels, with -1 meaning noise
- Count clusters as the number of unique labels excluding -1; noise count is (labels == -1).sum()