Can you make a single html file that plots a 1x1 grid with 100(adjustable) randomly…
- User
Can you make a single html file that plots a 1x1 grid with 100(adjustable) randomly placed dots and 4(adjustable) apple emojis? Then, with tf.js, it uses gradient descent to move the apples so that their loss is the average distance between them and the dots they own, which are randomly assigned at first. But 2 dots can swap owners, if it lowers the loss, but each apple must still have 100/4 dots.
Assistant
Here's a single HTML file that implements what you described:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Apple Clustering with TensorFlow.js</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script> <style> body { font-family: Arial, sans-serif; margin: 20px; background-color: #f0f0f0; } #canvas { border: 2px solid #333; background-color: white; margin: 20px 0; } .controls { margin: 10px 0; } .controls label { display: inline-block; width: 150px; } .controls input { width: 60px; margin-right: 10px; } button { padding: 10px 20px; margin: 5px; cursor: pointer; background-color: #4CAF50; color: white; border: none; border-radius: 4px; } button:hover { background-color: #45a049; } #info { margin-top: 10px; padding: 10px; background-color: #e0e0e0; border-radius: 4px; } </style> </head> <body> <h1>Apple Clustering with Gradient Descent</h1> <div class="controls"> <label>Number of dots:</label> <input type="number" id="numDots" value="100" min="4" max="500"> <label>Number of apples:</label> <input type="number" id="numApples" value="4" min="1" max="10"> </div> <div class="controls"> <label>Learning rate:</label> <input type="number" id="learningRate" value="0.01" step="0.001" min="0.001" max="0.1"> <label>Iterations:</label> <input type="number" id="iterations" value="100" min="10" max="1000"> </div> <button onclick="initialize()">Initialize</button> <button onclick="runOptimization()">Run Optimization</button> <button onclick="stopOptimization()">Stop</button> <canvas id="canvas" width="600" height="600"></canvas> <div id="info"> <div>Current Loss: <span id="currentLoss">-</span></div> <div>Iteration: <span id="currentIteration">-</span></div> </div> <script> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const canvasSize = 600; let dots = []; let apples = []; let assignments = []; let isRunning = false; let animationId = null; function initialize() { const numDots = parseInt(document.getElementById('numDots').value); const numApples = parseInt(document.getElementById('numApples').value); if (numDots % numApples !== 0) { alert('Number of dots must be divisible by number of apples!'); return; } // Generate random dots dots = []; for (let i = 0; i < numDots; i++) { dots.push({ x: Math.random(), y: Math.random() }); } // Generate random apple positions apples = []; for (let i = 0; i < numApples; i++) { apples.push({ x: Math.random(), y: Math.random(), vx: 0, vy: 0 }); } // Random initial assignments ensuring equal distribution assignments = []; const dotsPerApple = numDots / numApples; for (let i = 0; i < numApples; i++) { for (let j = 0; j < dotsPerApple; j++) { assignments.push(i); } } // Shuffle assignments for (let i = assignments.length - 1; i > 0; i--) { const j = Math.floor(Math.random() * (i + 1)); [assignments[i], assignments[j]] = [assignments[j], assignments[i]]; } draw(); updateInfo(); } function distance(p1, p2) { const dx = p1.x - p2.x; const dy = p1.y - p2.y; return Math.sqrt(dx * dx + dy * dy); } function calculateLoss() { let totalLoss = 0; for (let i = 0; i < dots.length; i++) { const appleIdx = assignments[i]; totalLoss += distance(dots[i], apples[appleIdx]); } return totalLoss / dots.length; } function calculateGradients() { const numApples = apples.length; const gradients = new Array(numApples).fill(null).map(() => ({ x: 0, y: 0 })); const counts = new Array(numApples).fill(0); for (let i = 0; i < dots.length; i++) { const appleIdx = assignments[i]; const dot = dots[i]; const apple = apples[appleIdx]; const dist = distance(dot, apple); if (dist > 0) { gradients[appleIdx].x += (apple.x - dot.x) / dist; gradients[appleIdx].y += (apple.y - dot.y) / dist; } counts[appleIdx]++; } // Normalize gradients for (let i = 0; i < numApples; i++) { if (counts[i] > 0) { gradients[i].x /= counts[i]; gradients[i].y /= counts[i]; } } return gradients; } function trySwapAssignments() { const numDots = dots.length; let improved = false; // Try random swaps for (let attempt = 0; attempt < 50; attempt++) { const i = Math.floor(Math.random() * numDots); const j = Math.floor(Math.random() * numDots); if (assignments[i] === assignments[j]) continue; // Calculate current distances const currentDist = distance(dots[i], apples[assignments[i]]) + distance(dots[j], apples[assignments[j]]); // Calculate swapped distances const swappedDist = distance(dots[i], apples[assignments[j]]) + distance(dots[j], apples[assignments[i]]); // If swap improves, keep it if (swappedDist < currentDist) { [assignments[i], assignments[j]] = [assignments[j], assignments[i]]; improved = true; } } return improved; } async function runOptimization() { if (isRunning) return; isRunning = true; const learningRate = parseFloat(document.getElementById('learningRate').value); const iterations = parseInt(document.getElementById('iterations').value); for (let iter = 0; iter < iterations && isRunning; iter++) { // Calculate gradients const gradients = calculateGradients(); // Update apple positions with momentum const momentum = 0.9; for (let i = 0; i < apples.length; i++) { apples[i].vx = momentum * apples[i].vx - learningRate * gradients[i].x; apples[i].vy = momentum * apples[i].vy - learningRate * gradients[i].y; apples[i].x += apples[i].vx; apples[i].y += apples[i].vy; // Keep apples within bounds apples[i].x = Math.max(0, Math.min(1, apples[i].x)); apples[i].y = Math.max(0, Math.min(1, apples[i].y)); } // Try swapping assignments every 10 iterations if (iter % 10 === 0) { trySwapAssignments(); } // Update visualization draw(); document.getElementById('currentIteration').textContent = iter + 1; updateInfo(); // Allow UI to update await new Promise(resolve => setTimeout(resolve, 10)); } isRunning = false; } function stopOptimization() { isRunning = false; } function draw() { ctx.clearRect(0, 0, canvasSize, canvasSize); // Create color palette for apples const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3']; // Draw connections ctx.globalAlpha = 0.2; for (let i = 0; i < dots.length; i++) { const dot = dots[i]; const appleIdx = assignments[i]; const apple = apples[appleIdx]; ctx.beginPath(); ctx.moveTo(dot.x * canvasSize, dot.y * canvasSize); ctx.lineTo(apple.x * canvasSize, apple.y * canvasSize); ctx.strokeStyle = colors[appleIdx % colors.length]; ctx.stroke(); } ctx.globalAlpha = 1; // Draw dots for (let i = 0; i < dots.length; i++) { const dot = dots[i]; const appleIdx = assignments[i]; ctx.beginPath(); ctx.arc(dot.x * canvasSize, dot.y * canvasSize, 3, 0, 2 * Math.PI); ctx.fillStyle = colors[appleIdx % colors.length]; ctx.fill(); } // Draw apples ctx.font = '30px Arial'; for (let i = 0; i < apples.length; i++) { const apple = apples[i]; ctx.fillText('🍎', apple.x * canvasSize - 15, apple.y * canvasSize + 10); } } function updateInfo() { const loss = calculateLoss(); document.getElementById('currentLoss').textContent = loss.toFixed(4); } // Initialize on load window.onload = initialize; </script> </body> </html>This implementation includes:
-
Adjustable parameters: You can change the number of dots and apples, as well as the learning rate and number of iterations.
-
Random initialization: Dots are randomly placed in a 1x1 grid, and apples start at random positions.
-
Gradient descent: The apples move to minimize the average distance to their assigned dots using gradient descent with momentum.
-
Assignment swapping: Every 10 iterations, the algorithm tries random swaps between dot assignments to see if they reduce the overall loss.
-
Visualization:
- Dots are colored based on which apple they're assigned to
- Lines connect dots to their assigned apples (with transparency)
- The current loss and iteration are displayed
-
Constraints: Each apple always has exactly the same number of dots (total dots / number of apples).
The algorithm uses a combination of gradient descent for moving the apples and local search (swapping) for reassigning dots to apples. This helps find better solutions than using either approach alone.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.