Watch k-means find the clusters
NumPy records every iteration of k-means escaping a deliberately terrible start; a slider scrubs the replay as three centroids untangle the clusters.
Watch k-means find the clusters
k-means is the hello-world of unsupervised learning, and it is best understood as a movie rather than a formula: assign every point to its nearest centroid, move each centroid to the mean of its points, repeat until nothing moves. The Python cell runs the algorithm and records every iteration; the HTML cell turns that recording into a scrubbable replay. To make it earn its keep, the three centroids start in the worst spot we could give them: stacked in one corner, far from every cluster.
1import json2import numpy as np34rng = np.random.default_rng(20260704)56blobs = [7 ((-2.4, 1.9), 0.55, 90),8 ((1.8, 2.3), 0.70, 90),9 ((0.2, -2.1), 0.60, 90),10]11pts = np.vstack([rng.normal(center, spread, (count, 2))12 for center, spread, count in blobs])1314# A deliberately terrible start: all three centroids in the same corner.15centroids = np.array([[-3.6, -3.2], [-3.2, -3.6], [-3.9, -3.7]])1617steps = []18for _ in range(20):19 d = np.linalg.norm(pts[:, None, :] - centroids[None, :, :], axis=2)20 assign = d.argmin(axis=1)21 inertia = float((d[np.arange(len(pts)), assign] ** 2).sum())22 steps.append({23 "c": np.round(centroids, 3).tolist(),24 "a": assign.tolist(),25 "inertia": round(inertia, 1),26 })27 moved = np.array([pts[assign == k].mean(axis=0) if np.any(assign == k)28 else centroids[k] for k in range(len(centroids))])29 if np.abs(moved - centroids).max() < 1e-4:30 break31 centroids = moved3233kmeans_steps = json.dumps({"pts": np.round(pts, 3).tolist(), "steps": steps},34 separators=(",", ":"))3536f"Converged after {len(steps) - 1} moves; inertia fell from {steps[0]['inertia']:,} to {steps[-1]['inertia']:,}."
'Converged after 8 moves; inertia fell from 9,373.0 to 1,027.1.'
1<div style="font-family:var(--verso-prose-font-family,sans-serif);">2 <div style="display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:8px;">3 <button id="km-play" type="button" style="padding:3px 12px;border:1px solid var(--verso-border-default,#bfbfbf);border-radius:999px;background:transparent;color:inherit;font:inherit;font-size:12.5px;cursor:pointer;">Replay</button>4 <input id="km-slider" type="range" min="0" max="1" value="0" step="1"5 style="flex:1;min-width:140px;accent-color:var(--verso-accent-primary,#0078d4);" />6 <span id="km-label" style="font-size:12.5px;color:var(--verso-fg-muted,#777);font-variant-numeric:tabular-nums;"></span>7 </div>8 <canvas id="km-canvas" width="760" height="520"9 style="width:100%;max-width:760px;display:block;border-radius:8px;"></canvas>10</div>11<script>12(function () {13 var data = @kmeans_steps;14 var pts = data.pts, steps = data.steps;15 var canvas = document.getElementById('km-canvas');16 var ctx = canvas.getContext('2d');17 var slider = document.getElementById('km-slider');18 var label = document.getElementById('km-label');19 var playBtn = document.getElementById('km-play');20 var COLORS = ['#58a6ff', '#ffa657', '#7ee787'];2122 slider.max = steps.length - 1;2324 var min = [Infinity, Infinity], max = [-Infinity, -Infinity];25 function grow(p) {26 for (var k = 0; k < 2; k++) {27 if (p[k] < min[k]) min[k] = p[k];28 if (p[k] > max[k]) max[k] = p[k];29 }30 }31 pts.forEach(grow);32 steps.forEach(function (s) { s.c.forEach(grow); });33 min[0] -= 0.5; min[1] -= 0.5; max[0] += 0.5; max[1] += 0.5;34 var s = Math.min(canvas.width / (max[0] - min[0]), canvas.height / (max[1] - min[1]));35 var offX = (canvas.width - s * (max[0] - min[0])) / 2;36 var offY = (canvas.height - s * (max[1] - min[1])) / 2;37 function px(p) { return offX + (p[0] - min[0]) * s; }38 function py(p) { return canvas.height - offY - (p[1] - min[1]) * s; }3940 function draw(i) {41 var st = steps[i];42 ctx.fillStyle = '#0e1117';43 ctx.fillRect(0, 0, canvas.width, canvas.height);4445 ctx.globalAlpha = 0.85;46 for (var j = 0; j < pts.length; j++) {47 ctx.fillStyle = COLORS[st.a[j]];48 ctx.beginPath();49 ctx.arc(px(pts[j]), py(pts[j]), 3.5, 0, Math.PI * 2);50 ctx.fill();51 }52 ctx.globalAlpha = 1;5354 for (var k = 0; k < st.c.length; k++) {55 ctx.strokeStyle = COLORS[k];56 ctx.setLineDash([4, 4]);57 ctx.lineWidth = 1.3;58 ctx.globalAlpha = 0.7;59 ctx.beginPath();60 for (var t = 0; t <= i; t++) {61 var q = steps[t].c[k];62 if (t === 0) ctx.moveTo(px(q), py(q));63 else ctx.lineTo(px(q), py(q));64 }65 ctx.stroke();66 ctx.setLineDash([]);67 ctx.globalAlpha = 1;6869 var cx = px(st.c[k]), cyy = py(st.c[k]);70 ctx.lineCap = 'round';71 ctx.strokeStyle = '#0e1117';72 ctx.lineWidth = 6;73 ctx.beginPath();74 ctx.moveTo(cx - 8, cyy - 8); ctx.lineTo(cx + 8, cyy + 8);75 ctx.moveTo(cx - 8, cyy + 8); ctx.lineTo(cx + 8, cyy - 8);76 ctx.stroke();77 ctx.strokeStyle = COLORS[k];78 ctx.lineWidth = 3;79 ctx.beginPath();80 ctx.moveTo(cx - 8, cyy - 8); ctx.lineTo(cx + 8, cyy + 8);81 ctx.moveTo(cx - 8, cyy + 8); ctx.lineTo(cx + 8, cyy - 8);82 ctx.stroke();83 }8485 label.textContent = 'iteration ' + i + ' / ' + (steps.length - 1)86 + ' · inertia ' + st.inertia.toLocaleString();87 }8889 var timer = null;90 function stopPlay() {91 if (timer) { clearInterval(timer); timer = null; }92 playBtn.textContent = 'Replay';93 }94 function play() {95 stopPlay();96 playBtn.textContent = 'Playing';97 var i = 0;98 slider.value = 0;99 draw(0);100 timer = setInterval(function () {101 if (!canvas.isConnected) { stopPlay(); return; }102 i++;103 if (i >= steps.length) { stopPlay(); return; }104 slider.value = i;105 draw(i);106 }, 700);107 }108109 slider.addEventListener('input', function () {110 stopPlay();111 draw(Number(slider.value));112 });113 playBtn.addEventListener('click', play);114115 draw(0);116 play();117})();118</script>
Change the story and rerun
Every frame of the replay came from the recording Python published; the slider
is just an index into it, and no code runs when you scrub. Add a fourth row to
centroids for k = 4, move the starting corner somewhere even meaner, or
tighten the blobs, and the notebook bakes a new movie on the next run.
The record-then-replay trick generalizes to any iterative algorithm you want to explain: gradient descent, simulated annealing, PageRank. If you can log the state per step, a notebook can show it.
Run it yourself
Nothing on this page is executable; the outputs were baked in by a real run. Download the notebook and it runs anywhere Verso does: VS Code, the browser, or the terminal.
dotnet tool install --global Verso.Cliverso serve kmeans-steps.versoWhat this shows
NumPy records every iteration of k-means escaping a deliberately terrible start; a slider scrubs the replay as three centroids untangle the clusters.
Every language in this notebook reads and writes the same variable store, so a value produced in one cell is simply there in the next, whatever the language.