Certainly! Below is a single HTML file that demonstrates the concept using TensorFlow.js. This example creates a 1x1 grid with 1000 random dots and 20 random apples. The apples will move to match the distribution of the dots using mean absolute difference in coordinates as the loss function.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Apples Matching Dots Distribution</title>
<style>
canvas {
border: 1px solid black;
}
</style>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
const numDots = 1000;
const numApples = 20;
const learningRate = 0.01;
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let dots = tf.randomUniform([numDots, 2]).arraySync();
let apples = tf.randomUniform([numApples, 2]).arraySync();
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
dots.forEach(dot => drawDot(dot));
apples.forEach(apple => drawApple(apple));
}
function drawDot(dot) {
ctx.beginPath();
ctx.arc(dot[0] * canvas.width, dot[1] * canvas.height, 1, 0, Math.PI * 2);
ctx.fillStyle = 'blue';
ctx.fill();
}
function drawApple(apple) {
ctx.beginPath();
ctx.arc(apple[0] * canvas.width, apple[1] * canvas.height, 3, 0, Math.PI * 2);
ctx.fillStyle = 'red';
ctx.fill();
}
async function train() {
const dotTensor = tf.tensor2d(dots);
const appleTensor = tf.tensor2d(apples, [numApples, 2]);
for (let step = 0; step < 1000; step++) {
const withGradients = tf.valueAndGrad(apples => {
const loss = tf.mean(tf.abs(apples.sub(dotTensor.mean(0)).repeat([numApples, 1])));
return loss;
});
const [loss, gradients] = withGradients(appleTensor);
apples = appleTensor.sub(gradients.mul(tf.scalar(learningRate))).arraySync();
appleTensor.dispose();
if (step % 10 === 0) {
draw();
}
await tf.nextFrame();
}
}
draw();
train();
</script>
</body>
</html>
Explanation:
-
HTML Structure:
- A canvas element is used to draw the dots and apples.
-
JavaScript:
- TensorFlow.js is loaded from a CDN.
dots and apples are initialized as random points in a 1x1 grid.
- The
draw function clears the canvas and draws the dots and apples.
- The
train function uses TensorFlow.js to minimize the mean absolute difference between the apples and the mean position of the dots.
- The training loop runs for 1000 steps, updating the positions of the apples to match the distribution of the dots.
Adjustable Parameters:
numDots and numApples can be adjusted to change the number of dots and apples.
learningRate can be adjusted to control the speed of convergence.