Classical MLClustering (K-Means, DBSCAN, GMM)

Clustering (K-Means, DBSCAN, GMM)

Background
  • 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)
The Concept

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.

How it Links
  • 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)
Concrete Example
Segmenting retail customers by purchase behavior: clustering naturally finds groups like frequent-small-buyers, infrequent-big-buyers, and one-time-gift-buyers without any labels. Each cluster gets a targeted marketing strategy.
Learning outcomes
  • 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

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 kk upfront. K-Means++ [3] seeds centroids with probability proportional to squared distance from the current set, giving an O(log⁡k)O(\log k) 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 kk 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 kk 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 is hard-EM on an isotropic Gaussian mixture

K-Means falls out of the EM derivation for Gaussian mixtures in the limit Σk=σ2I\Sigma_k = \sigma^2 I with σ→0\sigma \to 0. The E-step posterior γik=πkN(xi∣μk,σ2I)/Zi\gamma_{ik} = \pi_k \mathcal{N}(x_i \mid \mu_k, \sigma^2 I) / Z_i 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 {xi}i=1n⊂Rd\{x_i\}_{i=1}^{n} \subset \mathbb{R}^{d}, partition the indices into kk disjoint sets C1,…,CkC_1, \dots, C_k with centroids μ1,…,μk\mu_1, \dots, \mu_k. The within-cluster sum of squares (SSE, also called inertia) is

J(C,μ)=∑k=1K∑i∈Ck∥xi−μk∥22.J(C, \mu) = \sum_{k=1}^{K} \sum_{i \in C_k} \lVert x_i - \mu_k \rVert_2^{2}.

The K-Means problem is

min⁡C,μ  J(C,μ).\min_{C, \mu}\; J(C, \mu).

This is NP-hard in general (even for fixed d≥2d \ge 2 and arbitrary kk, or fixed k=2k = 2 and arbitrary dd).

Lloyd’s algorithm as coordinate descent

Lloyd’s algorithm [1] alternates two block updates:

Assignment step (fix μ\mu, optimize CC). Assign each point to the cluster of its nearest centroid:

Ck={i:k=arg⁡min⁡j∥xi−μj∥22}.C_k = \{ i : k = \arg\min_{j} \lVert x_i - \mu_j \rVert_2^{2} \}.

Update step (fix CC, optimize μ\mu). Set μk\mu_k to the centroid of cluster kk:

μk=1∣Ck∣∑i∈Ckxi.\mu_k = \frac{1}{|C_k|} \sum_{i \in C_k} x_i.

Monotone decrease

Each step weakly decreases JJ:

  • The assignment step minimizes JJ over CC with μ\mu fixed, by definition.
  • For the update step, ∑i∈Ck∥xi−μk∥2\sum_{i \in C_k} \lVert x_i - \mu_k \rVert^{2} is a strictly convex quadratic in μk\mu_k whose minimizer is the cluster mean.

Since J≥0J \ge 0 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: O(nkd)O(nkd) 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 D(x)D(x) denote the distance from a point xx to the nearest already-chosen centroid.

  1. Choose c1c_1 uniformly at random from the data.
  2. For j=2,…,kj = 2, \dots, k: choose cj=xic_j = x_i with probability proportional to D(xi)2D(x_i)^{2}.
  3. 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 D2D^{2} (rather than DD) 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 8(ln⁡k+2)8(\ln k + 2) of the optimal SSE:

E ⁣[Jkmeans++]≤8(ln⁡k+2) J⋆.\mathbb{E}\!\left[J_{\text{kmeans++}}\right] \le 8(\ln k + 2)\, J^{\star}.

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 KK components is

p(x)=∑k=1Kπk N(x∣μk,Σk),∑k=1Kπk=1,    πk≥0.p(x) = \sum_{k=1}^{K} \pi_k\, \mathcal{N}(x \mid \mu_k, \Sigma_k), \quad \sum_{k=1}^{K} \pi_k = 1, \;\; \pi_k \ge 0.

Introduce a latent indicator zi∈{1,…,K}z_i \in \{1, \dots, K\} for each xix_i with p(zi=k)=πkp(z_i = k) = \pi_k and p(xi∣zi=k)=N(xi∣μk,Σk)p(x_i \mid z_i = k) = \mathcal{N}(x_i \mid \mu_k, \Sigma_k). The complete-data log-likelihood is

log⁡p(x,z∣θ)=∑i=1n∑k=1K1[zi=k] [log⁡πk+log⁡N(xi∣μk,Σk)],\log p(x, z \mid \theta) = \sum_{i=1}^{n} \sum_{k=1}^{K} \mathbb{1}[z_i = k]\, \bigl[\log \pi_k + \log \mathcal{N}(x_i \mid \mu_k, \Sigma_k)\bigr],

with θ={πk,μk,Σk}k=1K\theta = \{\pi_k, \mu_k, \Sigma_k\}_{k=1}^{K}.

The evidence lower bound

For any distribution q(z)q(z) over the latents, Jensen’s inequality gives

log⁡p(x∣θ)=log⁡∑zp(x,z∣θ)≥Eq(z) ⁣[log⁡p(x,z∣θ)]−Eq(z) ⁣[log⁡q(z)]  =:  F(q,θ).\log p(x \mid \theta) = \log \sum_{z} p(x, z \mid \theta) \ge \mathbb{E}_{q(z)}\!\bigl[\log p(x, z \mid \theta)\bigr] - \mathbb{E}_{q(z)}\!\bigl[\log q(z)\bigr] \;=:\; \mathcal{F}(q, \theta).

F\mathcal{F} is the evidence lower bound (ELBO). The slack equals KL⁡(q ∥ p(z∣x,θ))≥0\operatorname{KL}(q \,\|\, p(z \mid x, \theta)) \ge 0, with equality when q=p(z∣x,θ)q = p(z \mid x, \theta).

E-step

Maximize F(q,θ)\mathcal{F}(q, \theta) over qq with θ\theta fixed. The bound is tight when qq equals the posterior, so set

q(zi=k)=γik=πk N(xi∣μk,Σk)∑j=1Kπj N(xi∣μj,Σj).q(z_i = k) = \gamma_{ik} = \frac{\pi_k\, \mathcal{N}(x_i \mid \mu_k, \Sigma_k)}{\sum_{j=1}^{K} \pi_j\, \mathcal{N}(x_i \mid \mu_j, \Sigma_j)}.

These are the responsibilities: the posterior probability that point ii was generated by component kk.

M-step

With qq fixed at the responsibilities, maximize F(q,θ)\mathcal{F}(q, \theta) over θ\theta. The dependence on θ\theta is

Q(θ)=Eq[log⁡p(x,z∣θ)]=∑i=1n∑k=1Kγik [log⁡πk+log⁡N(xi∣μk,Σk)].Q(\theta) = \mathbb{E}_q\bigl[\log p(x, z \mid \theta)\bigr] = \sum_{i=1}^{n} \sum_{k=1}^{K} \gamma_{ik}\, \bigl[\log \pi_k + \log \mathcal{N}(x_i \mid \mu_k, \Sigma_k)\bigr].

Setting partial derivatives to zero (with the Lagrange multiplier for ∑kπk=1\sum_k \pi_k = 1) gives weighted-MLE updates:

Nk=∑i=1nγik,πk=Nkn,N_k = \sum_{i=1}^{n} \gamma_{ik}, \qquad \pi_k = \frac{N_k}{n},μk=1Nk∑i=1nγik xi,Σk=1Nk∑i=1nγik (xi−μk)(xi−μk)⊤.\mu_k = \frac{1}{N_k} \sum_{i=1}^{n} \gamma_{ik}\, x_i, \qquad \Sigma_k = \frac{1}{N_k} \sum_{i=1}^{n} \gamma_{ik}\, (x_i - \mu_k)(x_i - \mu_k)^\top.

Monotone increase of the ELBO

After the E-step, F(q,θ)=log⁡p(x∣θ)\mathcal{F}(q, \theta) = \log p(x \mid \theta) (the bound is tight). After the M-step, θ\theta changes to maximize F\mathcal{F} at fixed qq, so F\mathcal{F} does not decrease. Therefore

log⁡p(x∣θnew)≥F(q,θnew)≥F(q,θold)=log⁡p(x∣θold).\log p(x \mid \theta_{\text{new}}) \ge \mathcal{F}(q, \theta_{\text{new}}) \ge \mathcal{F}(q, \theta_{\text{old}}) = \log p(x \mid \theta_{\text{old}}).

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 σ→0\sigma \to 0

Take Σk=σ2I\Sigma_k = \sigma^2 I with σ→0\sigma \to 0. Then N(xi∣μk,σ2I)∝exp⁡(−∥xi−μk∥2/2σ2)\mathcal{N}(x_i \mid \mu_k, \sigma^2 I) \propto \exp(-\lVert x_i - \mu_k \rVert^2 / 2\sigma^2), and the responsibility γik\gamma_{ik} collapses to the indicator 1[k=arg⁡min⁡j∥xi−μj∥2]\mathbb{1}[k = \arg\min_j \lVert x_i - \mu_j \rVert^2]. 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 ϵ\epsilon and a minimum count m=minPtsm = \mathrm{minPts}.

  • Core point. A point xx is core if its ϵ\epsilon-neighborhood contains at least mm points (including itself): ∣Nϵ(x)∣≥m|N_\epsilon(x)| \ge m.
  • Directly density-reachable. yy is directly density-reachable from xx if xx is a core point and y∈Nϵ(x)y \in N_\epsilon(x).
  • Density-reachable. yy is density-reachable from xx if there is a chain of core points x=p0,p1,…,pℓ=yx = p_0, p_1, \dots, p_\ell = y with each pi+1p_{i+1} directly density-reachable from pip_i.
  • Density-connected. xx and yy are density-connected if there exists a core point zz 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

  1. For each unvisited point xx: count its ϵ\epsilon-neighbors. If at most m−1m - 1, label noise (provisionally) and continue.
  2. Otherwise mark xx as the next cluster id and BFS-expand the neighborhood: any neighbor that is itself a core point contributes its own neighbors.
  3. 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

  • ϵ\epsilon: the most sensitive parameter. The k-distance plot (sort the distances to the mm-th nearest neighbor and look for the elbow) is the standard heuristic.
  • minPts: typically ≥d+1\ge d + 1; many practitioners use m=2dm = 2 d as a starting point.
  • Limitation: variable density. A single ϵ\epsilon 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]:

  1. Start with each point as its own cluster.
  2. Merge the two clusters with the smallest linkage distance.
  3. Repeat until one cluster remains.

Cutting the dendrogram at any height yields a flat partition. Linkage choices:

LinkageDistanceTendencyNotes
Singlemin over cross-cluster pairschains: long, snake-like clustersSensitive to noise; can chain through outliers.
Completemax over cross-cluster pairscompact, ball-like clustersLess prone to chaining; biased toward equal diameters.
Average (UPGMA)mean over cross-cluster pairsbetween single and completeCommon default in bioinformatics.
Wardincrease in within-cluster SSE on mergespherical clusters of similar sizeEquivalent to minimizing the K-Means objective greedily; only valid for Euclidean distance.

Hierarchical clustering is O(n2)O(n^2) memory (the full distance matrix) and O(n2log⁡n)O(n^2 \log n) to O(n3)O(n^3) 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:

  1. Build a similarity graph (often a kk-nearest-neighbor or RBF-weighted graph) with affinity matrix WW.
  2. Compute the symmetric normalized Laplacian Lsym=I−D−1/2WD−1/2L_{\mathrm{sym}} = I - D^{-1/2} W D^{-1/2}, where DD is the diagonal degree matrix.
  3. Stack the bottom kk eigenvectors of LsymL_{\mathrm{sym}} as columns of U∈Rn×kU \in \mathbb{R}^{n \times k}.
  4. Normalize each row of UU to unit length.
  5. Run K-Means on the rows of UU.

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 kk

Without labels, “the right kk” is ill-defined. The three standard scores:

MetricRangeHigher = better?How it works
Silhouette score[-1, 1]yesFor 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)yesCompare 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 kk 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

PropertyK-MeansGMM (full Sigma)DBSCANHierarchical (Ward)
Assumed cluster shapespherical, equal varianceellipsoidal (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 thousandsno (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?yesyesno (eps + minPts)no (cut at any height)
Hyperparametersk, init, n_initk, covariance type, reg covareps, minPtslinkage, 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.

python
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))
About 30 lines including K-Means++ seeding. Production code uses Cython inner loops and a tolerance-based stopping rule.

Run sklearn’s K-Means live on a synthetic 3-blob dataset and inspect the cluster centers and inertia:

Idle (packages: numpy, scikit-learn)
(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 ϵ\epsilon is too small, and how GMM with kk greater than 3 wastes a component on the densest blob.

Clustering demo (3 overlapping Gaussian blobs, n = 60)
clusters = 3

Real-world uses

DomainUseWhy this family
Marketing / business analyticsCustomer segmentation by RFM (recency, frequency, monetary value)K-Means on standardized RFM features is the textbook recipe; segments are interpretable as centroid descriptions.
Computer visionSuperpixel 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 detectionIdentifying low-density points (label = -1) as suspiciousDBSCAN is the only mainstream clusterer that natively returns a noise label, which is the anomaly score.
Topic discoveryClustering document embeddingsDensity-based or spectral methods handle the non-spherical clusters that emerge in high-dimensional embedding spaces.
AstronomyIdentifying stellar populations and galaxy clusters from photometric surveysGMMs with full covariance capture elongated stellar streams; DBSCAN extracts dense substructure.

Pitfalls

K-Means assumes spherical clusters of comparable size

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.

DBSCAN is sharply sensitive to (eps, minPts)

A single global ϵ\epsilon 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 ϵ\epsilon is a starting point, not a final answer. When density varies across the data, switch to OPTICS or HDBSCAN, which adapt the radius locally.

GMM can collapse to a single point (singular covariance)

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: Σk←Σk+λI\Sigma_k \leftarrow \Sigma_k + \lambda I with λ\lambda around 10−610^{-6} to 10−310^{-3} (sklearn’s reg_covar). It is cheap insurance and should be on by default.

Always StandardScale before clustering on Euclidean distance

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

Check yourself
Score: 0 / 5(0 answered)
  1. 1. Why does Lloyd's algorithm converge in finitely many steps?
  2. 2. In the EM algorithm for a Gaussian mixture, what does the responsibility gamma_ik represent?
  3. 3. Which property does DBSCAN have that K-Means does not?
  4. 4. Why is K-Means called the hard-EM limit of an isotropic Gaussian mixture?
  5. 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. J(C,μ)=∑k∑i∈Ck∥xi−μk∥2J(C, \mu) = \sum_{k} \sum_{i \in C_k} \lVert x_i - \mu_k \rVert^{2}, jointly over assignments CC and centroids μ\mu.

Block 1 (assignments). Fix μ\mu. The objective decomposes per point: J=∑imin⁡k∥xi−μk∥2+slackJ = \sum_i \min_k \lVert x_i - \mu_k \rVert^{2} + \text{slack}, minimized by assigning each xix_i to its closest centroid. So the assignment step minimizes JJ over CC exactly.

Block 2 (centroids). Fix CC. For each cluster kk, ∑i∈Ck∥xi−μk∥2\sum_{i \in C_k} \lVert x_i - \mu_k \rVert^{2} is strictly convex in μk\mu_k with minimizer μk=(1/∣Ck∣)∑i∈Ckxi\mu_k = (1 / |C_k|) \sum_{i \in C_k} x_i. So the update step minimizes JJ over μ\mu exactly.

Convergence. Each block update weakly decreases JJ, and there are at most knk^n 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. JJ is non-convex jointly in (C,μ)(C, \mu), 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 q(z)q(z), Jensen gives

log⁡p(x∣θ)≥Eq[log⁡p(x,z∣θ)]−Eq[log⁡q(z)]=:F(q,θ).\log p(x \mid \theta) \ge \mathbb{E}_q[\log p(x, z \mid \theta)] - \mathbb{E}_q[\log q(z)] =: \mathcal{F}(q, \theta).

The slack equals KL⁡(q ∥ p(z∣x,θ))\operatorname{KL}(q \,\|\, p(z \mid x, \theta)).

E-step. Maximize F\mathcal{F} over qq at fixed θ\theta. The KL gap is zero when q=p(z∣x,θ)q = p(z \mid x, \theta), so set

q(zi=k)=γik=πk N(xi∣μk,Σk)∑jπj N(xi∣μj,Σj).q(z_i = k) = \gamma_{ik} = \frac{\pi_k\, \mathcal{N}(x_i \mid \mu_k, \Sigma_k)}{\sum_j \pi_j\, \mathcal{N}(x_i \mid \mu_j, \Sigma_j)}.

M-step. With qq fixed, F(q,θ)=∑i,kγik[log⁡πk+log⁡N(xi∣μk,Σk)]+const\mathcal{F}(q, \theta) = \sum_{i, k} \gamma_{ik} [\log \pi_k + \log \mathcal{N}(x_i \mid \mu_k, \Sigma_k)] + \text{const}. Setting the gradient to zero (with the Lagrange multiplier for ∑kπk=1\sum_k \pi_k = 1) gives

Nk=∑iγik,    πk=Nkn,    μk=1Nk∑iγik xi,    Σk=1Nk∑iγik (xi−μk)(xi−μk)⊤.N_k = \sum_i \gamma_{ik}, \;\; \pi_k = \frac{N_k}{n}, \;\; \mu_k = \frac{1}{N_k}\sum_i \gamma_{ik}\, x_i, \;\; \Sigma_k = \frac{1}{N_k}\sum_i \gamma_{ik}\,(x_i - \mu_k)(x_i - \mu_k)^\top.

Monotonicity. After the E-step the bound is tight: F(q,θ)=log⁡p(x∣θ)\mathcal{F}(q, \theta) = \log p(x \mid \theta). The M-step does not decrease F\mathcal{F}, so log⁡p(x∣θnew)≥log⁡p(x∣θold)\log p(x \mid \theta_{\text{new}}) \ge \log p(x \mid \theta_{\text{old}}). 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 ∑k∑i∈Ck∥xi−μk∥2\sum_k \sum_{i \in C_k} \lVert x_i - \mu_k \rVert^{2} is the negative log-likelihood (up to constants) of a Gaussian mixture with Σk=σ2I\Sigma_k = \sigma^2 I for the same σ\sigma across all kk. The model that K-Means is implicitly fitting therefore says: every cluster is an isotropic Gaussian of the same width. As σ→0\sigma \to 0, 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:

  1. You do not know kk in advance. DBSCAN takes ϵ\epsilon and minPts and discovers however many clusters the density structure supports.
  2. Clusters have arbitrary shape. Two interlocking moons, a ring around a ball, or any density-connected shape works for DBSCAN and breaks K-Means.
  3. You need a noise label. DBSCAN tags low-density points as −1-1 rather than forcing them into the nearest cluster, which is exactly what an anomaly-detection pipeline wants.

DBSCAN’s price: a single ϵ\epsilon struggles when clusters have very different densities (use OPTICS or HDBSCAN), and the tuning is more delicate than K-Means’s kk. But on tabular data with outliers and unknown kk, DBSCAN is the right default [4].

Build it yourself

A weekend exercise to internalize the family:

  1. Implement K-Means from scratch with K-Means++ seeding (about 30 lines, see the numpy CodeCompare block above) and reproduce sklearn’s inertia within rounding on make_blobs.
  2. Add the EM updates for a 2-component isotropic GMM and verify the log-likelihood is monotone non-decreasing across iterations.
  3. Generate two interlocking moons with make_moons(noise=0.05) and confirm K-Means cuts them in half while DBSCAN with ϵ≈0.2\epsilon \approx 0.2 recovers them perfectly.
  4. Run silhouette, Davies-Bouldin, and the gap statistic over k∈{2,…,8}k \in \{2, \dots, 8\} on a 4-blob dataset and confirm all three pick k=4k = 4.

References

  1. Lloyd, S. P. (1982). Least squares quantization in PCM. IEEE Transactions on Information Theory 28(2), 129-137. doi:10.1109/TIT.1982.1056489
  2. 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
  3. 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
  4. 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
  5. 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
  6. 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
  7. 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
  8. 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
  9. Bishop, C. M. (2006). Pattern Recognition and Machine Learning. Springer. ISBN 978-0-387-31073-2
  10. Hastie, T., Tibshirani, R., and Friedman, J. (2009). The Elements of Statistical Learning, 2nd ed.. Springer. https://hastie.su.domains/ElemStatLearn/