Can you make a single html file with tf.js that demonstrates that with 1000(adjustable)…
- User
Can you make a single html file with tf.js that demonstrates that with 1000(adjustable) random dots and 20(adjustable) random apples in a 1x1 grid. There should be a loss for all the apples that makes them match the distribution of the dots, so the apples like disperse to match the dots. I don't want to have to balance different losses or values. I want them to converge automatically. Also, don't use distance, use something like mean absolute difference in coordinates because Im going to be scaling to higher dimensions
Assistant
Here's a complete HTML file using TensorFlow.js that demonstrates the behavior you described. It includes:
- Adjustable number of dots (1000 by default) and apples (20 by default)
- Mean Absolute Difference (MAD) loss between apple positions and dot positions
- Automatic convergence without manual parameter balancing
- Visualization of dots (blue) and apples (red) on a canvas
<!DOCTYPE html> <html> <head> <title>TF.js Apple-Dot Convergence</title> <style> body { font-family: Arial; text-align: center; } canvas { border: 1px solid #ccc; margin-top: 20px; } .controls { margin: 20px; } </style> </head> <body> <h1>Apple-Dot Convergence</h1> <div class="controls"> <label>Dots: <span id="dotsVal">1000</span> <input type="range" id="dotsSlider" min="100" max="5000" value="1000"> </label> <br> <label>Apples: <span id="applesVal">20</span> <input type="range" id="applesSlider" min="5" max="100" value="20"> </label> </div> <canvas id="canvas" width="600" height="600"></canvas> <!-- TensorFlow.js CDN --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.10.0/dist/tf.min.js"></script> <script> let dots, apples; let optimizer; const learningRate = 0.01; const canvasSize = 600; // Initialize with default values function init() { const numDots = parseInt(document.getElementById('dotsSlider').value); const numApples = parseInt(document.getElementById('applesSlider').value); // Dispose previous tensors if (dots) dots.dispose(); if (apples) apples.dispose(); if (optimizer) optimizer.dispose(); // Create dots dots = tf.tensor2d( Array.from({length: numDots}, () => [Math.random(), Math.random()]), [numDots, 2] ); // Create apples as trainable variables apples = tf.variable(tf.randomUniform([numApples, 2], 0, 1)); // Initialize optimizer optimizer = tf.train.sgd(learningRate); // Start training loop train(); } // Calculate MAD loss between apples and dots function computeLoss() { // Reshape apples to [apples, 1, 2] const expandedApples = apples.reshape([apples.shape[0], 1, 2]); // Reshape dots to [1, dots, 2] const expandedDots = dots.reshape([1, dots.shape[0], 2]); // Calculate absolute differences const diffs = expandedApples.sub(expandedDots); const absDiffs = diffs.abs(); // Average MAD per apple const perAppleMAD = absDiffs.sum(1).div(dots.shape[0]); // Overall loss is the average of all apples' MAD return perAppleMAD.mean(); } // Training loop async function train() { await tf.tidy(() => { const loss = computeLoss(); const grads = tf.grad(() => loss)(); optimizer.applyGradients(grads); }); draw(); requestAnimationFrame(train); } // Draw dots and apples on canvas function draw() { const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw dots ctx.fillStyle = 'blue'; const dotsArray = dots.arraySync(); for (const [x, y] of dotsArray) { ctx.beginPath(); ctx.arc(x * canvas.width, y * canvas.height, 1, 0, Math.PI*2); ctx.fill(); } // Draw apples ctx.fillStyle = 'red'; const applesArray = apples.arraySync(); for (const [x, y] of applesArray) { ctx.beginPath(); ctx.arc(x * canvas.width, y * canvas.height, 3, 0, Math.PI*2); ctx.fill(); } } // Update controls document.getElementById('dotsSlider').addEventListener('input', () => { document.getElementById('dotsVal').textContent = document.getElementById('dotsSlider').value; init(); }); document.getElementById('applesSlider').addEventListener('input', () => { document.getElementById('applesVal').textContent = document.getElementById('applesSlider').value; init(); }); // Initialize on load init(); </script> </body> </html>Key Features:
- Mean Absolute Difference (MAD) Loss: The loss function calculates the absolute difference between apple positions and dot positions, then averages these values to create a single scalar loss.
- Automatic Convergence: The optimizer (SGD) automatically adjusts the apple positions to minimize the loss without manual parameter tuning.
- Visual Feedback: Blue dots represent the target distribution, and red apples move to match this distribution over time.
- Adjustable Parameters: You can adjust the number of dots and apples using the sliders at the top.
How It Works:
- The apples are initialized as trainable variables.
- In each training iteration, the loss is calculated based on the MAD between apple positions and dot positions.
- The optimizer updates the apple positions to minimize this loss.
- The canvas is continuously redrawn to show the progress of the apples converging to the dot distribution.
This implementation should work well in any modern web browser with JavaScript enabled.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.