Unsupervised Learning
K-Means Clustering
Assignment holds centres fixed; updating holds memberships fixed. Both minimise the same squared-distance objective, but a fixed point need not be globally optimal.
3 centres, seeded from starting position 7. Geometry blobs, x multiplier 1, inspected row 0. The centres are placed and no point has joined one yet, so there is no inertia to report. Step to assign.
- Observation
- Cluster centre
- Path a centre has taken
- Inertia over the run
- Inertia at the chosen k
- Inertia at other k
Row 0: unassigned. Cluster glyphs C0–C5: circle, square, diamond, triangle, cross, bars. Cross centres have C labels.
Where can groups come from when no labels are supplied?
No classes, no ground truth. Just positions. Whatever structure gets found has to come out of the geometry alone.
- Nearest centre
- Membership
- Mean of members
- Inertia
Observation
One fixed pair of numerical feature values; its row ID stays the same through algorithm steps.
Check this stage
Check your understanding
K-means alternates nearest-centre assignments with arithmetic-mean updates on the same observations. A fixed point can still have much higher squared loss than another start.
What changes in each step?
K-means groups numerical observations by minimising a within-cluster sum of squared Euclidean distances. Assignment changes memberships with centres fixed. Recentre changes centres with memberships fixed. Together they form one iteration.
Open Assign, then recentre. Predict which operation moves the centres, then Step twice. The same sixty observations stay in place. Their glyphs encode cluster IDs C0 through C5; cross-shaped centres have C labels. A centre is a mean, so it need not coincide with any observation. Trails record only its seeded and updated positions.
Inspect a row and open Under the hood. Its segment joins that observation to its currently assigned centre; its squared length in feature units contributes to J. The table keeps all distances and contributions, including memberships that are no longer nearest immediately after an update. Those change only on the next assignment.
Why is the update an arithmetic mean?
For cluster j with n_j members, the objective and mean are:
The mean minimises the sum of squared Euclidean distances for fixed memberships. A median would minimise a different, absolute-distance objective. The loss is a sum, not an average or a sum of unsquared distances. See the Stanford algorithm notes.
For (0,0), (0,2), (6,0), (6,2) with centres (0,2), (6,2), assignment produces memberships [0,0,1,1] and J=8. Recentre moves the centres to (0,1), (6,1), leaving those memberships unchanged and reducing J to 4. Compare the cluster counts, coordinate sums and member means in the drawer on the lab's larger dataset.
What does stopping mean?
The initial state has centres but no assignments, so inertia is undefined. The first Step assigns every row. A full iteration completes at Recentre. Both operations leave J unchanged or reduce it. A bounded, non-increasing number alone does not prove finite termination.
This lab tests a fixed point: a new assignment would change no membership and recomputing member means would move no centre. It also imposes a separate iteration budget. Set that budget to 1 and finish the available phases: Budget exhausted does not mean Converged. Raise the budget to restart with more work available.
Play advances one operation per tick. Previous phase, Phase history and the trace diamond restore exact phases, including their memberships, centres and trails. The trace axis marks assignment half-steps and completed iterations; it is not elapsed work time. Stage changes pause and retain the run. Shared links deterministically recompute the selected phase and pause; guesses and recovery remain in memory.
How can initialisation change a stable answer?
Starting positions changes the initial centroids, not the observations. This lab shuffles row indices and selects K distinct indices (Forgy initialisation). Different starts can reach different local solutions. On the original unscaled blobs at K=3, starts 3, 27, 33 and 36 reach fixed points with J between 185.5 and 223.4; the best observed among forty starts is about 42.3. That reference is not a proof of global optimality or evidence of true labels.
Use Load bad initialisation, then Step or Play. Recovery restores the complete preceding experiment, including the selected phase, inspected row, prediction and sandbox mode, with playback paused. It remains available after further edits. Load challenge starts the guarded task on the original unscaled blobs at K=3; a fixed point above twice the reference solves it. Changing geometry, scale or K invalidates that task. An unfinished run cannot solve it.
Restarts compare the same objective on identical observations. The reference and elbow use forty starts with a separate 50-iteration budget each. Better seeding can help; k-means++ is one researched alternative, not a global-optimum guarantee. This lab retains Forgy. Actual library defaults depend on the method; check the KMeans API.
Can inertia choose K or fix the geometry?
Optimal inertia cannot increase when K increases: an extra centre can leave the previous solution available. With enough centres each observation can have zero loss. Minimising raw inertia alone therefore cannot choose a useful K. Finite searches can miss better local solutions and need not yield a monotone elbow. The bars show the best observed values, not certified optima or a computed correct K.
In Choosing k, change X feature multiplier. Multiplying x by s weights its squared-distance contribution by s squared. Observations retain their original row identities; the algorithm restarts in changed feature units. Comparing raw inertia across these scales is misleading. Axis ranges rescale independently: screen lengths do not represent equal feature distances. Standardisation is a modelling choice, not a guarantee that all feature meanings or cluster shapes become suitable.
Data geometry replaces the observations with two fixed concentric rings. At K=2, nearest-centre regions cut them into convex cells rather than recovering inner and outer rings. More restarts can improve the objective without repairing this mismatch. Unequal sizes, unequal variances, elongated groups and outliers can cause other problems: squared loss makes faraway points influential. Compare the assumptions examples and scaling limitations.
What happens at ties and empty clusters?
Exact distance ties go to the lowest centre index. Duplicate observations remain separate rows and count separately in sums. Distinct starting indices can therefore produce coincident centroids. A centre with no members stays where it is; its member mean is undefined, not zero. K does not guarantee K nonempty groups.
The pure maths accepts positive integer K and caps it at the number of observations; invalid K and non-finite input coordinates are rejected. Empty input has no centres, no initial inertia and zero objective after assignment. Singleton and all-identical inputs are supported, including unused coincident centres. The interactive fixtures have sixty finite observations and retain the supported K range 2 through 6.
Reset restores starting settings, keeps the guided stage, pauses and clears recovery and predictions. Explore freely unlocks every control and visual; returning to guided keeps the experiment. Exploration is not evidence that the clusters are useful.
Stage recap
Unlabelled data
No classes, no ground truth. Just positions. Whatever structure gets found has to come out of the geometry alone.
Assign, then recentre
Step once: every point takes the glyph of its nearest centroid. Step again: every centroid moves to the mean of the points that chose it. Those two operations, alternating, are the entire algorithm — and each leaves a trail showing where its centre has been.
Territory
Outline the territory nearest to each centroid in feature coordinates. The cell walls sit exactly halfway between neighbouring centroids, so they move whenever the centroids do — and they stop moving at the same moment the centroids do.
Inertia, and a bad start
Both operations leave squared loss unchanged or lower it. A fixed point is different from exhausting the iteration budget. Compare starts on identical data, K and scale; the best observed result is not a proof of global optimality.
Choosing k
Optimal inertia cannot increase with K, so its minimum alone cannot choose K. These bars show finite searches, which need not be monotone. Try rings at K=2: a low-loss convex partition need not recover the groups you intended.
Reference
- Assignment
- each point joins the cluster whose centre is nearest
- Update
- each centre moves to the mean of its assigned points
- Inertia
- Σ ‖xᵢ − μ(cluster of i)‖² — total squared distance to own centre
- Stopping
- fixed point or iteration budget exhausted; the latter does not certify convergence
- Fixed point
- no point switches cluster and no centre moves
- Local solution
- a fixed point is not a certified global optimum; starts affect the result
- Restarts
- run it n times from different starts, keep the lowest inertia
- Choosing k
- chosen by the reader; optimal inertia cannot increase with K, while finite searches can miss better solutions
Break it on purpose
Four of the forty starting positions — 3, 27, 33 and 36 — merge two of the three blobs and split the third. The run converges in two to four iterations, reports a perfectly stable inertia, and nothing about it looks broken. One way to detect elevated loss is to compare it against the best of the other starts: 185.5 to 223.4 against 42.3, four to five times worse. The comparison is empirical evidence, not proof of global optimality.
Explore next
- Principal Component Analysis (PCA)For a fixed centred dataset, variance kept plus mean squared orthogonal reconstruction error is constant; PCA chooses a direction that keeps the most variance.
- k-Nearest NeighborsChange the distance metric or neighbour count and watch the votes reshape the decision boundary.
- Autoencoder (Bottleneck Compression)Change the bottleneck width and inspect how many shared templates the decoder can use to rebuild an image.