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.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Below is an all-in-one HTML file that uses TensorFlow.js to “cluster” randomly placed apples so they settle in locations that “explain” an underlying set of random dots. In our example the loss for the apples is defined as the average (over all dots) of the “smooth minimum” squared distance from a dot to all apples. (That is, for each dot we take a differentiable approximation of the minimum distance from that dot to any apple.) In effect, the apples will shift until they best cover (or “explain”) the randomly scattered dots. (For a uniform dot distribution the apples will drift out to cover the square uniformly.) You can adjust the number of dots and apples via HTML inputs and then click “Restart” to reinitialize.
Simply save the text below as (for example) index.html and open it in your browser:
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>TF.js Apples and Dots Distribution Demo</title>
<!-- Load TF.js from CDN -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.20.0/dist/tf.min.js"></script>
<style>
body {
font-family: sans-serif;
}
canvas {
border: 1px solid #ccc;
margin-top: 10px;
}
</style>
</head>
<body>
<h2>TF.js Apples and Dots Demo</h2>
<p>
This demo randomly places some dots (blue) and a few apples (red). Using a loss that for each dot computes a
differentiable “minimum” distance to the apples we let gradient descent move the apples so that they “explain”
or cover the dots.
</p>
<label for="numDots">Number of Dots:</label>
<input type="number" id="numDots" value="1000">
<label for="numApples">Number of Apples:</label>
<input type="number" id="numApples" value="20">
<button id="restart">Restart</button>
<br>
<canvas id="canvas" width="600" height="600"></canvas>
<script>
// Global variables for dot positions and apple positions.
// Dot positions is a tf.Tensor2d of shape [numDots,2];
// Apple positions is stored as a tf.Variable of shape [numApples,2] (with values in [0,1]).
let dotPositions;
let applePositions;
let numDots = parseInt(document.getElementById('numDots').value);
let numApples = parseInt(document.getElementById('numApples').value);
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// Parameter for the smooth minimum.
// A higher beta makes the smooth-min closer to the true min.
const beta = 50;
// Learning rate for the optimizer.
const learningRate = 0.05;
const optimizer = tf.train.adam(learningRate);
// Initialize dot positions and apple positions.
function initialize() {
numDots = parseInt(document.getElementById('numDots').value);
numApples = parseInt(document.getElementById('numApples').value);
// Dispose previous dot positions if any.
if (dotPositions) {
dotPositions.dispose();
}
// Random dots in the [0,1]×[0,1] square.
dotPositions = tf.randomUniform([numDots, 2]);
// Dispose previous apple positions if any.
if (applePositions) {
applePositions.dispose();
}
// Random initial apple positions.
let initialApples = tf.randomUniform([numApples, 2]);
applePositions = tf.variable(initialApples);
}
// Define a loss function.
//
// For each dot we compute the squared Euclidean distance to each apple.
// Then we compute a smooth-min using the formula:
// smoothMin = - (1/beta) * log(sum(exp(-beta*d^2)))
// so that when beta is high the smoothMin approximates the minimum distance.
// Finally, we average the smoothMin values over all dots.
//
// With this loss, any apple that is “far away” from many dots will feel a gradient pulling it toward those dots.
function lossFunction() {
return tf.tidy(() => {
// Expand the dims so that we can vectorize over dots and apples.
// dots: shape [numDots, 1, 2]
// apples: shape [1, numApples, 2]
const dots = dotPositions.expandDims(1);
const apples = applePositions.expandDims(0);
// Compute differences. This results in shape [numDots, numApples, 2].
const diff = dots.sub(apples);
// Squared distances: shape [numDots, numApples].
const sqDist = diff.square().sum(2);
// For each dot, compute the smooth minimum of the distances:
// smoothMin = - (1/beta) * log( sum(exp(-beta * d)) )
const softMin = sqDist.mul(-beta).exp().sum(1).log().mul(-1 / beta);
// Average over all dots.
return softMin.mean();
});
}
// Draw the dots and apples on the canvas.
function draw() {
// Clear the canvas.
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Draw dots as small blue circles.
tf.tidy(() => {
const dotsData = dotPositions.dataSync();
for (let i = 0; i < numDots; i++) {
const x = dotsData[i*2] * canvas.width;
const y = dotsData[i*2+1] * canvas.height;
ctx.beginPath();
ctx.arc(x, y, 2, 0, 2 * Math.PI);
ctx.fillStyle = 'blue';
ctx.fill();
}
});
// Draw apples as larger red circles with black borders.
tf.tidy(() => {
const applesData = applePositions.dataSync();
for (let i = 0; i < numApples; i++) {
const x = applesData[i*2] * canvas.width;
const y = applesData[i*2+1] * canvas.height;
ctx.beginPath();
ctx.arc(x, y, 8, 0, 2 * Math.PI);
ctx.fillStyle = 'red';
ctx.fill();
ctx.strokeStyle = 'black';
ctx.stroke();
}
});
}
// Animation loop: one step of optimization and drawing each frame.
function animate() {
// Run one optimization step.
optimizer.minimize(lossFunction, /* returnCost= */ false);
// (Optional) Keep apples inside the 1x1 grid.
tf.tidy(() => {
const clipped = applePositions.clipByValue(0, 1);
applePositions.assign(clipped);
});
// Draw updated positions.
draw();
requestAnimationFrame(animate);
}
// Wire the restart button.
document.getElementById('restart').addEventListener('click', () => {
initialize();
});
// Initialize and start the animation.
initialize();
animate();
</script>
</body>
</html>
How It Works
Initialization:
The script creates numDots random dot positions and numApples random apple positions (both in [0,1]×[0,1]). The user can change these numbers via inputs and then click “Restart” to reinitialize.
The Loss Function:
For each dot, we compute the squared distances to every apple.
A smooth minimum (using a log-sum-exp trick with a parameter beta) approximates the “closest apple” distance.
Averaging these values over all dots gives a loss. Minimizing this loss via gradient descent nudges the apple positions so that all dots “find” a nearby apple.
Optimization:
TensorFlow’s Adam optimizer automatically updates the apple positions (stored in a tf.Variable) without having to balance separate loss terms.
Visualization:
A canvas is redrawn each frame showing the fixed blue dots and the moving red apple markers.
Open the file in your browser and watch as the apples (red circles) gradually reposition to “cover” the blue dots according to their distribution. Enjoy experimenting with the parameters!