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
Absolutely! Below is a single HTML file using TensorFlow.js that demonstrates your request:
- 1000 random "dots" (blue) and 20 random "apples" (red) in a 1x1 grid.
- The apples are trainable variables.
- The loss is the mean absolute difference (MAD) between the sorted coordinates of apples and dots, per dimension. This is a simple way to match two distributions (the Earth Mover's Distance in 1D is the mean absolute difference between sorted samples).
- No need to balance losses or values.
- You can adjust the number of dots, apples, and dimensions at the top of the script.
How it works:
- The apples' positions are optimized so that their distribution matches the dots' distribution as closely as possible, in the sense of the mean absolute difference in each coordinate.
- The apples will "spread out" to match the dots' distribution.
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>tf.js Distribution Matching Demo</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.20.0/dist/tf.min.js"></script> <style> body { background: #222; color: #eee; font-family: sans-serif; } canvas { background: #fff; display: block; margin: 20px auto; } #controls { text-align: center; margin-bottom: 10px; } label { margin: 0 10px; } </style> </head> <body> <div id="controls"> <label>Dots: <input type="number" id="numDots" value="1000" min="10" max="5000"></label> <label>Apples: <input type="number" id="numApples" value="20" min="2" max="100"></label> <label>Dimensions: <input type="number" id="numDims" value="2" min="1" max="5"></label> <button onclick="restart()">Restart</button> <span id="loss"></span> </div> <canvas id="canvas" width="500" height="500"></canvas> <script> // Adjustable parameters let numDots = 1000; let numApples = 20; let numDims = 2; // UI elements const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); const lossSpan = document.getElementById('loss'); document.getElementById('numDots').onchange = e => { numDots = +e.target.value; restart(); } document.getElementById('numApples').onchange = e => { numApples = +e.target.value; restart(); } document.getElementById('numDims').onchange = e => { numDims = +e.target.value; restart(); } // Data let dots, applesVar, optimizer, stop = false; function randomPoints(n, d) { return tf.randomUniform([n, d], 0, 1); } function restart() { stop = true; setTimeout(() => { stop = false; // Generate random dots dots = randomPoints(numDots, numDims); // Apples: trainable variables, initialized randomly applesVar = tf.variable(randomPoints(numApples, numDims)); optimizer = tf.train.adam(0.1); trainStep(); }, 100); } // Loss: mean absolute difference between sorted coordinates (per dimension) function distributionLoss() { return tf.tidy(() => { let loss = tf.scalar(0); for (let d = 0; d < numDims; ++d) { // Get d-th coordinate for dots and apples const dotsD = dots.gather([d], 1).reshape([numDots]); const applesD = applesVar.gather([d], 1).reshape([numApples]); // Sort both const dotsSorted = tf.topk(dotsD, numDots, true).values.reverse(); const applesSorted = tf.topk(applesD, numApples, true).values.reverse(); // If apples < dots, match as many as possible const minN = Math.min(numDots, numApples); const dotsS = dotsSorted.slice([0], [minN]); const applesS = applesSorted.slice([0], [minN]); // Mean absolute difference loss = loss.add(tf.mean(tf.abs(dotsS.sub(applesS)))); } return loss.div(numDims); }); } // Draw function function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); // Draw dots (blue) const dotsArr = dots.arraySync(); ctx.fillStyle = 'rgba(0,120,255,0.5)'; for (let i = 0; i < dotsArr.length; ++i) { const [x, y] = dotsArr[i]; ctx.beginPath(); ctx.arc(x * canvas.width, (numDims > 1 ? y : 0.5) * canvas.height, 2, 0, 2 * Math.PI); ctx.fill(); } // Draw apples (red) const applesArr = applesVar.arraySync(); ctx.fillStyle = 'rgba(255,40,40,0.9)'; for (let i = 0; i < applesArr.length; ++i) { const [x, y] = applesArr[i]; ctx.beginPath(); ctx.arc(x * canvas.width, (numDims > 1 ? y : 0.5) * canvas.height, 6, 0, 2 * Math.PI); ctx.fill(); } } // Training loop async function trainStep() { for (let i = 0; i < 10000 && !stop; ++i) { const loss = optimizer.minimize(distributionLoss, true); if (i % 2 === 0) { draw(); lossSpan.textContent = `Loss: ${loss.dataSync()[0].toFixed(5)}`; await tf.nextFrame(); } loss.dispose(); } } // Initial run restart(); </script> </body> </html>
How to use:
- Open the file in your browser.
- Adjust the number of dots, apples, or dimensions and click "Restart".
- In 2D, apples will spread out to match the distribution of the blue dots.
- In higher dimensions, only the first two dimensions are visualized (x, y), but the loss is computed in all dimensions.
Note:
- The loss is the mean absolute difference between sorted coordinates, which is a simple and effective way to match distributions in any dimension, and doesn't require balancing different losses.
- For higher dimensions, you can extend the visualization as needed.
Let me know if you want a more advanced visualization or further customization!
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.