Okay. That was good, but I want all of the dots to switch if it is better after every…
- User
Okay. That was good, but I want all of the dots to switch if it is better after every iteration
- Assistant
Below is an updated single-file demo.
Main change: after EVERY gradient step we recompute an entirely new, capacity-respecting assignment for all dots; if that reassignment lowers the loss we accept it.
(The reassignment is done with a fast greedy “nearest-with-quota” sweep; for ≤ 500 dots it’s plenty responsive in the browser. Feel free to swap in a Hungarian solver if you want full optimality.)<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Balanced Apple Clustering</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4"></script> <style> body{font-family:sans-serif;background:#f4f4f4;padding:1rem} canvas{border:2px solid #444;background:#fff;display:block;margin:1rem 0} input{width:70px;margin-right:8px} button{margin:.3rem;padding:.4rem .8rem} #info{background:#eee;padding:.5rem;border-radius:4px} </style> </head> <body> <h2>🍏 Balanced Apple Clustering</h2> <!-- controls --> <label>Dots <input id="numDots" type="number" value="100" min="4" max="500"> </label> <label>Apples <input id="numApples" type="number" value="4" min="1" max="10"> </label> <label>LR <input id="lr" type="number" step="0.001" value="0.01"> </label> <label>Iter <input id="iters" type="number" value="300"> </label> <button onclick="init()">Init</button> <button onclick="run()">Run</button> <button onclick="stop()">Stop</button> <canvas id="c" width="600" height="600"></canvas> <div id="info"> Iteration: <span id="iter">-</span> | Loss: <span id="loss">-</span> </div> <script> const canvas = document.getElementById('c'); const ctx = canvas.getContext('2d'); const SIZE = canvas.width; let dots=[], apples=[], assignment=[]; let running=false, dotsPerApple=0, colors; function init(){ running=false; const nDots = +numDots.value|0; const nApples = +numApples.value|0; if(nDots % nApples){ alert('Number of dots must be divisible by apples'); return; } dotsPerApple = nDots / nApples; dots = Array.from({length:nDots},_=>({x:Math.random(),y:Math.random()})); apples = Array.from({length:nApples},_=>({x:Math.random(),y:Math.random(),vx:0,vy:0})); // random balanced assignment assignment=[]; for(let k=0;k<nApples;k++) for(let i=0;i<dotsPerApple;i++) assignment.push(k); shuffle(assignment); colors = ['#ff6b6b','#4ecdc4','#ffa502','#1e90ff','#9b59b6','#2ecc71','#f368e0']; draw(); updateInfo(); } function shuffle(a){for(let i=a.length-1;i>0;i--){const j=(Math.random()*(i+1))|0;[a[i],a[j]]=[a[j],a[i]];}} const dist=(p,q)=>Math.hypot(p.x-q.x,p.y-q.y); function loss(assign=assignment){ let s=0; for(let i=0;i<dots.length;i++) s+=dist(dots[i],apples[assign[i]]); return s/dots.length; } function gradients(){ const g = apples.map(_=>({x:0,y:0,c:0})); dots.forEach((d,i)=>{ const k=assignment[i], a=apples[k]; const dx=a.x-d.x, dy=a.y-d.y, r=Math.hypot(dx,dy)||1e-8; g[k].x += dx/r; g[k].y += dy/r; g[k].c++; }); g.forEach(o=>{ if(o.c){o.x/=o.c; o.y/=o.c;} }); return g; } /* ---------- NEW : global balanced reassignment ---------- */ function bestBalancedAssignment(){ // greedy “nearest with quota” – O(N*K log K) const quota = Array(apples.length).fill(0); const order = [...Array(dots.length).keys()]; shuffle(order); // randomise to avoid bias const newA = Array(dots.length); order.forEach(i=>{ const d=dots[i]; const list = apples.map((a,k)=>({k,dist:dist(d,a)})) .sort((a,b)=>a.dist-b.dist); for(const {k} of list){ if(quota[k] < dotsPerApple){ quota[k]++; newA[i]=k; break; } } }); return newA; } /* ----------------------------------------------------------- */ async function run(){ if(running) return; running=true; const lr=+document.getElementById('lr').value; const iters=+document.getElementById('iters').value; const momentum=.9; for(let it=0;it<iters && running;it++){ const g = gradients(); apples.forEach((a,k)=>{ a.vx = momentum*a.vx - lr*g[k].x; a.vy = momentum*a.vy - lr*g[k].y; a.x = Math.min(1,Math.max(0,a.x+a.vx)); a.y = Math.min(1,Math.max(0,a.y+a.vy)); }); /* every iteration try a FULL reassignment */ const candidate = bestBalancedAssignment(); if(loss(candidate) < loss()) assignment=candidate; draw(); updateInfo(it+1); await tf.nextFrame(); // allows UI/JS thread to breathe } running=false; } function stop(){running=false;} function draw(){ ctx.clearRect(0,0,SIZE,SIZE); // connections ctx.globalAlpha=.25; dots.forEach((d,i)=>{ const a=apples[assignment[i]], col=colors[assignment[i]%colors.length]; ctx.beginPath(); ctx.moveTo(d.x*SIZE,d.y*SIZE); ctx.lineTo(a.x*SIZE,a.y*SIZE); ctx.strokeStyle=col; ctx.stroke(); }); ctx.globalAlpha=1; // dots dots.forEach((d,i)=>{ ctx.beginPath(); ctx.arc(d.x*SIZE,d.y*SIZE,3,0,2*Math.PI); ctx.fillStyle=colors[assignment[i]%colors.length]; ctx.fill(); }); // apples ctx.font='30px serif'; apples.forEach(a=>{ ctx.fillText('🍎',a.x*SIZE-15,a.y*SIZE+10); }); } function updateInfo(it='-'){ iter.textContent=it; loss.textContent=loss().toFixed(4); } window.onload=init; </script> </body> </html>What changed?
•
bestBalancedAssignment()
– Greedy, capacity-aware reassignment that gives every apple exactlydotsPerAppledots.
– Called after each gradient update. If the new assignment’s loss is lower, we adopt it.•
loss(candidate)helper lets us compare losses quickly.Play with the sliders, hit “Init”, then “Run”, and watch the apples chase their balanced dot flocks. Have fun!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.