{
 "verso": "1.1",
 "metadata": {
  "title": "Watch k-means find the clusters",
  "created": "2026-07-04T00:00:00+00:00",
  "defaultKernel": "python",
  "activeLayout": {
   "extensionId": "verso.layout.notebook",
   "layoutId": "notebook"
  }
 },
 "cells": [
  {
   "id": "00000008-0001-0001-0001-000000000001",
   "type": "markdown",
   "source": "# Watch k-means find the clusters\n\nk-means is the hello-world of unsupervised learning, and it is best understood\nas a movie rather than a formula: assign every point to its nearest centroid,\nmove each centroid to the mean of its points, repeat until nothing moves. The\nPython cell runs the algorithm and records every iteration; the HTML cell turns\nthat recording into a scrubbable replay. To make it earn its keep, the three\ncentroids start in the worst spot we could give them: stacked in one corner,\nfar from every cluster.",
   "outputs": [
    {
     "mimeType": "text/html",
     "content": "<h1 id=\"watch-k-means-find-the-clusters\">Watch k-means find the clusters</h1>\n<p>k-means is the hello-world of unsupervised learning, and it is best understood\nas a movie rather than a formula: assign every point to its nearest centroid,\nmove each centroid to the mean of its points, repeat until nothing moves. The\nPython cell runs the algorithm and records every iteration; the HTML cell turns\nthat recording into a scrubbable replay. To make it earn its keep, the three\ncentroids start in the worst spot we could give them: stacked in one corner,\nfar from every cluster.</p>\n"
    }
   ]
  },
  {
   "id": "00000008-0001-0001-0001-000000000002",
   "type": "code",
   "language": "python",
   "source": "import json\nimport numpy as np\n\nrng = np.random.default_rng(20260704)\n\nblobs = [\n    ((-2.4, 1.9), 0.55, 90),\n    ((1.8, 2.3), 0.70, 90),\n    ((0.2, -2.1), 0.60, 90),\n]\npts = np.vstack([rng.normal(center, spread, (count, 2))\n                 for center, spread, count in blobs])\n\n# A deliberately terrible start: all three centroids in the same corner.\ncentroids = np.array([[-3.6, -3.2], [-3.2, -3.6], [-3.9, -3.7]])\n\nsteps = []\nfor _ in range(20):\n    d = np.linalg.norm(pts[:, None, :] - centroids[None, :, :], axis=2)\n    assign = d.argmin(axis=1)\n    inertia = float((d[np.arange(len(pts)), assign] ** 2).sum())\n    steps.append({\n        \"c\": np.round(centroids, 3).tolist(),\n        \"a\": assign.tolist(),\n        \"inertia\": round(inertia, 1),\n    })\n    moved = np.array([pts[assign == k].mean(axis=0) if np.any(assign == k)\n                      else centroids[k] for k in range(len(centroids))])\n    if np.abs(moved - centroids).max() < 1e-4:\n        break\n    centroids = moved\n\nkmeans_steps = json.dumps({\"pts\": np.round(pts, 3).tolist(), \"steps\": steps},\n                          separators=(\",\", \":\"))\n\nf\"Converged after {len(steps) - 1} moves; inertia fell from {steps[0]['inertia']:,} to {steps[-1]['inertia']:,}.\"\n",
   "outputs": [
    {
     "mimeType": "text/plain",
     "content": "'Converged after 8 moves; inertia fell from 9,373.0 to 1,027.1.'"
    }
   ]
  },
  {
   "id": "00000008-0001-0001-0001-000000000003",
   "type": "html",
   "language": "html",
   "source": "<div style=\"font-family:var(--verso-prose-font-family,sans-serif);\">\n  <div style=\"display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:8px;\">\n    <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>\n    <input id=\"km-slider\" type=\"range\" min=\"0\" max=\"1\" value=\"0\" step=\"1\"\n           style=\"flex:1;min-width:140px;accent-color:var(--verso-accent-primary,#0078d4);\" />\n    <span id=\"km-label\" style=\"font-size:12.5px;color:var(--verso-fg-muted,#777);font-variant-numeric:tabular-nums;\"></span>\n  </div>\n  <canvas id=\"km-canvas\" width=\"760\" height=\"520\"\n          style=\"width:100%;max-width:760px;display:block;border-radius:8px;\"></canvas>\n</div>\n<script>\n(function () {\n  var data = @kmeans_steps;\n  var pts = data.pts, steps = data.steps;\n  var canvas = document.getElementById('km-canvas');\n  var ctx = canvas.getContext('2d');\n  var slider = document.getElementById('km-slider');\n  var label = document.getElementById('km-label');\n  var playBtn = document.getElementById('km-play');\n  var COLORS = ['#58a6ff', '#ffa657', '#7ee787'];\n\n  slider.max = steps.length - 1;\n\n  var min = [Infinity, Infinity], max = [-Infinity, -Infinity];\n  function grow(p) {\n    for (var k = 0; k < 2; k++) {\n      if (p[k] < min[k]) min[k] = p[k];\n      if (p[k] > max[k]) max[k] = p[k];\n    }\n  }\n  pts.forEach(grow);\n  steps.forEach(function (s) { s.c.forEach(grow); });\n  min[0] -= 0.5; min[1] -= 0.5; max[0] += 0.5; max[1] += 0.5;\n  var s = Math.min(canvas.width / (max[0] - min[0]), canvas.height / (max[1] - min[1]));\n  var offX = (canvas.width - s * (max[0] - min[0])) / 2;\n  var offY = (canvas.height - s * (max[1] - min[1])) / 2;\n  function px(p) { return offX + (p[0] - min[0]) * s; }\n  function py(p) { return canvas.height - offY - (p[1] - min[1]) * s; }\n\n  function draw(i) {\n    var st = steps[i];\n    ctx.fillStyle = '#0e1117';\n    ctx.fillRect(0, 0, canvas.width, canvas.height);\n\n    ctx.globalAlpha = 0.85;\n    for (var j = 0; j < pts.length; j++) {\n      ctx.fillStyle = COLORS[st.a[j]];\n      ctx.beginPath();\n      ctx.arc(px(pts[j]), py(pts[j]), 3.5, 0, Math.PI * 2);\n      ctx.fill();\n    }\n    ctx.globalAlpha = 1;\n\n    for (var k = 0; k < st.c.length; k++) {\n      ctx.strokeStyle = COLORS[k];\n      ctx.setLineDash([4, 4]);\n      ctx.lineWidth = 1.3;\n      ctx.globalAlpha = 0.7;\n      ctx.beginPath();\n      for (var t = 0; t <= i; t++) {\n        var q = steps[t].c[k];\n        if (t === 0) ctx.moveTo(px(q), py(q));\n        else ctx.lineTo(px(q), py(q));\n      }\n      ctx.stroke();\n      ctx.setLineDash([]);\n      ctx.globalAlpha = 1;\n\n      var cx = px(st.c[k]), cyy = py(st.c[k]);\n      ctx.lineCap = 'round';\n      ctx.strokeStyle = '#0e1117';\n      ctx.lineWidth = 6;\n      ctx.beginPath();\n      ctx.moveTo(cx - 8, cyy - 8); ctx.lineTo(cx + 8, cyy + 8);\n      ctx.moveTo(cx - 8, cyy + 8); ctx.lineTo(cx + 8, cyy - 8);\n      ctx.stroke();\n      ctx.strokeStyle = COLORS[k];\n      ctx.lineWidth = 3;\n      ctx.beginPath();\n      ctx.moveTo(cx - 8, cyy - 8); ctx.lineTo(cx + 8, cyy + 8);\n      ctx.moveTo(cx - 8, cyy + 8); ctx.lineTo(cx + 8, cyy - 8);\n      ctx.stroke();\n    }\n\n    label.textContent = 'iteration ' + i + ' / ' + (steps.length - 1)\n      + ' \u00b7 inertia ' + st.inertia.toLocaleString();\n  }\n\n  var timer = null;\n  function stopPlay() {\n    if (timer) { clearInterval(timer); timer = null; }\n    playBtn.textContent = 'Replay';\n  }\n  function play() {\n    stopPlay();\n    playBtn.textContent = 'Playing';\n    var i = 0;\n    slider.value = 0;\n    draw(0);\n    timer = setInterval(function () {\n      if (!canvas.isConnected) { stopPlay(); return; }\n      i++;\n      if (i >= steps.length) { stopPlay(); return; }\n      slider.value = i;\n      draw(i);\n    }, 700);\n  }\n\n  slider.addEventListener('input', function () {\n    stopPlay();\n    draw(Number(slider.value));\n  });\n  playBtn.addEventListener('click', play);\n\n  draw(0);\n  play();\n})();\n</script>",
   "outputs": [
    {
     "mimeType": "text/html",
     "content": "<div style=\"font-family:var(--verso-prose-font-family,sans-serif);\">\n  <div style=\"display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin-bottom:8px;\">\n    <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>\n    <input id=\"km-slider\" type=\"range\" min=\"0\" max=\"1\" value=\"0\" step=\"1\"\n           style=\"flex:1;min-width:140px;accent-color:var(--verso-accent-primary,#0078d4);\" />\n    <span id=\"km-label\" style=\"font-size:12.5px;color:var(--verso-fg-muted,#777);font-variant-numeric:tabular-nums;\"></span>\n  </div>\n  <canvas id=\"km-canvas\" width=\"760\" height=\"520\"\n          style=\"width:100%;max-width:760px;display:block;border-radius:8px;\"></canvas>\n</div>\n<script>\n(function () {\n  var data = {\"pts\":[[-2.987,2.603],[-2.328,1.691],[-1.825,1.18],[-2.305,1.737],[-1.818,1.911],[-1.782,1.604],[-2.67,2.874],[-1.112,1.692],[-2.693,1.634],[-2.413,0.949],[-2.492,0.994],[-1.627,1.181],[-2.163,2.066],[-2.918,1.835],[-2.547,2.531],[-2.52,1.132],[-1.969,1.835],[-1.986,2.028],[-2.376,1.909],[-2.981,2.502],[-2.997,2.648],[-2.72,1.623],[-2.417,1.77],[-2.166,2.018],[-2.587,1.345],[-1.899,1.374],[-1.981,1.883],[-2.102,2.703],[-2.679,3.364],[-2.171,1.414],[-2.317,2.198],[-2.377,2.798],[-3.529,1.951],[-2.262,1.62],[-2.31,1.119],[-2.495,1.238],[-2.682,1.543],[-1.679,1.965],[-2.743,2.402],[-1.942,1.693],[-1.655,2.115],[-3.799,1.651],[-2.545,0.845],[-2.223,2.453],[-2.356,1.734],[-3.344,1.668],[-2.36,2.343],[-3.258,2.855],[-2.299,1.487],[-2.269,1.909],[-1.292,2.09],[-2.041,2.482],[-1.546,1.943],[-1.901,1.569],[-2.2,1.83],[-1.986,2.107],[-2.726,2.389],[-2.455,2.257],[-2.497,2.592],[-1.97,1.521],[-2.896,1.809],[-1.603,1.977],[-2.959,1.755],[-1.384,0.089],[-2.651,1.422],[-1.917,1.053],[-2.406,2.001],[-3.545,1.441],[-2.381,1.879],[-2.592,1.12],[-3.165,2.012],[-2.418,2.846],[-2.967,2.203],[-2.083,1.689],[-3.012,2.684],[-2.138,2.402],[-2.309,2.306],[-2.627,2.537],[-2.343,1.748],[-3.213,1.492],[-1.908,2.455],[-1.847,1.586],[-1.892,2.75],[-1.816,1.257],[-1.929,2.759],[-2.169,2.154],[-2.983,2.548],[-2.166,2.291],[-3.507,2.127],[-2.412,2.769],[0.975,2.349],[1.51,1.799],[1.039,3.725],[1.995,1.722],[1.088,2.405],[2.591,1.979],[2.005,2.35],[3.21,2.796],[2.103,2.09],[1.832,2.017],[2.49,3.384],[1.873,2.173],[0.69,1.36],[3.473,1.937],[3.258,2.888],[2.604,2.163],[2.444,2.05],[2.702,2.585],[2.617,1.977],[1.12,2.834],[1.835,2.317],[2.332,2.563],[2.325,2.783],[2.512,1.935],[1.575,2.5],[2.278,1.553],[1.905,1.609],[1.168,2.865],[1.689,1.555],[1.891,1.941],[2.79,2.697],[1.215,2.371],[2.309,1.838],[1.604,1.757],[3.086,2.086],[2.526,2.464],[1.843,1.41],[1.225,1.445],[2.802,1.695],[2.997,1.884],[2.441,2.576],[1.866,1.764],[1.609,3.106],[1.584,2.192],[1.963,0.203],[1.622,1.584],[1.562,1.912],[2.099,1.788],[0.887,2.919],[3.034,1.614],[2.758,3.911],[1.289,2.511],[2.375,1.326],[1.887,2.985],[3.823,2.379],[1.432,3.67],[1.987,1.836],[2.782,2.797],[2.013,2.514],[1.135,2.308],[1.272,1.059],[2.787,3.344],[1.525,3.043],[2.369,3.114],[1.12,2.153],[2.231,2.609],[2.354,2.111],[2.4,2.062],[2.178,2.084],[2.696,2.385],[1.756,1.407],[1.782,2.618],[2.377,2.078],[1.766,1.641],[1.282,2.503],[2.968,2.439],[2.518,2.354],[0.817,2.236],[1.01,2.767],[2.4,2.392],[1.33,3.249],[2.49,2.202],[0.439,3.806],[1.299,2.021],[2.462,1.508],[1.313,2.45],[1.586,1.782],[0.251,2.466],[2.182,2.327],[1.56,0.357],[0.798,-2.324],[-0.043,-1.236],[0.1,-2.046],[0.616,-1.77],[-0.171,-2.97],[0.738,-1.865],[0.562,-2.223],[0.376,-2.952],[0.316,-0.197],[-0.414,-2.304],[-0.659,-1.856],[0.462,-1.713],[0.115,-3.152],[-0.009,-1.478],[0.586,-2.675],[-1.108,-2.91],[0.202,-2.809],[0.438,-2.987],[0.956,-3.233],[-0.158,-1.886],[-1.426,-2.858],[0.335,-0.935],[0.65,-1.834],[-0.783,-2.205],[0.933,-2.648],[-0.536,-2.097],[0.539,-3.433],[-0.398,-2.665],[0.087,-1.807],[0.42,-1.424],[-0.346,-2.652],[-0.374,-1.856],[0.219,-2.143],[-0.188,-3.723],[0.642,-2.43],[-0.197,-2.439],[0.391,-1.999],[0.16,-1.739],[0.432,-1.922],[0.08,-2.72],[0.311,-2.065],[-0.138,-2.75],[0.977,-2.527],[1.033,-1.776],[-0.679,-2.31],[1.137,-1.488],[0.856,-3.02],[0.908,-1.284],[0.215,-2.533],[0.141,-2.287],[0.903,-1.581],[0.495,-1.773],[-0.346,-2.845],[0.124,-2.78],[0.508,-0.965],[0.476,-2.45],[0.702,-2.602],[0.606,-2.277],[-0.249,-2.65],[0.048,-2.775],[0.201,-2.302],[1.14,-1.288],[-0.013,-2.551],[-1.047,-2.243],[0.964,-1.326],[1.337,-1.568],[0.158,-1.396],[-0.114,-1.911],[0.604,-2.023],[-0.62,-2.512],[-0.695,-3.338],[-1.149,-1.878],[0.388,-2.337],[0.284,-2.834],[0.523,-2.57],[0.415,-2.247],[0.709,-2.09],[0.854,-1.551],[0.28,-1.361],[0.117,-2.424],[0.133,-1.551],[0.247,-2.339],[0.859,-2.733],[0.942,-2.67],[0.882,-2.718],[-0.081,-2.149],[-0.067,-1.908],[-0.835,-2.582],[0.49,-1.864],[-1.071,-2.127]],\"steps\":[{\"c\":[[-3.6,-3.2],[-3.2,-3.6],[-3.9,-3.7]],\"a\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,0,0,0,1,1,1,1,1,1,0,0,0,0,1,0,1,1,0,1,0,1,0,1,0,1,1,1,0,1,1,0,1,0,0,1,1,0,1,0,1,0,0,1,0,1,0,1,0,0,0,1,0,0,0,0,0,1,1,1,1,1,0,1,1,0,1,1,0,0,1,0,1,0,0,1,0,0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,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,1,2,1,2,1,2,2,1,2,2,1,2,1,2,2,2,2,2,2,2,1,1,2,2,2,2,2,1,1,2,2,2,2,2,2,1,1,1,2,2,2,2,1,2,1,2,1,2,2,1,1,2,2,1,2,2,2,2,2,2,1,2,2,1,1,1,2,1,2,2,2,2,2,2,2,1,1,1,2,1,2,2,2,2,2,2,2,1,2],\"inertia\":1027.1},{\"c\":[[-0.218,2.108],[0.637,-1.427],[0.033,-2.532]],\"a\":[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,2,1,2,1,2,1,2,2,1,2,2,1,2,1,2,2,2,2,2,2,2,1,1,2,2,2,2,2,1,1,2,2,2,2,2,2,1,1,1,2,2,2,2,1,2,1,2,1,2,2,1,1,2,2,1,2,2,2,2,2,2,1,2,2,1,1,1,2,1,2,2,2,2,2,2,2,1,1,1,2,1,2,2,2,2,2,2,2,1,2],\"inertia\":1027.1}]};\n  var pts = data.pts, steps = data.steps;\n  var canvas = document.getElementById('km-canvas');\n  var ctx = canvas.getContext('2d');\n  var slider = document.getElementById('km-slider');\n  var label = document.getElementById('km-label');\n  var playBtn = document.getElementById('km-play');\n  var COLORS = ['#58a6ff', '#ffa657', '#7ee787'];\n\n  slider.max = steps.length - 1;\n\n  var min = [Infinity, Infinity], max = [-Infinity, -Infinity];\n  function grow(p) {\n    for (var k = 0; k < 2; k++) {\n      if (p[k] < min[k]) min[k] = p[k];\n      if (p[k] > max[k]) max[k] = p[k];\n    }\n  }\n  pts.forEach(grow);\n  steps.forEach(function (s) { s.c.forEach(grow); });\n  min[0] -= 0.5; min[1] -= 0.5; max[0] += 0.5; max[1] += 0.5;\n  var s = Math.min(canvas.width / (max[0] - min[0]), canvas.height / (max[1] - min[1]));\n  var offX = (canvas.width - s * (max[0] - min[0])) / 2;\n  var offY = (canvas.height - s * (max[1] - min[1])) / 2;\n  function px(p) { return offX + (p[0] - min[0]) * s; }\n  function py(p) { return canvas.height - offY - (p[1] - min[1]) * s; }\n\n  function draw(i) {\n    var st = steps[i];\n    ctx.fillStyle = '#0e1117';\n    ctx.fillRect(0, 0, canvas.width, canvas.height);\n\n    ctx.globalAlpha = 0.85;\n    for (var j = 0; j < pts.length; j++) {\n      ctx.fillStyle = COLORS[st.a[j]];\n      ctx.beginPath();\n      ctx.arc(px(pts[j]), py(pts[j]), 3.5, 0, Math.PI * 2);\n      ctx.fill();\n    }\n    ctx.globalAlpha = 1;\n\n    for (var k = 0; k < st.c.length; k++) {\n      ctx.strokeStyle = COLORS[k];\n      ctx.setLineDash([4, 4]);\n      ctx.lineWidth = 1.3;\n      ctx.globalAlpha = 0.7;\n      ctx.beginPath();\n      for (var t = 0; t <= i; t++) {\n        var q = steps[t].c[k];\n        if (t === 0) ctx.moveTo(px(q), py(q));\n        else ctx.lineTo(px(q), py(q));\n      }\n      ctx.stroke();\n      ctx.setLineDash([]);\n      ctx.globalAlpha = 1;\n\n      var cx = px(st.c[k]), cyy = py(st.c[k]);\n      ctx.lineCap = 'round';\n      ctx.strokeStyle = '#0e1117';\n      ctx.lineWidth = 6;\n      ctx.beginPath();\n      ctx.moveTo(cx - 8, cyy - 8); ctx.lineTo(cx + 8, cyy + 8);\n      ctx.moveTo(cx - 8, cyy + 8); ctx.lineTo(cx + 8, cyy - 8);\n      ctx.stroke();\n      ctx.strokeStyle = COLORS[k];\n      ctx.lineWidth = 3;\n      ctx.beginPath();\n      ctx.moveTo(cx - 8, cyy - 8); ctx.lineTo(cx + 8, cyy + 8);\n      ctx.moveTo(cx - 8, cyy + 8); ctx.lineTo(cx + 8, cyy - 8);\n      ctx.stroke();\n    }\n\n    label.textContent = 'iteration ' + i + ' / ' + (steps.length - 1)\n      + ' \u00b7 inertia ' + st.inertia.toLocaleString();\n  }\n\n  var timer = null;\n  function stopPlay() {\n    if (timer) { clearInterval(timer); timer = null; }\n    playBtn.textContent = 'Replay';\n  }\n  function play() {\n    stopPlay();\n    playBtn.textContent = 'Playing';\n    var i = 0;\n    slider.value = 0;\n    draw(0);\n    timer = setInterval(function () {\n      if (!canvas.isConnected) { stopPlay(); return; }\n      i++;\n      if (i >= steps.length) { stopPlay(); return; }\n      slider.value = i;\n      draw(i);\n    }, 700);\n  }\n\n  slider.addEventListener('input', function () {\n    stopPlay();\n    draw(Number(slider.value));\n  });\n  playBtn.addEventListener('click', play);\n\n  draw(0);\n  play();\n})();\n</script>"
    }
   ]
  },
  {
   "id": "00000008-0001-0001-0001-000000000004",
   "type": "markdown",
   "source": "## Change the story and rerun\n\nEvery frame of the replay came from the recording Python published; the slider\nis just an index into it, and no code runs when you scrub. Add a fourth row to\n`centroids` for k = 4, move the starting corner somewhere even meaner, or\ntighten the blobs, and the notebook bakes a new movie on the next run.\n\nThe record-then-replay trick generalizes to any iterative algorithm you want to\nexplain: gradient descent, simulated annealing, PageRank. If you can log the\nstate per step, a notebook can show it.",
   "outputs": [
    {
     "mimeType": "text/html",
     "content": "<h2 id=\"change-the-story-and-rerun\">Change the story and rerun</h2>\n<p>Every frame of the replay came from the recording Python published; the slider\nis just an index into it, and no code runs when you scrub. Add a fourth row to\n<code>centroids</code> for k = 4, move the starting corner somewhere even meaner, or\ntighten the blobs, and the notebook bakes a new movie on the next run.</p>\n<p>The record-then-replay trick generalizes to any iterative algorithm you want to\nexplain: gradient descent, simulated annealing, PageRank. If you can log the\nstate per step, a notebook can show it.</p>\n"
    }
   ]
  }
 ]
}