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.
Here's a complete HTML file that demonstrates dots and apples converging using TensorFlow.js:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dots and Apples Distribution Matching</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
background-color: #f0f0f0;
}
canvas {
border: 2px solid #333;
background-color: white;
display: block;
margin: 20px auto;
}
.controls {
text-align: center;
margin: 20px;
}
.controls input {
margin: 5px;
padding: 5px;
}
.info {
text-align: center;
margin: 10px;
font-size: 14px;
}
</style>
</head>
<body>
<h1 style="text-align: center;">Distribution Matching with TensorFlow.js</h1>
<div class="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="1" max="100"></label>
<button onclick="reset()">Reset</button>
<button onclick="toggleTraining()" id="trainButton">Start Training</button>
</div>
<canvas id="canvas" width="600" height="600"></canvas>
<div class="info">
<div>Loss: <span id="loss">0</span></div>
<div>Iteration: <span id="iteration">0</span></div>
</div>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
const canvasSize = 600;
let dots = [];
let apples = [];
let isTraining = false;
let iteration = 0;
// TensorFlow variables
let applePositions;
let optimizer;
function initializePositions() {
const numDots = parseInt(document.getElementById('numDots').value);
const numApples = parseInt(document.getElementById('numApples').value);
// Generate random dots
dots = [];
for (let i = 0; i < numDots; i++) {
dots.push({
x: Math.random(),
y: Math.random()
});
}
// Initialize apples with random positions
const initialAppleData = [];
for (let i = 0; i < numApples; i++) {
initialAppleData.push([Math.random(), Math.random()]);
}
// Create TensorFlow variable for apple positions
if (applePositions) {
applePositions.dispose();
}
applePositions = tf.variable(tf.tensor2d(initialAppleData));
// Create optimizer
optimizer = tf.train.adam(0.01);
iteration = 0;
document.getElementById('iteration').textContent = iteration;
}
function computeLoss() {
return tf.tidy(() => {
// Get current apple positions
const applePos = applePositions;
const numApples = applePos.shape[0];
const numDots = dots.length;
// Convert dots to tensor
const dotPositions = tf.tensor2d(dots.map(d => [d.x, d.y]));
// For each apple, find the minimum distance to any dot
// This encourages apples to move towards areas with dots
let totalLoss = tf.scalar(0);
for (let i = 0; i < numApples; i++) {
const apple = applePos.slice([i, 0], [1, 2]);
// Calculate distances from this apple to all dots
const distances = tf.norm(tf.sub(dotPositions, apple), 2, 1);
// Use the minimum distance as loss (encourages apple to get close to nearest dot)
const minDistance = tf.min(distances);
totalLoss = tf.add(totalLoss, minDistance);
}
// Add a small repulsion term between apples to prevent clustering
let repulsionLoss = tf.scalar(0);
for (let i = 0; i < numApples; i++) {
for (let j = i + 1; j < numApples; j++) {
const apple1 = applePos.slice([i, 0], [1, 2]);
const apple2 = applePos.slice([j, 0], [1, 2]);
const distance = tf.norm(tf.sub(apple1, apple2), 2);
// Add inverse distance as repulsion (stronger when closer)
const repulsion = tf.div(tf.scalar(0.01), tf.add(distance, tf.scalar(0.001)));
repulsionLoss = tf.add(repulsionLoss, repulsion);
}
}
return tf.add(totalLoss, repulsionLoss);
});
}
function trainStep() {
const loss = optimizer.minimize(() => computeLoss());
// Clamp positions to [0, 1] range
const clampedPositions = tf.clipByValue(applePositions, 0, 1);
applePositions.assign(clampedPositions);
return loss;
}
function draw() {
ctx.clearRect(0, 0, canvasSize, canvasSize);
// Draw dots (small blue circles)
ctx.fillStyle = 'rgba(0, 100, 255, 0.6)';
for (const dot of dots) {
ctx.beginPath();
ctx.arc(dot.x * canvasSize, dot.y * canvasSize, 2, 0, 2 * Math.PI);
ctx.fill();
}
// Draw apples (red circles)
if (applePositions) {
const appleData = applePositions.dataSync();
ctx.fillStyle = 'rgba(255, 50, 50, 0.8)';
for (let i = 0; i < appleData.length; i += 2) {
const x = appleData[i] * canvasSize;
const y = appleData[i + 1] * canvasSize;
ctx.beginPath();
ctx.arc(x, y, 8, 0, 2 * Math.PI);
ctx.fill();
// Add apple stem
ctx.strokeStyle = 'green';
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(x, y - 8);
ctx.lineTo(x, y - 12);
ctx.stroke();
}
}
}
function animate() {
if (isTraining) {
const loss = trainStep();
const lossValue = loss.dataSync()[0];
document.getElementById('loss').textContent = lossValue.toFixed(6);
document.getElementById('iteration').textContent = ++iteration;
loss.dispose();
}
draw();
requestAnimationFrame(animate);
}
function toggleTraining() {
isTraining = !isTraining;
const button = document.getElementById('trainButton');
button.textContent = isTraining ? 'Stop Training' : 'Start Training';
}
function reset() {
isTraining = false;
document.getElementById('trainButton').textContent = 'Start Training';
initializePositions();
draw();
}
// Initialize and start
initializePositions();
draw();
animate();
</script>
</body>
</html>
This HTML file creates a complete demonstration where:
Blue dots represent the target distribution (randomly scattered)
Red apples start at random positions and learn to match the dot distribution
The loss function automatically balances two objectives:
Attraction: Each apple tries to get close to the nearest dots
Repulsion: Apples avoid clustering too close together
The system converges automatically without manual tuning because:
The main loss (distance to nearest dots) naturally drives apples toward dot-dense areas
The small repulsion term prevents all apples from converging to the same spots
The Adam optimizer handles the learning rate automatically
You can adjust the number of dots and apples using the input controls, and watch as the apples gradually disperse to match the dot distribution when you start training. The loss decreases as the apples find better positions that match the overall dot pattern.