Clustering (K-Means, DBSCAN, GMM)
- K-means dates to Stuart Lloyd (1957); hierarchical clustering to Sokal & Sneath (1963)
- Unsupervised learning: no labels needed, structure is discovered from data geometry alone
- Used across biology (gene expression), marketing (customer segmentation), NLP (topic modeling)
Clustering groups data points so that points within a cluster are more similar to each other than to points in other clusters. K-means assigns each point to the nearest centroid and iterates; DBSCAN finds dense regions; hierarchical methods build a tree of nested clusters.
- K-means initialization (k-means++) connects to the theory of coresets and greedy algorithms
- Gaussian mixture models are the probabilistic, soft-assignment version of k-means (EM algorithm)
- Connects to vector quantization (codebooks in image compression and VQ-VAEs)
- Derive K-Means as coordinate descent on the within-cluster sum of squares and explain why it converges to a local optimum.
- Explain K-Means++ seeding and the $O(\log k)$ approximation guarantee it gives in expectation.
- Derive the full EM algorithm for a Gaussian mixture model and prove the ELBO is non-decreasing in each iteration.
- State DBSCAN's density-reachability framework and explain when it succeeds where K-Means fails.
- Pick a clustering algorithm given (cluster shape, scale, presence of noise, whether $k$ is known) and choose $k$ with silhouette, Davies-Bouldin, or the gap statistic.
TL;DR
Clustering is unsupervised partitioning. K-Means [1][2] minimizes the within-cluster sum of squares by alternating assignment and centroid update; it is fast and scales but assumes spherical clusters and requires upfront. K-Means++ [3] seeds centroids with probability proportional to squared distance from the current set, giving an approximation guarantee in expectation. Gaussian Mixture Models [9] generalize K-Means to soft assignments and ellipsoidal clusters; EM [5] alternates an E-step (posterior responsibilities) with an M-step (weighted MLE), monotonically increasing the evidence lower bound. DBSCAN [4] defines clusters as density-connected components, finds arbitrary shapes, and labels low-density points as noise. Hierarchical clustering builds a dendrogram via single, complete, average, or Ward linkage. Spectral clustering [6] embeds points via the eigenvectors of the graph Laplacian and runs K-Means in that space. Choose with silhouette score [7], Davies-Bouldin index, or the gap statistic [8].
Intuition
Three families partition data in three different ways:
- Partitional (K-Means, GMM). Pick representatives (centroids or Gaussians). Assign each point to the closest one. Re-fit the representatives. Repeat. Output: a flat partition of the data.
- Density-based (DBSCAN, OPTICS). A cluster is a maximal region of high point density, separated from other clusters by low-density gaps. Output: clusters of arbitrary shape, plus a “noise” label for points in low-density regions.
- Hierarchical (agglomerative, divisive). Start with each point in its own cluster, repeatedly merge the closest pair (agglomerative); or start with everything together and recursively split (divisive). Output: a tree of nested partitions (dendrogram), readable at any granularity.
K-Means falls out of the EM derivation for Gaussian mixtures in the limit with . The E-step posterior collapses to the indicator of the closest centroid (hard assignment), and the M-step becomes the centroid average. So whenever K-Means looks wrong, the isotropic-Gaussian assumption is the first thing to question: anisotropic clusters need full-covariance GMMs; non-Gaussian shapes need DBSCAN or spectral methods [9].
Math
K-Means as coordinate descent on the SSE objective
Objective
Given , partition the indices into disjoint sets with centroids . The within-cluster sum of squares (SSE, also called inertia) is
The K-Means problem is
This is NP-hard in general (even for fixed and arbitrary , or fixed and arbitrary ).
Lloyd’s algorithm as coordinate descent
Lloyd’s algorithm [1] alternates two block updates:
Assignment step (fix , optimize ). Assign each point to the cluster of its nearest centroid:
Update step (fix , optimize ). Set to the centroid of cluster :
Monotone decrease
Each step weakly decreases :
- The assignment step minimizes over with fixed, by definition.
- For the update step, is a strictly convex quadratic in whose minimizer is the cluster mean.
Since and decreases monotonically, Lloyd’s algorithm converges in finitely many steps (the partition space is finite). But it converges to a local minimum, not the global one. Multiple random restarts and K-Means++ seeding mitigate this.
Complexity
Per iteration: to compute distances and update centroids. Typical iterations to converge: a few dozen. The SciPy / sklearn defaults run K-Means++ then iterate Lloyd until the assignment is stable.
K-Means++: probabilistic seeding with an O(log k) approximation guarantee
Algorithm
Let denote the distance from a point to the nearest already-chosen centroid.
- Choose uniformly at random from the data.
- For : choose with probability proportional to .
- Run Lloyd’s algorithm to convergence with these seeds.
Why the squared distance
Step 2 biases toward points that are poorly covered by the centroids chosen so far. Sampling proportional to (rather than ) matches the SSE objective: it is exactly the loss each point contributes if no further centroid is added.
Approximation guarantee
Arthur and Vassilvitskii [3] proved that the expected SSE of the K-Means++ seeding (before any Lloyd iteration) is within a factor of the optimal SSE:
This is the only widely deployed initialization with a non-trivial approximation guarantee and is the sklearn default (init='k-means++'). Empirically it dominates random seeding on every benchmark.
EM for Gaussian mixture models: full ELBO derivation
The model
A Gaussian mixture model with components is
Introduce a latent indicator for each with and . The complete-data log-likelihood is
with .
The evidence lower bound
For any distribution over the latents, Jensen’s inequality gives
is the evidence lower bound (ELBO). The slack equals , with equality when .
E-step
Maximize over with fixed. The bound is tight when equals the posterior, so set
These are the responsibilities: the posterior probability that point was generated by component .
M-step
With fixed at the responsibilities, maximize over . The dependence on is
Setting partial derivatives to zero (with the Lagrange multiplier for ) gives weighted-MLE updates:
Monotone increase of the ELBO
After the E-step, (the bound is tight). After the M-step, changes to maximize at fixed , so does not decrease. Therefore
EM monotonically increases the data log-likelihood [5][9]. Convergence is to a local maximum; multiple random restarts are standard.
Why K-Means is hard-EM with
Take with . Then , and the responsibility collapses to the indicator . The M-step then becomes the centroid average. So K-Means is the “hard-assignment” limit of EM for an isotropic Gaussian mixture.
DBSCAN: density-based clustering
DBSCAN [4] defines clusters by density rather than centroids, which lets it find arbitrary shapes and label outliers as noise.
Key concepts
Fix two hyperparameters: a radius and a minimum count .
- Core point. A point is core if its -neighborhood contains at least points (including itself): .
- Directly density-reachable. is directly density-reachable from if is a core point and .
- Density-reachable. is density-reachable from if there is a chain of core points with each directly density-reachable from .
- Density-connected. and are density-connected if there exists a core point from which both are density-reachable.
A cluster is a maximal set of density-connected points. A noise point is a non-core point that is not density-reachable from any core point.
Algorithm sketch
- For each unvisited point : count its -neighbors. If at most , label noise (provisionally) and continue.
- Otherwise mark as the next cluster id and BFS-expand the neighborhood: any neighbor that is itself a core point contributes its own neighbors.
- Border points (in some core point’s neighborhood but not core themselves) get the cluster’s id; truly isolated points keep the noise label.
Why it succeeds where K-Means fails
K-Means assumes spherical, equal-variance clusters of comparable size. DBSCAN makes no shape assumption: it finds two interlocking moons, a ring around a ball, or any density-connected shape, and tags the low-density tail as noise rather than forcing it into the nearest cluster.
Practical knobs
- : the most sensitive parameter. The k-distance plot (sort the distances to the -th nearest neighbor and look for the elbow) is the standard heuristic.
- minPts: typically ; many practitioners use as a starting point.
- Limitation: variable density. A single struggles when clusters have very different densities. OPTICS (1999) and HDBSCAN (2013) are the standard fixes.
Hierarchical clustering
Agglomerative hierarchical clustering builds a binary tree (dendrogram) [10]:
- Start with each point as its own cluster.
- Merge the two clusters with the smallest linkage distance.
- Repeat until one cluster remains.
Cutting the dendrogram at any height yields a flat partition. Linkage choices:
| Linkage | Distance | Tendency | Notes |
|---|---|---|---|
| Single | min over cross-cluster pairs | chains: long, snake-like clusters | Sensitive to noise; can chain through outliers. |
| Complete | max over cross-cluster pairs | compact, ball-like clusters | Less prone to chaining; biased toward equal diameters. |
| Average (UPGMA) | mean over cross-cluster pairs | between single and complete | Common default in bioinformatics. |
| Ward | increase in within-cluster SSE on merge | spherical clusters of similar size | Equivalent to minimizing the K-Means objective greedily; only valid for Euclidean distance. |
Hierarchical clustering is memory (the full distance matrix) and to time. It does not scale beyond a few tens of thousands of points, but it is interpretable: the dendrogram is the model.
Spectral clustering
Spectral clustering [6] embeds points via the eigenvectors of the graph Laplacian and runs K-Means in that space. The recipe:
- Build a similarity graph (often a -nearest-neighbor or RBF-weighted graph) with affinity matrix .
- Compute the symmetric normalized Laplacian , where is the diagonal degree matrix.
- Stack the bottom eigenvectors of as columns of .
- Normalize each row of to unit length.
- Run K-Means on the rows of .
The geometry is non-obvious. The Laplacian’s bottom eigenvectors encode the graph’s connected-component structure; on a graph that is almost disconnected (a few weak inter-cluster edges), the bottom eigenvectors are nearly piecewise-constant on the components, so a simple K-Means in spectral space recovers them. Spectral clustering shines on non-convex shapes that defeat K-Means but does not scale to millions of points without approximations.
Cluster validity: choosing
Without labels, “the right ” is ill-defined. The three standard scores:
| Metric | Range | Higher = better? | How it works |
|---|---|---|---|
| Silhouette score | [-1, 1] | yes | For each i: a(i) = mean intra-cluster distance, b(i) = mean nearest-other-cluster distance, s(i) = (b - a) / max(a, b). Average over points. Rousseeuw 1987. |
| Davies-Bouldin index | [0, +inf) | no (lower is better) | For each cluster, compute the worst ratio (sigma_i + sigma_j) / d(c_i, c_j) over j != i, then average. Compact, well-separated clusters score near 0. |
| Gap statistic | (-inf, +inf) | yes | Compare log(W_k) on the data to its expectation under a uniform null reference; pick the smallest k whose gap is within one standard error of the next. Tibshirani-Walther-Hastie 2001. |
In practice run all three over a range of and look for agreement. Silhouette is the cheapest and most popular; the gap statistic has the best statistical justification [7][8].
How the families compare
| Property | K-Means | GMM (full Sigma) | DBSCAN | Hierarchical (Ward) |
|---|---|---|---|---|
| Assumed cluster shape | spherical, equal variance | ellipsoidal (per cluster) | arbitrary (density-connected) | spherical, equal variance |
| Scales to n in the millions? | yes (MiniBatchKMeans) | no (covariance update is O(n d^2)) | with index structures, n in the hundreds of thousands | no (n^2 memory) |
| Finds outliers / noise? | no (forces every point into a cluster) | no (every point gets a soft assignment) | yes (label = -1) | no (cut height is global) |
| Requires k upfront? | yes | yes | no (eps + minPts) | no (cut at any height) |
| Hyperparameters | k, init, n_init | k, covariance type, reg covar | eps, minPts | linkage, distance metric, threshold |
| Deterministic? | no (random init) | no (random init) | no (point ordering affects ties) | yes (given linkage and distance) |
Implementations
The numpy version implements Lloyd’s algorithm from scratch in about 30 lines. The sklearn version is the production default. The MiniBatchKMeans version trades a sliver of accuracy for the ability to fit millions of rows.
import numpy as np
def kmeans(X, k, n_iters=100, seed=0):
"""Lloyd's algorithm with K-Means++ seeding."""
rng = np.random.default_rng(seed)
n, d = X.shape
# K-Means++ seeding
centers = np.empty((k, d))
centers[0] = X[rng.integers(n)]
for j in range(1, k):
d2 = np.min(((X[:, None, :] - centers[:j][None, :, :]) ** 2).sum(-1), axis=1)
probs = d2 / d2.sum()
centers[j] = X[rng.choice(n, p=probs)]
# Lloyd iterations
for _ in range(n_iters):
# Assignment
dists = ((X[:, None, :] - centers[None, :, :]) ** 2).sum(-1)
assign = dists.argmin(axis=1)
# Update
new_centers = np.array([
X[assign == c].mean(axis=0) if (assign == c).any() else centers[c]
for c in range(k)
])
if np.allclose(new_centers, centers):
break
centers = new_centers
inertia = float(((X - centers[assign]) ** 2).sum())
return centers, assign, inertia
rng = np.random.default_rng(0)
X = np.vstack([rng.normal([-2, 0], 0.5, (40, 2)),
rng.normal([+2, 0], 0.5, (40, 2)),
rng.normal([0, 3], 0.5, (40, 2))])
centers, assign, inertia = kmeans(X, k=3)
print("centers:\n", np.round(centers, 2))
print("inertia:", round(inertia, 2))Run sklearn’s K-Means live on a synthetic 3-blob dataset and inspect the cluster centers and inertia:
(no output yet)
Interactive demo
Pick a method (K-Means, DBSCAN, GMM) and a tunable hyperparameter to see how each algorithm partitions three overlapping Gaussian blobs. Note how DBSCAN labels gray points as noise when is too small, and how GMM with greater than 3 wastes a component on the densest blob.
Real-world uses
| Domain | Use | Why this family |
|---|---|---|
| Marketing / business analytics | Customer segmentation by RFM (recency, frequency, monetary value) | K-Means on standardized RFM features is the textbook recipe; segments are interpretable as centroid descriptions. |
| Computer vision | Superpixel image segmentation (SLIC is K-Means in 5-D color + position space) | K-Means scales linearly in n; the spatial constraint keeps clusters compact in pixel space. |
| Anomaly / fraud detection | Identifying low-density points (label = -1) as suspicious | DBSCAN is the only mainstream clusterer that natively returns a noise label, which is the anomaly score. |
| Topic discovery | Clustering document embeddings | Density-based or spectral methods handle the non-spherical clusters that emerge in high-dimensional embedding spaces. |
| Astronomy | Identifying stellar populations and galaxy clusters from photometric surveys | GMMs with full covariance capture elongated stellar streams; DBSCAN extracts dense substructure. |
Pitfalls
The SSE objective is a sum of squared Euclidean distances, which is the log-likelihood of an isotropic Gaussian mixture (up to additive constants). On clusters that are elongated, anisotropic, or wildly different in scale, K-Means will slice them along the wrong axes. If your blobs are not balls, use a full-covariance GMM, DBSCAN, or spectral clustering.
A single global struggles when clusters have very different densities, and minPts that is too small turns every noisy point into its own cluster. The k-distance elbow heuristic for is a starting point, not a final answer. When density varies across the data, switch to OPTICS or HDBSCAN, which adapt the radius locally.
If a component captures only one or two examples, its covariance estimate can
shrink toward zero and the likelihood diverges to infinity. The standard fix
is a small regularization added to the diagonal of every covariance
update: with around
to (sklearn’s reg_covar). It is cheap insurance and
should be on by default.
K-Means, GMM (with full covariance), DBSCAN, and Ward linkage all use
Euclidean distance directly. A feature in millimetres versus one in
kilometres will dominate the distance and silently determine the partition.
Wrap any clusterer in a StandardScaler (or RobustScaler when outliers are
present); the only exception is when the input is already an embedding
trained to be metric-aware.
Pop quiz
- 1. Why does Lloyd's algorithm converge in finitely many steps?
- 2. In the EM algorithm for a Gaussian mixture, what does the responsibility gamma_ik represent?
- 3. Which property does DBSCAN have that K-Means does not?
- 4. Why is K-Means called the hard-EM limit of an isotropic Gaussian mixture?
- 5. You have customer segmentation data with three clearly elongated, anisotropic clusters that K-Means keeps slicing the wrong way. Which method is most likely to recover the true structure?
Interview Q&A
Derive K-Means as coordinate descent on the SSE objective. Does it converge to the global optimum?onsite
Objective. , jointly over assignments and centroids .
Block 1 (assignments). Fix . The objective decomposes per point: , minimized by assigning each to its closest centroid. So the assignment step minimizes over exactly.
Block 2 (centroids). Fix . For each cluster , is strictly convex in with minimizer . So the update step minimizes over exactly.
Convergence. Each block update weakly decreases , and there are at most partitions, so the algorithm visits at most finitely many partitions before repeating. Once it repeats, both blocks are at their per-block optima for the current state and the algorithm has converged.
Globality. is non-convex jointly in , so coordinate descent finds a local minimum. Random restarts and K-Means++ seeding are the standard mitigations [1][3].
Derive the EM algorithm for a Gaussian mixture from the ELBO.research
ELBO. For any , Jensen gives
The slack equals .
E-step. Maximize over at fixed . The KL gap is zero when , so set
M-step. With fixed, . Setting the gradient to zero (with the Lagrange multiplier for ) gives
Monotonicity. After the E-step the bound is tight: . The M-step does not decrease , so . EM monotonically increases the log-likelihood and converges to a local maximum [5][9].
Why does K-Means assume spherical clusters?onsite
The SSE objective is the negative log-likelihood (up to constants) of a Gaussian mixture with for the same across all . The model that K-Means is implicitly fitting therefore says: every cluster is an isotropic Gaussian of the same width. As , the responsibilities harden into the closest-centroid indicator and you recover Lloyd’s algorithm.
That assumption fails on:
- Anisotropic clusters (an elongated shape cannot be captured by a ball). Use a full-covariance GMM.
- Different-scale clusters (a tight blob next to a diffuse one). Use GMM with cluster-specific covariances or DBSCAN.
- Non-Gaussian shapes (concentric rings, half-moons). Use DBSCAN or spectral clustering.
If you ever see K-Means slicing one elongated cluster down the middle, the isotropic-Gaussian assumption is the diagnosis.
When would you reach for DBSCAN over K-Means?phone
Three triggers, any one of which is enough:
- You do not know in advance. DBSCAN takes and minPts and discovers however many clusters the density structure supports.
- Clusters have arbitrary shape. Two interlocking moons, a ring around a ball, or any density-connected shape works for DBSCAN and breaks K-Means.
- You need a noise label. DBSCAN tags low-density points as rather than forcing them into the nearest cluster, which is exactly what an anomaly-detection pipeline wants.
DBSCAN’s price: a single struggles when clusters have very different densities (use OPTICS or HDBSCAN), and the tuning is more delicate than K-Means’s . But on tabular data with outliers and unknown , DBSCAN is the right default [4].
A weekend exercise to internalize the family:
- Implement K-Means from scratch with K-Means++ seeding (about 30 lines, see the numpy
CodeCompareblock above) and reproduce sklearn’s inertia within rounding onmake_blobs. - Add the EM updates for a 2-component isotropic GMM and verify the log-likelihood is monotone non-decreasing across iterations.
- Generate two interlocking moons with
make_moons(noise=0.05)and confirm K-Means cuts them in half while DBSCAN with recovers them perfectly. - Run silhouette, Davies-Bouldin, and the gap statistic over on a 4-blob dataset and confirm all three pick .
References
- Lloyd, S. P. (1982). Least squares quantization in PCM. IEEE Transactions on Information Theory 28(2), 129-137. doi:10.1109/TIT.1982.1056489
- MacQueen, J. (1967). Some methods for classification and analysis of multivariate observations. Proc. 5th Berkeley Symp. on Math. Stat. and Probability, Vol. 1, 281-297. https://projecteuclid.org/euclid.bsmsp/1200512992
- Arthur, D. and Vassilvitskii, S. (2007). k-means++: The advantages of careful seeding. Proc. 18th ACM-SIAM Symposium on Discrete Algorithms (SODA), 1027-1035. doi:10.1145/1283383.1283494
- Ester, M., Kriegel, H.-P., Sander, J., and Xu, X. (1996). A density-based algorithm for discovering clusters in large spatial databases with noise. Proc. 2nd International Conference on Knowledge Discovery and Data Mining (KDD-96), 226-231. https://dl.acm.org/doi/10.5555/3001460.3001507
- Dempster, A. P., Laird, N. M., and Rubin, D. B. (1977). Maximum likelihood from incomplete data via the EM algorithm. Journal of the Royal Statistical Society, Series B, 39(1), 1-38. doi:10.1111/j.2517-6161.1977.tb01600.x
- Ng, A. Y., Jordan, M. I., and Weiss, Y. (2001). On spectral clustering: Analysis and an algorithm. Advances in Neural Information Processing Systems 14 (NeurIPS), 849-856. https://papers.nips.cc/paper/2001/hash/801272ee79cfde7fa5960571fee36b9b-Abstract.html
- Rousseeuw, P. J. (1987). Silhouettes: a graphical aid to the interpretation and validation of cluster analysis. Journal of Computational and Applied Mathematics 20, 53-65. doi:10.1016/0377-0427(87)90125-7
- Tibshirani, R., Walther, G., and Hastie, T. (2001). Estimating the number of clusters in a data set via the gap statistic. Journal of the Royal Statistical Society, Series B, 63(2), 411-423. doi:10.1111/1467-9868.00293
- Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. ISBN 978-0-387-31073-2
- Hastie, T., Tibshirani, R., and Friedman, J. (2009). The Elements of Statistical Learning, 2nd ed.. Springer. https://hastie.su.domains/ElemStatLearn/