Absolutely! Here's a single HTML file using TensorFlow.js (tf.js) that demonstrates what you're asking for:
- 1000 (adjustable) random dots placed in a 1x1 grid.
- 20 (adjustable) trainable apples, whose 2D coordinates are updated to match the distribution of the dots.
- The loss is computed by matching the mean absolute difference (MAD) between sorted coordinates (in each axis) — this way the apples learn to spread out like the dots without needing any manual balancing of loss terms or distance heuristics.
- This can be easily scaled to higher dimensions because there's no reliance on pairwise distance or hardcoded losses.
✅ Concept Summary
We sort the apples and dots by axis before computing MAD. Since the apples and dots are randomly distributed, sorting by x and y aligns their distributions. This makes sure the apples "match" the underlying distribution of the dots without directly aligning specific points.
📄 Full HTML File
You can just save this as an .html file and run it in the browser:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>TF.js Apples Match Dots</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.18.0/dist/tf.min.js"></script>
<style>
canvas { border: 1px solid black; }
</style>
</head>
<body>
<canvas id="canvas" width="600" height="600"></canvas>
<script>
(async function() {
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const CANVAS_SIZE = canvas.width;
const numDots = 1000;
const numApples = 20;
const learningRate = 0.1;
const optimizer = tf.train.adam(learningRate);
const stepsPerFrame = 1;
// Generate fixed dot positions
const dotCoords = tf.randomUniform([numDots, 2]);
// Create trainable variable for apples
let applePos = tf.variable(tf.randomUniform([numApples, 2]));
function draw() {
ctx.clearRect(0, 0, CANVAS_SIZE, CANVAS_SIZE);
// Draw dots in blue
const dots = dotCoords.arraySync();
ctx.fillStyle = 'blue';
dots.forEach(([x, y]) => {
ctx.beginPath();
ctx.arc(x * CANVAS_SIZE, y * CANVAS_SIZE, 2, 0, 2 * Math.PI);
ctx.fill();
});
// Draw apples in red
const apples = applePos.arraySync();
ctx.fillStyle = 'red';
apples.forEach(([x, y]) => {
ctx.beginPath();
ctx.arc(x * CANVAS_SIZE, y * CANVAS_SIZE, 5, 0, 2 * Math.PI);
ctx.fill();
});
}
function computeDistributionLoss(apples, dots) {
// Sort apples and dots separately along each axis
const lossX = tf.tidy(() => {
const applesX = apples.gather(0, 1).reshape([-1]).arraySync().sort((a, b) => a - b);
const dotsX = dots.gather(0, 1).reshape([-1]).arraySync().sort((a, b) => a - b);
return tf.mean(tf.abs(tf.tensor1d(applesX).sub(tf.tensor1d(dotsX.slice(0, numApples)))));
});
const lossY = tf.tidy(() => {
const applesY = apples.gather(1, 1).reshape([-1]).arraySync().sort((a, b) => a - b);
const dotsY = dots.gather(1, 1).reshape([-1]).arraySync().sort((a, b) => a - b);
return tf.mean(tf.abs(tf.tensor1d(applesY).sub(tf.tensor1d(dotsY.slice(0, numApples)))));
});
return tf.add(lossX, lossY);
}
function lossFunction() {
return tf.tidy(() => {
const apples = applePos;
const dotsSample = dotCoords;
// Sort the values per axis
const applesSortedX = tf.topk(apples.gather(1, 0).reshape([-1]), numApples, true).values.reverse();
const dotsSortedX = tf.topk(dotsSample.gather(1, 0).reshape([-1]), numApples, true).values.reverse();
const applesSortedY = tf.topk(apples.gather(1, 1).reshape([-1]), numApples, true).values.reverse();
const dotsSortedY = tf.topk(dotsSample.gather(1, 1).reshape([-1]), numApples, true).values.reverse();
const lossX = tf.mean(tf.abs(tf.sub(applesSortedX, dotsSortedX)));
const lossY = tf.mean(tf.abs(tf.sub(applesSortedY, dotsSortedY)));
return tf.add(lossX, lossY);
});
}
async function trainStep() {
for (let i = 0; i < stepsPerFrame; i++) {
optimizer.minimize(lossFunction, /* returnCost */ false);
}
}
async function loop() {
await trainStep();
draw();
requestAnimationFrame(loop);
}
draw();
loop();
})();
</script>
</body>
</html>
🔧 Adjustable Parameters
Edit these in the JS:
const numDots = 1000;
const numApples = 20;
const learningRate = 0.1;
⚙️ How it Works
- Apples are model parameters — 2D coordinates stored in a TensorFlow variable.
- We sort the
x and y coordinates separately, so we align distributions instead of individual points.
- Use mean absolute difference (MAD) between sorted axes — robust, dimension-agnostic.
- We don’t match structure, just overall distributions (this is scalable to high dimensions like 100s or 1000s).
💡 Notes for Higher Dimensions
- You'll need a generalized
sortAndMatch() per dimension — loop over D dimensions and compute MAD over sorted values.
- You can easily dynamically scale this by replacing the 2 in shapes like
[numPoints, 2] with D.
Let me know if you want a higher-D version, animation trails, or saving apples afterward!