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 single self‐contained HTML file that uses TensorFlow.js and a Sinkhorn optimal‐transport loss so that your “apples” automatically disperse to match the empirical distribution of randomly placed “dots” in a 1×1 square. Change the sliders to adjust the number of dots/apples on the fly—no manual loss‐weight tuning required.
Save this as index.html, open it in Chrome/Firefox, and watch the apples converge!
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Apples vs Dots: Automatic Dispersion via Sinkhorn OT</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.8.0/dist/tf.min.js"></script>
<style>
body { font-family: sans-serif; text-align: center; margin: 0; padding: 0; }
#controls { padding: 10px; background: #fafafa; border-bottom: 1px solid #ddd; }
#controls label { margin: 0 10px; }
canvas { border:1px solid #333; margin-top: 10px; }
</style>
</head>
<body>
<div id="controls">
<label>
# Dots: <span id="ndotsLabel">1000</span>
<input type="range" id="ndots" min="100" max="5000" step="100" value="1000"/>
</label>
<label>
# Apples: <span id="napplesLabel">20</span>
<input type="range" id="napples" min="5" max="200" step="5" value="20"/>
</label>
<button id="reset">Reset</button>
</div>
<canvas id="c" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById('c');
const ctx = canvas.getContext('2d');
const ndotsSlider = document.getElementById('ndots');
const napplesSlider = document.getElementById('napples');
const ndotsLabel = document.getElementById('ndotsLabel');
const napplesLabel = document.getElementById('napplesLabel');
const resetButton = document.getElementById('reset');
let ndots = +ndotsSlider.value;
let napples = +napplesSlider.value;
// hyper‐parameters for Sinkhorn
const eps = 0.02;
const sinkhornIter = 30;
const lr = 0.1;
let dotsTensor; // [ndots,2], fixed
let applesVar; // tf.Variable [napples,2]
let optimizer;
ndotsSlider.oninput = () => {
ndots = +ndotsSlider.value;
ndotsLabel.innerText = ndots;
};
napplesSlider.oninput = () => {
napples = +napplesSlider.value;
napplesLabel.innerText = napples;
};
resetButton.onclick = init; // reinitialize on reset
// Utility to sample uniform points in [0,1]^2
function randomPoints(n) {
const a = new Float32Array(n*2);
for (let i = 0; i < n*2; i++) {
a[i] = Math.random();
}
return a;
}
// Sinkhorn OT cost between apples (m×2) and dots (n×2)
function sinkhornCost(apples, dots) {
// apples: [m,2], dots: [n,2]
return tf.tidy(() => {
const m = apples.shape[0], n = dots.shape[0];
// Compute pairwise cost: C_ij = ||apple_i − dot_j||^2
const A = apples.reshape([m,1,2]);
const B = dots.reshape([1,n,2]);
const C = A.sub(B).square().sum(-1); // [m,n]
const K = C.div(-eps).exp(); // [m,n]
// uniform marginals
const a = tf.fill([m], 1.0 / m);
const b = tf.fill([n], 1.0 / n);
// initialize u,v
let u = tf.fill([m], 1.0 / m);
let v = tf.fill([n], 1.0 / n);
// Sinkhorn iterations
for (let i = 0; i < sinkhornIter; i++) {
// u = a / (K · v)
u = a.div(tf.matMul(K, v.reshape([n,1])).reshape([m]).add(1e-9));
// v = b / (Kᵀ · u)
v = b.div(tf.matMul(K.transpose(), u.reshape([m,1])).reshape([n]).add(1e-9));
}
// Transport plan P = diag(u)·K·diag(v)
const U = u.reshape([m,1]);
const V = v.reshape([1,n]);
const P = U.mul(K).mul(V); // [m,n]
// cost = sum(P * C)
return tf.sum(P.mul(C));
});
}
function init() {
// dispose old tensors
if (dotsTensor) dotsTensor.dispose();
if (applesVar) applesVar.dispose();
// build new
dotsTensor = tf.tensor2d(randomPoints(ndots), [ndots,2]);
const initApples = tf.tensor2d(randomPoints(napples), [napples,2]);
applesVar = tf.variable(initApples);
optimizer = tf.train.adam(lr);
}
async function step() {
// run one gradient step
optimizer.minimize(() => sinkhornCost(applesVar, dotsTensor), /* returnCost */ false);
}
function draw() {
// draw dots in blue and apples in red
const d = canvas.width;
ctx.clearRect(0,0,d,d);
// dots
const dt = dotsTensor.arraySync();
ctx.fillStyle = 'rgba(30,144,255,0.6)';
dt.forEach(p => {
ctx.beginPath();
ctx.arc(p[0]*d, p[1]*d, 2, 0, 2*Math.PI);
ctx.fill();
});
// apples
const at = applesVar.arraySync();
ctx.fillStyle = 'rgba(220,20,60,0.8)';
at.forEach(p => {
ctx.beginPath();
ctx.arc(p[0]*d, p[1]*d, 5, 0, 2*Math.PI);
ctx.fill();
});
}
// main loop
async function animate() {
await step();
draw();
requestAnimationFrame(animate);
}
// start
init();
animate();
</script>
</body>
</html>
How it works:
• We sample ndots random “dots” and keep them fixed.
• We keep napples as a learnable tf.Variable of 2D points.
• We define a Sinkhorn‐regularized optimal transport cost—no hand‐tuning of multiple losses needed.
• An Adam optimizer takes a gradient step each frame, moving the apples so their empirical distribution matches the dots.
• Canvas drawing shows blue dots vs. red apples evolving in real‐time.
Play with the sliders and hit Reset to see it adapt instantly! 🍎✨