The goal is to split points into groups without being told the answer. Choose a PRESET, or hold and drag on the plot to spray your own points.
Pick a METHOD and press RUN. The run moves one step at a time: PAUSE and STEP control it, and SPEED under More settings sets the pace.
Drag a numbered centroid to restart k-means from there. The elbow chart shows the inertia for k = 1 to 10 on the current points.
| Clusters found | — |
| Iterations | — |
| Inertia (SSE) | — |
| Log-likelihood / pt | — |
| Noise points | — |
| Silhouette | — |
| Converged | — |
Clustering splits unlabelled points into groups, so that points in one group are more alike than points in different groups. The lab runs three methods with different ideas of a group. k-means cuts the plane into k regions around k centres and alternates two steps until nothing moves. DBSCAN grows clusters through dense regions and labels what is left over as noise. A Gaussian mixture fitted by EM describes each cluster as an ellipse and gives every point a probability for each. All three run in your browser, step by step, from the same seeded generator as the Python package clusters/1.
k-means splits the points into k clusters. Each cluster has a centroid, the mean of its points. Lloyd's algorithm is the standard way to fit it: from k starting centroids, it repeats two steps, and one iteration is one pass of both. Assign: each point takes its nearest centroid by squared Euclidean distance, and a tie goes to the lower index2. Update: each centroid moves to the mean of the points assigned to it. A centroid with no points stays where it is3.
Here x_i is point i, z_i is its cluster label, c_j is centroid j, and S_j = \{ i : z_i = j \} is the set of points with label j. The objective J is the inertia, the within-cluster sum of squared errors (SSE)4. Neither step increases it. The assign step gives each point its nearest centroid, which lowers each point's term for fixed centroids. The update step sets each centroid to the mean of its group, and the mean is the point that minimises the summed squared distance to that group. The inertia therefore never increases from one step to the next. There are only finitely many labellings, so the run cannot go on forever.
The loop ends at the first assign step that leaves every label unchanged, which counts as converged5. It also ends after \text{MAX-ITER} = 100 iterations6. In that case the labels are recomputed for the final centroids, so the result is a valid labelling7. The readout Iterations counts assign steps, so a converged run includes the final assign step that confirmed nothing had changed.
function K-MEANS(points, k):
centres ← K-MEANS-PP(points, k) # or k random data points
labels ← none
while true:
new ← ASSIGN(points, centres) # each point takes its nearest centre
if new = labels:
return labels, centres # no label changed: converged
labels ← new
centres ← UPDATE(points, labels, centres) # each centre moves to its cluster's mean
constants: MAX-ITER = 100
function K-MEANS(P, k, seed, init, dragged):
rng ← MULBERRY32(seed)
if dragged is given:
C ← dragged # centroids the user moved on the plot
else if init = k-means++:
C ← K-MEANS-PP(P, k, rng)
else:
C ← RANDOM-INIT(P, k, rng)
labels ← none
repeat MAX-ITER times:
next ← ASSIGN(P, C) # nearest centre, ties to the lower index
record SSE(P, next, C) as this step's inertia
if labels is not none and next = labels: # elementwise
return next, C, SSE(P, next, C) # converged
labels ← next
C ← UPDATE(P, labels, C) # an empty cluster keeps its centre
labels ← ASSIGN(P, C) # out of iterations: relabel the final centres
return labels, C, SSE(P, labels, C)
Ties. Equal distances go to the lower index, both when assigning and when seeding, so a run is deterministic for a given seed. Dragged centroids. A centroid the user drags on the plot replaces the seeds, so the next run starts there. Empty clusters. A centroid with no points keeps its position, so the number of centroids stays k even when a cluster empties. Out of iterations. The centroids move after the last assign step, so the labels must be recomputed for them. Without that step the labels and the centroids would disagree.
k-means++ chooses the starting centroids so that they are spread out. The first centroid is a uniformly random point. Each later centroid is drawn with probability proportional to its squared distance D(x)^2 from the nearest centroid already chosen10. The alternative, random data points, takes k distinct points from a seeded shuffle11. Random starts can drop two centroids into one blob and leave another blob with none, which is why k-means++ is the default.
Here C is the set of centroids chosen so far, and D(x) is the distance from x to its nearest one. The code does not normalise: it draws r uniformly from [0, \sum_m D(x_m)^2) and takes the first point whose running sum of D^2 exceeds r. That picks point i with the probability above. If every point already coincides with a centroid, the sum is zero and the next centroid is a uniform point.
function K-MEANS-PP(points, k):
centres ← [a uniform random point]
for c ← 2 to k:
for each point x: D(x) ← distance from x to its nearest centre
draw a point x with probability D(x)² / Σ D²
add x to centres
return centres
function K-MEANS-PP(P, k, rng):
n ← number of points
first ← rng.index(n) # uniform: floor(random · n)
C ← [P[first]]
d2(i) ← |P[i] − P[first]|² for each point i
for c ← 2 to k:
cum(i) ← d2(0) + d2(1) + … + d2(i) # running sums
total ← cum(n − 1)
if total = 0:
j ← rng.index(n) # every point sits on a centre
else:
r ← rng.random() · total
j ← the first index with cum(j) > r # capped at n − 1
append P[j] to C
d2(i) ← min(d2(i), |P[i] − P[j]|²) for each point i
return C
Example. On the blobs preset with seed 2 and k = 4, k-means converges in two iterations to four clusters of 75 points each. The page lets you compare k-means++ with random starts under More settings.
DBSCAN (density-based spatial clustering of applications with noise) finds clusters by density, so it needs no k. It has two parameters: eps, the radius of a neighbourhood, and minPts, how many points a neighbourhood must hold for its centre to count as dense. The eps-neighbourhood of a point is every point within eps of it, the point itself included. The test compares squared distances with eps², so no square root is needed13.
Here p and q are points, \varepsilon is eps, and |N_{\varepsilon}(p)| counts the neighbourhood. A point is a core point when its neighbourhood holds at least minPts points. Core points within eps of each other belong to the same cluster, so each cluster grows like a flood fill through the core points15. A border point is not core but lies in the neighbourhood of a core point. It joins the cluster of its lowest-index core neighbour16. Every other point is noise, labelled −1. The number of clusters is not set in advance. It follows from eps and minPts.
function DBSCAN(points, eps, minPts):
for each point p: N(p) ← points within eps of p, p included
core(p) ← |N(p)| ≥ minPts for each point p
every point starts as noise
for each core point p with no cluster yet:
start a new cluster and grow it through the core points
reachable from p within eps
each border point joins the cluster of its lowest-index core neighbour
the points that remain are noise (−1)
constants: NOISE = −1
function DBSCAN(P, eps, minPts):
limit ← eps · eps # compare squared distances
for each point i:
N(i) ← [ j for j in ascending order if |P[j] − P[i]|² ≤ limit ] # includes i
for each point i:
core(i) ← |N(i)| ≥ minPts
labels(i) ← NOISE for each point i
cid ← 0
for each point i:
if core(i) is false or labels(i) is not NOISE:
continue
labels(i) ← cid
queue ← [i]
while queue is not empty: # flood fill over core points only
p ← remove the front of queue
for each q in N(p):
if core(q) and labels(q) is NOISE:
labels(q) ← cid
add q to the back of queue
cid ← cid + 1
for each point i:
if core(i): continue
for each q in N(i): # ascending, so the lowest index first
if core(q):
labels(i) ← labels(q)
stop searching N(i)
return labels, core
Ideas in the full version. The neighbourhood includes the point itself, so with minPts = 1 every point is core. Clusters are numbered in the order of their lowest core index, so the labels are canonical: the same input always gives the same numbering. Border points are decided after all the core points are placed, which means a border point between two clusters always joins the one with the lower-index core neighbour. The page advances this same generator a few points at a time, so the animation shows the same result as the batch run.
Example. On the rings preset with seed 2, eps 0.08 and minPts 5 break the outer ring into three pieces (133, 8 and 9 points). With eps 0.10 the two rings come out as two clusters with no noise. Both runs use the same points, so only eps differs.
A Gaussian mixture describes the points as k Gaussian components. Component j has a weight \pi_j, a mean \mu_j and a full 2×2 covariance \Sigma_j, so each component is an ellipse. Expectation-maximisation (EM) fits the parameters by alternating an E step, which computes each point's responsibilities, and an M step, which refits the parameters to those responsibilities19. The code evaluates the densities in log space. The log density of a 2D Gaussian is:
Here \det\Sigma is the determinant of the covariance and \Sigma^{-1} its inverse. For a 2×2 matrix the code writes both in closed form22.
E step. The responsibility r_{ik} is the share of point i that component k claims. The code computes \log \pi_k + \log \mathcal{N} for each component, subtracts the largest of them before exponentiating, and normalises23. That is the log-sum-exp trick, which keeps the numbers finite when a point is far from every component.
The responsibilities of each point sum to 1 over the components. The average log-likelihood after the E step is the quantity EM tracks. It is computed under the parameters that produced the responsibilities24.
M step. Each component's effective size is N_k = \sum_i r_{ik}, floored at 10^{-10} so an empty component cannot divide by zero25. The new weight, mean and covariance are weighted versions of the usual estimates. The covariance gets a small regulariser \text{reg} = 10^{-6} on its diagonal, so a component fitted to very few points cannot collapse to zero width.
Here n is the number of points, \pi_k the weight of component k, I the 2×2 identity matrix, and \text{reg} = 10^{-6}. The page draws each component as its 2-sigma contour, an ellipse whose semi-axes are 2\sqrt{\lambda_1} and 2\sqrt{\lambda_2}, where \lambda_1 and \lambda_2 are the eigenvalues of \Sigma_k. Its angle is \tfrac{1}{2} \operatorname{atan2}(2b, a - d) for \Sigma_k = \begin{pmatrix} a & b \\ b & d \end{pmatrix}27.
The first M step uses hard labels rather than random responsibilities. The k-means++ centres give each point one component, which sets its responsibility to 128. The loop then stops when the log-likelihood gains less than 10^{-6} over the previous iteration29, or after \text{MAX-ITER} = 200 iterations30. At the cap the loop stops before its M step, so the returned weights, means and covariances are the ones that produced the responsibilities and the log-likelihood31. Each point's label is its largest responsibility32.
function GMM-EM(points, k):
centres ← K-MEANS-PP(points, k)
hard ← ASSIGN(points, centres)
weights, means, covs ← M-STEP(points, hard labels as responsibilities)
repeat until the log-likelihood stops improving:
E step: r(i, k) ← share of point i claimed by component k
ℓ ← average log-likelihood of the points under the current fit
M step: weights, means, covs ← M-STEP(points, r)
return the fit, the responsibilities and the hard labels
constants: MAX-ITER = 200, TOL = 1e−6, REG = 1e−6
function GMM-EM(P, k, seed, init):
rng ← MULBERRY32(seed)
centres ← K-MEANS-PP(P, k, rng) if init is k-means++ else RANDOM-INIT(P, k, rng)
hard ← ASSIGN(P, centres)
r(i, j) ← 1 if j = hard(i) else 0 for each point i and component j
weights, means, covs ← M-STEP(P, r, REG)
prev ← −infinity
for it in 1 to MAX-ITER:
for each component j and point i: # E step under the current fit
logp(i, j) ← log weights(j) + LOG-N(P[i] | means(j), covs(j))
for each point i:
m ← max over j of logp(i, j)
lognorm(i) ← m + log of the sum over j of exp(logp(i, j) − m)
r(i, j) ← exp(logp(i, j) − lognorm(i)) for each component j
ll ← (1 / n) · sum over i of lognorm(i)
if ll − prev < TOL and it > 1:
stop # converged
prev ← ll
if it = MAX-ITER:
stop # keep the fit that produced r and ll
weights, means, covs ← M-STEP(P, r, REG)
labels(i) ← the component j with the largest r(i, j)
return weights, means, covs, r, labels, ll
function M-STEP(P, r, REG):
for each component j:
N ← max(sum over i of r(i, j), 1e−10)
weights(j) ← N / n
means(j) ← (1 / N) · sum over i of r(i, j) · P[i]
covs(j) ← (1 / N) · sum over i of r(i, j) · (P[i] − means(j))(P[i] − means(j))ᵀ + REG · I
return weights, means, covs
Ideas in the full version. Weights multiply densities, so the code adds \log \pi_k to the log density and never multiplies raw values. The log-sum-exp step (subtracting the row maximum) is what keeps the responsibilities finite. The floor of 10^{-10} on N_k guards an empty component. The rule \ell_t - \ell_{t-1} < 10^{-6} is the convergence test, and it is applied after the E step. The average log-likelihood never decreases in exact arithmetic, so a falling value would mean a bug. The test suite checks this across presets and component counts.
Colour. The page colours each point by a blend of the component colours, weighted by its responsibilities, so a point between two ellipses shows a mixed colour.
The elbow runs k-means for k = 1 to 10 on the current points, with the same seed for each k, and plots the final inertia3435. Inertia generally falls as k grows, because more centroids fit the points more tightly. The point where the falls flatten is a rough guide to k. It is a guide, not a test: the chart shows how much each extra cluster helps, and the choice still depends on the problem.
The silhouette scores how well each point sits in its own cluster. For point i, a(i) is its mean distance to the other points of its cluster, and b(i) is the smallest mean distance from i to the points of any other cluster. The score of point i is s(i) = (b(i) - a(i)) / \max(a(i), b(i)), which lies in [−1, 1]. The silhouette is the mean of s(i) over the points that are not noise3637. A singleton scores 0. Values near 1 mean compact, well-separated clusters, and values near 0 mean overlap.
Here c(i) is the cluster of point i, n_c is its size, and n counts the points that are not noise. The mean in b(i) is taken over each other cluster in turn, and the minimum is kept. The silhouette is undefined with fewer than two clusters, and the page shows a dash.
function SILHOUETTE(points, labels):
keep the points whose label is not noise
if fewer than two clusters remain: return none
for each kept point i:
a ← mean distance from i to the other points of its cluster
b ← smallest mean distance from i to the points of another cluster
s ← (b − a) / max(a, b)
return the mean of s over the kept points
function SILHOUETTE(P, labels):
idx ← indices i with labels(i) ≥ 0 # DBSCAN noise is −1
if the labels of idx hold fewer than two distinct values: return none
D(a, b) ← Euclidean distance between idx[a] and idx[b]
total ← 0
for each kept point i:
same ← kept points with the same label as i, including i
if |same| ≤ 1:
continue # a singleton scores 0
a ← (sum of D(i, j) over j in same) / (|same| − 1)
b ← infinity
for each other label c:
b ← min(b, mean of D(i, j) over the points j with label c)
m ← max(a, b)
total ← total + ((b − a) / m if m > 0 else 0)
return total / (number of kept points)
Ideas in the full version. Noise is removed before anything else, so DBSCAN noise never counts as a cluster. A singleton has no same-cluster distance, so its score is 0 by definition; it still counts in the denominator. The distance matrix is computed once, which makes the score quadratic in the number of points. The page caps the number of points to keep this pass fast.
| Parameter | Default | Why this value |
|---|---|---|
| k (k-means, EM)38 | 4 | k is the one number you must know in advance. The presets have 4 blobs, 3 stretched blobs, 2 rings, 2 moons and 4 smiley parts, so 4 fits most of them. The elbow chart shows what the data supports.39 |
| Initialisation40 | k-means++ | Spreads the starting centres apart, so runs land in one good solution far more often than random starts. Random starts are kept to show the failure. |
| Max iterations (k-means)6 | 100 | On the five presets at k = 4 and seed 2, k-means converges in 2 to 14 iterations. The cap is a safety net, and the readout says if it was hit. |
| eps (DBSCAN)41 | 0.08 | On the blobs preset with seed 2, 0.08 gives four clusters and no noise. Too small splits a cluster into arcs; too large merges neighbours. |
| minPts (DBSCAN)42 | 5 | Counts the point itself. A value of 2 would let any two close points form a cluster. Five needs a real group of points before a region counts as dense. |
| EM tolerance43 | 1e−6 | Stop when the average log-likelihood gains less than this in one iteration. |
| EM max iterations4330 | 200 | EM converges slowly when clusters overlap. On the five presets at k = 4 and seed 2, EM took 2 to 92 iterations, so the cap bounds the animation, and the readout says if it was hit. |
| EM covariance regulariser43 | 1e−6 | Added to the covariance diagonal so a component fitted to a few points cannot collapse to zero width. |
| Method | Strengths | Weaknesses |
|---|---|---|
| k-means | Fast (each step is one pass over the points); simple; the elbow tells you where k should be. | Needs k up front. Assumes round clusters of similar size. On rings and moons with k = 2 it splits each shape between the two clusters. Sensitive to the start. |
| DBSCAN | Finds clusters of any shape, including rings and moons, and marks noise. No k needed. | Struggles when clusters have very different densities, since one eps cannot fit both. Sensitive to eps; the page's eps circles show why. |
| EM (Gaussian mixture) | Soft labels, and each cluster's own shape and tilt, so an elongated cluster is described by its own ellipse. | Needs k. Assumes each cluster is Gaussian, so a ring or a moon is a poor fit. Can converge to a local optimum. |
Reference implementation: the Python package clusters/ runs the same algorithms with the same seeds (python -m clusters run --algo kmeans --k 4 --data blobs --seed 2)44. A test compares the browser core with it on fixed seeds45. Other tests check k-means' non-increasing inertia, DBSCAN against a brute-force reference, and EM's non-decreasing log-likelihood464748.