PIXELBANKv9.1.0
Menu
Back to ML Study Plan
Week 15-16

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

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

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

1Algorithm
2Inertia (WCSS)
3Choosing K
4Limitations
1 of 4
Algorithm
  1. Initialize K centroids randomly. 2) Assign each point to nearest centroid. 3) Update centroids to mean of assigned points. 4) Repeat until convergence.
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

Within-cluster sum of squares. Lower is better, but decreases with more clusters.

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

Elbow method: plot inertia vs K, pick the 'elbow'. Silhouette score: higher is better (-1 to 1).

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

Assumes spherical clusters, sensitive to initialization and outliers, must specify K in advance.

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