Type at least 2 letters. Enter opens the first result, Esc closes.

    learn.mohebi.ai

    Clustering: k-means and Gaussian mixtures

    Watch k-means and the EM algorithm group points step by step. Drag the points, compare k-means++ with a random start, choose the number of clusters with the elbow plot and BIC, and see when k-means fails and what a Gaussian mixture adds.

    Clustering means splitting data points into groups (clusters) so that points in the same group are similar. Nobody gives the algorithm the right groups: there are no labels. This page shows the two classic methods on points in the plane:

    In the first simulation you run both methods one step at a time on data that you can change. In the second one you see the same data clustered by both methods side by side, and you find out when k-means gives the wrong answer. The math behind the pictures is in section 4.

    1. k-means and EM, step by step #

    Interactive figure: loading…

    Press Step again and again, and watch the two steps of k-means. Each data point takes the colour of its cluster (blue, orange, aqua, violet, magenta, yellow for clusters 1 to 6). The large ringed dots are the centres μk\mu_k; the lines behind them are their paths. With k-means the coloured regions are the Voronoi cells: each region holds the places that are closest to one centre. Press New start to see the seeding step by step: with k-means++ the size of a grey dot shows its chance to be picked as the next centre. Switch the method to Gaussian mixture (EM): the ellipses show 1 and 2 standard deviations of each Gaussian, a point's colour mixes the cluster colours with its responsibilities, and the background shows the mixture density. Drag points, click to add points or a whole cloud, and drag a centre to pick your own start. The first chart shows the objective of this run after every step; the second chart is the elbow plot (k-means) or BIC (mixture) for K=1,…,8K = 1, \dots, 8. Click it to change KK.

    2. When k-means fails #

    Interactive figure: loading…

    Move the slider and watch the two clusterings change. The first panel shows k-means, the second a Gaussian mixture fitted with EM. Both get the true number of clusters KK and keep the best of several runs, so a failure is not bad luck. Colours are matched to the true clusters, and a ring marks each point in the wrong cluster. The chart shows the adjusted Rand index (ARI) of both methods against the slider value: 11 means a perfect clustering, about 00 means no better than random groups. Press Show the true clusters to see the answer, and try the other kinds of data.

    3. Try this #

    1. Can the objective go up? Keep blobs and K=4K = 4 and press Step slowly. Question: after an assign step and after an update step, can the inertia JJ (the sum of squared distances from each point to its centre) become larger? What to see: the chart only goes down. After an update step, some points lie in a region of another colour: the next assign step moves exactly these points. Here k-means stops after 2 iterations with J≈180J \approx 180.
    2. A bad start. Set Start to random points and press To the end. Question: do the four centres find the four blobs? What to see: no. Two centres share one blob, and one centre sits between two blobs. k-means stops with J≈578J \approx 578, three times the J≈180J \approx 180 of the good answer, and it never escapes: this is a local minimum. Press New start a few times with both kinds of start. In our runs, random points ended in a worse local minimum in 16 of 40 starts, and k-means++ in 4 of 40. Step through a k-means++ start: the big grey dots (likely picks) are always far from the centres chosen so far.
    3. How many clusters? Look at the elbow plot for blobs. Question: where does the curve bend? What to see: the best inertia drops fast up to K=4K = 4 (2539, 1066, 591, 180) and then slowly (158, 142, …). The bend, the elbow, is at the true K=4K = 4. Now pick rings or elongated: the curve has no clear elbow. Switch the method to Gaussian mixture and read the BIC chart: for blobs and elongated the minimum is at the true KK.
    4. Long clusters. In the second figure, pick elongated and move length / width from 1 to 7. Question: at what point does k-means start to cut across the clusters? What to see: the ARI of k-means falls from 0.980.98 to about 0.450.45 near a ratio of 3.53.5, while the mixture stays near 0.970.97. At the default setting k-means puts 70 points in the wrong cluster, but its inertia (J≈362J \approx 362) is lower than the inertia of the true clusters (J≈616J \approx 616). k-means is not stuck here: its objective prefers the wrong answer. In the first figure, choose elongated, Gaussian mixture, and spherical covariance: with circles only, EM fails like k-means.
    5. One big cluster, two small ones. Pick uneven sizes. Question: which points does k-means give to the wrong cluster? What to see: the outer points of the big cluster, on the side of the small clusters. The true sizes are 180, 30 and 30; k-means finds about 160, 36 and 44. The mixture learns the weights π=(0.75,0.12,0.12)\pi = (0.75, 0.12, 0.12) and a large covariance for the big cluster, and gets every point right. On the chart, the ARI of k-means falls when the spread ratio grows above about 3, while the ARI of the mixture stays near 11 up to a ratio of about 5.5.
    6. Rings. Pick rings. Question: can either method separate the inner ring from the outer one? What to see: no; both ARIs stay near 00 for every radius. The ARI of the mixture is even a little below 00: its clusters agree with the rings a little less than random groups would. A ring is not convex: the straight line between two of its points leaves the ring. A k-means region is always convex, and a Gaussian puts most of its mass near its centre, which here is in the middle of the other ring. In the first figure, the BIC of the mixture on rings keeps falling up to K=7K = 7: the mixture covers each ring with several small Gaussians. That is a good model of the density, but not two clusters.

    4. The math behind the figures #

    k-means minimizes the inertia #

    We have nn points x1,…,xn∈R2x_1, \dots, x_n \in \R^2 and want KK clusters. k-means chooses centres μ1,…,μK\mu_1, \dots, \mu_K and an assignment ai∈{1,…,K}a_i \in \{1, \dots, K\} for each point that make the inertia (the within-cluster sum of squares) small:

    J(μ,a)=∑i=1n∥xi−μai∥2.J(\mu, a) = \sum_{i=1}^n \lVert x_i - \mu_{a_i} \rVert^2 .

    Lloyd's algorithm (the usual k-means algorithm) changes one group of variables at a time:

    Each step minimizes JJ over one group of variables, so JJ never increases. There are only finitely many assignments, and none can repeat with a lower JJ, so the algorithm stops after finitely many steps, when no point changes cluster. But it stops at a local minimum, which depends on the start. Finding the global minimum is NP-hard in general, so in practice we run k-means from several starts and keep the lowest JJ.

    Why the regions are polygons. A place xx is closer to μj\mu_j than to μk\mu_k when ∥x−μj∥2<∥x−μk∥2\lVert x - \mu_j \rVert^2 < \lVert x - \mu_k \rVert^2. Expand both sides; the ∥x∥2\lVert x \rVert^2 terms cancel and we get a linear inequality:

    2(μk−μj)⊤x<∥μk∥2−∥μj∥2.2 (\mu_k - \mu_j)^\top x < \lVert \mu_k \rVert^2 - \lVert \mu_j \rVert^2 .

    So the border between two clusters is a straight line: the perpendicular bisector of the two centres. A Voronoi cell is an intersection of half-planes, so it is a convex polygon. This explains the failures in section 2: k-means cannot follow a ring (not convex), and it puts the border halfway between two centres even when one cluster is much wider than the other (uneven variance). For long clusters, a cut across them gives a lower JJ than the true clusters, so the objective itself prefers the wrong answer.

    Worked example (one dimension). Points 1,2,3,10,11,201, 2, 3, 10, 11, 20 with K=2K = 2 and start centres 11 and 2020.

    Quick check

    Which statement about Lloyd's algorithm is true?

    k-means++: a better start #

    k-means++ (Arthur and Vassilvitskii, 2007) chooses the start centres among the data points. The first centre is a uniformly random point. Each next centre is point xix_i with probability

    P(xi)=D(xi)2∑j=1nD(xj)2,P(x_i) = \frac{D(x_i)^2}{\sum_{j=1}^n D(x_j)^2},

    where D(x)D(x) is the distance from xx to the nearest centre chosen so far. This is D2D^2 sampling: points far from all centres, probably in a cluster without a centre yet, are likely to be picked. Points that already have a centre nearby are rarely picked. The authors proved that the start alone already has expected inertia at most 8(ln⁡K+2)8(\ln K + 2) times the optimal JJ; Lloyd's steps only lower it further. It is the default start in scikit-learn.

    In the worked example with first centre 11, the squared distances are 0,1,4,81,100,3610, 1, 4, 81, 100, 361 with sum 547547, so the second centre is 2020 with probability 361/547≈0.66361/547 \approx 0.66.

    Quick check

    Three points on a line: 00, 11 and 55. k-means++ picked 00 as the first centre. What is the probability that the second centre is 55?

    Gaussian mixtures #

    A Gaussian mixture says that each point was made in two steps: first pick a cluster z∈{1,…,K}z \in \{1, \dots, K\} with probabilities π1,…,πK\pi_1, \dots, \pi_K (the mixing weights, πk≥0\pi_k \ge 0, ∑kπk=1\sum_k \pi_k = 1), then draw xx from the Gaussian of that cluster, N(μk,Σk)\mathcal N(\mu_k, \Sigma_k). The cluster zz is a hidden (latent) variable. The density of one point is

    p(x∣θ)=∑k=1Kπk N(x∣μk,Σk),θ=(πk,μk,Σk)k=1K,p(x \mid \theta) = \sum_{k=1}^K \pi_k \, \mathcal N(x \mid \mu_k, \Sigma_k), \qquad \theta = (\pi_k, \mu_k, \Sigma_k)_{k=1}^K ,

    and we fit θ\theta by maximizing the log-likelihood ℓ(θ)=∑i=1nlog⁡∑k=1Kπk N(xi∣μk,Σk)\ell(\theta) = \sum_{i=1}^n \log \sum_{k=1}^K \pi_k \, \mathcal N(x_i \mid \mu_k, \Sigma_k). The sum inside the logarithm couples all clusters, so there is no closed-form maximum. If we knew the cluster of every point, the problem would be easy: fit one Gaussian per cluster. EM uses this idea with soft guesses of the clusters.

    E-step (expectation). Compute the responsibilities: the posterior probability that point ii came from cluster kk, by Bayes' rule with the current parameters,

    rik=p(zi=k∣xi,θ)=πk N(xi∣μk,Σk)∑j=1Kπj N(xi∣μj,Σj).r_{ik} = p(z_i = k \mid x_i, \theta) = \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)} .

    Each row ri1,…,riKr_{i1}, \dots, r_{iK} sums to 11. These are the colour mixes in the figure.

    M-step (maximization). Fit each Gaussian to all points, each point weighted by its responsibility. With Nk=∑irikN_k = \sum_i r_{ik} (the "soft size" of cluster kk):

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

    With spherical covariance the widget uses Σk=σk2I\Sigma_k = \sigma_k^2 I with σk2=12Nk∑irik∥xi−μk∥2\sigma_k^2 = \frac{1}{2 N_k} \sum_i r_{ik} \lVert x_i - \mu_k \rVert^2.

    EM never decreases the log-likelihood, just as Lloyd's algorithm never increases JJ. The widget stops when ℓ/n\ell / n changes by less than 10−510^{-5}. Like k-means, EM finds a local maximum that depends on the start; the widget starts the means with k-means++ or random points, each covariance as a circle, and πk=1/K\pi_k = 1/K.

    Why EM never decreases the log-likelihood

    For any distribution qiq_i over the cluster of point ii, the log-likelihood of that point splits into two parts (see the ELBO lesson):

    log⁡p(xi∣θ)=∑kqi(k)log⁡p(xi,zi=k∣θ)qi(k)⏟ELBO(qi, θ)+KL(qi ∥ p(zi∣xi,θ))⏟≥0.\log p(x_i \mid \theta) = \underbrace{\sum_k q_i(k) \log \frac{p(x_i, z_i = k \mid \theta)}{q_i(k)}}_{\text{ELBO}(q_i,\, \theta)} + \underbrace{\mathrm{KL}\big(q_i \,\big\|\, p(z_i \mid x_i, \theta)\big)}_{\ge 0} .

    The E-step sets qi=p(zi∣xi,θold)q_i = p(z_i \mid x_i, \theta_{\text{old}}), which is ri⋅r_{i\cdot}. Then the KL term is 00, so ∑iELBO(qi,θold)=ℓ(θold)\sum_i \text{ELBO}(q_i, \theta_{\text{old}}) = \ell(\theta_{\text{old}}). The M-step maximizes ∑iELBO(qi,θ)\sum_i \text{ELBO}(q_i, \theta) over θ\theta; for Gaussians the maximizer is exactly the formulas above (set the gradients to zero; for π\pi use a Lagrange multiplier for ∑kπk=1\sum_k \pi_k = 1). So

    ℓ(θnew)≥∑iELBO(qi,θnew)≥∑iELBO(qi,θold)=ℓ(θold).\ell(\theta_{\text{new}}) \ge \sum_i \text{ELBO}(q_i, \theta_{\text{new}}) \ge \sum_i \text{ELBO}(q_i, \theta_{\text{old}}) = \ell(\theta_{\text{old}}) .

    The first inequality holds because KL is never negative (Jensen's inequality).

    Quick check

    One dimension, two Gaussians with π1=π2=0.5\pi_1 = \pi_2 = 0.5, σ1=σ2=1\sigma_1 = \sigma_2 = 1, μ1=0\mu_1 = 0 and μ2=2\mu_2 = 2. What is the responsibility r1r_{1} of the first Gaussian for the point x=0.5x = 0.5?

    What EM adds to k-means #

    k-means is a limit of EM. Fix all covariances to σ2I\sigma^2 I and all weights to 1/K1/K, and let σ→0\sigma \to 0. Then rik∝exp⁡(−∥xi−μk∥2/2σ2)r_{ik} \propto \exp(-\lVert x_i - \mu_k \rVert^2 / 2\sigma^2) goes to 11 for the nearest centre and 00 for the others: the E-step becomes the assign step, and the M-step for μk\mu_k becomes the update step. So k-means is "hard EM" for round clusters of the same size and weight, and this is exactly the case where it works well.

    What EM does not fix: a Gaussian is still one blob around one centre, so a ring stays out of reach. Methods built on neighbours, such as spectral clustering, DBSCAN, or a kernel version of k-means, can follow such shapes.

    A trap: the likelihood has no maximum. Put one mean exactly on a data point, μk=xi\mu_k = x_i, with Σk=σ2I\Sigma_k = \sigma^2 I. The term N(xi∣μk,σ2I)=1/(2πσ2)\mathcal N(x_i \mid \mu_k, \sigma^2 I) = 1/(2\pi\sigma^2) grows without limit as σ→0\sigma \to 0, and so does ℓ\ell. A Gaussian that sits on one point (or on points along a line) can collapse. Practical code adds a small ridge to each covariance (scikit-learn adds 10−6I10^{-6} I, called reg_covar), uses a prior, or restarts. The widget adds 10−6I10^{-6} I too, and it stops with a message when a covariance becomes almost singular. To see it: press Clear all, set Click to adds a cloud and click once, then set it to adds a point and click once far away. With K=2K = 2 and Gaussian mixture, press To the end. k-means++ gives the lonely point its own Gaussian, and that Gaussian shrinks onto it.

    Choosing the number of clusters KK #

    The inertia always goes down when KK grows (with K=nK = n it is 00), so we cannot simply minimize it.

    Measuring the result. When the true groups are known (as in the second figure), the adjusted Rand index compares two clusterings: it counts the pairs of points that are put together or apart in both, and corrects for the agreement expected by chance. It is 11 for identical clusterings (up to renaming the clusters) and about 00 for random ones.