Make me a single html file to train a variational autoencoder with tensorflow js when…
- User
Make me a single html file to train a variational autoencoder with tensorflow js when the user uploads a folder of images that gets resized to 64x64
- Assistant
Below is a stand-alone HTML file (just save it as
vae_trainer.htmland open it in a modern browser with WebGL support).
It lets the user:- Select a folder of images.
- Automatically resizes every image to 64 × 64.
- Builds a small Variational Auto-Encoder (convolutional encoder / decoder).
- Trains the VAE completely in the browser with TensorFlow.js.
- Shows reconstruction examples after every epoch.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>Browser-VAE trainer (TensorFlow.js)</title> <style> body { font-family: Arial, sans-serif; margin: 2rem; } canvas { border: 1px solid #ccc; margin: 4px; } #preview canvas { width: 32px; height: 32px; } </style> </head> <body> <h2>Variational Auto-Encoder in your browser 🚀</h2> <p> 1) Pick a folder with (small) images.<br> 2) Wait for thumbnails to load.<br> 3) Click “Start training” – reconstructions will appear after every epoch. </p> <!-- Folder picker --> <input type="file" id="file-input" multiple webkitdirectory directory accept="image/*"/> <button id="start-btn" disabled>Start training</button> <!-- Status + preview + reconstructions --> <h4 id="status">Awaiting images…</h4> <div id="preview"></div> <h3>Reconstructions</h3> <div id="recon"></div> <!-- TensorFlow.js --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.18.0/dist/tf.min.js"></script> <script> // ============ Hyper-parameters ============ const IMG_SIZE = 64; // all pictures → 64×64 const LATENT = 32; // size of latent vector z const EPOCHS = 30; const BATCH = 32; const LR = 1e-3; // ========================================== // DOM nodes const fileInput = document.getElementById('file-input'); const startBtn = document.getElementById('start-btn'); const statusBox = document.getElementById('status'); const previewBox= document.getElementById('preview'); const reconBox = document.getElementById('recon'); // Global image tensors (array of rank-3 tensors [64,64,3]) let images = []; // ------------- 1. LOAD IMAGES ------------- fileInput.addEventListener('change', async (e) => { const files = Array.from(e.target.files) .filter(f => f.type.startsWith('image/')); previewBox.innerHTML = ''; reconBox.innerHTML = ''; images = []; statusBox.textContent = `Loading ${files.length} images…`; for (let i = 0; i < files.length; i++) { statusBox.textContent = `Loading ${i+1}/${files.length}`; const tensor = await readImageToTensor(files[i]); images.push(tensor); // quick thumbnail preview const thumb = document.createElement('canvas'); thumb.width = thumb.height = 32; thumb.getContext('2d').drawImage(await tensorToCanvas(tensor), 0, 0, 32, 32); previewBox.appendChild(thumb); } statusBox.textContent = `Loaded ${images.length} images. Ready to train.`; startBtn.disabled = false; }); // helper: read a File -> 64×64 Float32 tensor [0-1] function readImageToTensor(file) { return new Promise((resolve) => { const img = new Image(); const reader = new FileReader(); reader.onload = e => img.src = e.target.result; img.onload = () => { const canvas = document.createElement('canvas'); canvas.width = canvas.height = IMG_SIZE; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, IMG_SIZE, IMG_SIZE); const tensor = tf.browser.fromPixels(canvas).toFloat().div(255); resolve(tensor); }; reader.readAsDataURL(file); }); } // tensor → canvas (for display) async function tensorToCanvas(t) { const canvas = document.createElement('canvas'); canvas.width = canvas.height = IMG_SIZE; await tf.browser.toPixels(t, canvas); return canvas; } // ------------- 2. MODEL ------------------- function makeEncoder() { const input = tf.input({shape: [IMG_SIZE, IMG_SIZE, 3]}); let x = tf.layers.conv2d({filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(input); x = tf.layers.conv2d({filters: 64, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(x); x = tf.layers.flatten().apply(x); const zMean = tf.layers.dense({units: LATENT}).apply(x); const zLogVar = tf.layers.dense({units: LATENT}).apply(x); return tf.model({inputs: input, outputs: [zMean, zLogVar]}); } function sample([mean, logVar]) { return tf.tidy(() => { const eps = tf.randomNormal(mean.shape); const std = tf.exp(logVar.mul(0.5)); return mean.add(std.mul(eps)); // μ + σ·ϵ }); } function makeDecoder() { const input = tf.input({shape: [LATENT]}); let x = tf.layers.dense({ units: (IMG_SIZE/4)*(IMG_SIZE/4)*64, activation: 'relu' }).apply(input); x = tf.layers.reshape({targetShape: [IMG_SIZE/4, IMG_SIZE/4, 64]}).apply(x); x = tf.layers.conv2dTranspose({filters: 64, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(x); x = tf.layers.conv2dTranspose({filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(x); const output = tf.layers.conv2d({ filters: 3, kernelSize: 3, activation: 'sigmoid', padding: 'same' }).apply(x); return tf.model({inputs: input, outputs: output}); } // losses function reconstructionLoss(x, xHat) { return tf.losses.meanSquaredError(x, xHat).mean(); } function klLoss(mean, logVar) { return tf.tidy(() => tf.add(tf.square(mean), tf.exp(logVar)).sub(logVar).sub(1).sum(-1).mean() ); } // ------------- 3. TRAIN ------------------- async function train() { startBtn.disabled = true; statusBox.textContent = 'Building model…'; const encoder = makeEncoder(); const decoder = makeDecoder(); const opt = tf.train.adam(LR); const batchesPerEpoch = Math.ceil(images.length / BATCH); for (let epoch = 0; epoch < EPOCHS; epoch++) { tf.util.shuffle(images); // simple shuffle let epochLoss = 0; for (let b = 0; b < batchesPerEpoch; b++) { const start = b * BATCH; const end = Math.min(start + BATCH, images.length); const batch = tf.stack(images.slice(start, end)); // shape [N,64,64,3] const lossVal = opt.minimize(() => { const [zMean, zLogVar] = encoder.apply(batch); const z = sample([zMean, zLogVar]); const xHat = decoder.apply(z); const recL = reconstructionLoss(batch, xHat); const klL = klLoss(zMean, zLogVar); return recL.add(klL.mul(1e-4)); // β≈1e-4 }, /*returnCost=*/true).dataSync()[0]; epochLoss += lossVal; tf.dispose(batch); // clean memory statusBox.textContent = `Epoch ${epoch+1}/${EPOCHS} – ` + `batch ${b+1}/${batchesPerEpoch} – loss ${lossVal.toFixed(4)}`; await tf.nextFrame(); // let UI update } statusBox.textContent = `Epoch ${epoch+1}/${EPOCHS} finished. Avg loss ${(epochLoss/batchesPerEpoch).toFixed(4)}`; // ---- show one reconstruction ---- tf.tidy(async () => { reconBox.innerHTML = ''; const idx = Math.floor(Math.random() * images.length); const x = images[idx].expandDims(0); // [1,64,64,3] const [μ, σ2] = encoder.predict(x); const z = sample([μ, σ2]); const xHat = decoder.predict(z); const origCan = await tensorToCanvas(x.squeeze()); const reconCan= await tensorToCanvas(xHat.squeeze()); reconBox.appendChild(origCan); reconBox.appendChild(reconCan); }); await tf.nextFrame(); } statusBox.textContent = 'Training done 🎉'; } startBtn.addEventListener('click', train); </script> </body> </html>How it works
• Folder picker (<input webkitdirectory>): lets the user choose an entire directory at once.
• Each file is loaded into an off-screen<canvas>, resized to 64 × 64, converted to a float tensor in the range 0-1.
• A tiny convolutional encoder produces μ and log σ²; a decoder reconstructs the image.
• Custom training loop withtf.GradientTape(viaoptimizer.minimize).
• Loss = MSE reconstruction + β·KL (β=1e-4 by default).
• After every epoch, shows one random original/reconstruction pair.Feel free to tweak hyper-parameters, architecture, or display logic.
(Training many large images inside the browser will use lots of GPU memory—start small first!)
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Identical first prompt
gemini-2.5-pro-preview-05-06Compare side by side →
- chatgpt-4o-latest-20250326Compare side by side →
claude-3-5-haiku-20241022Compare side by side →
qwen-max-2025-01-25Compare side by side →
- chatgpt-4o-latest-20250326Compare side by side →
gemini-2.0-flash-001Compare side by side →
- gpt-4.1-2025-04-14Compare side by side →
- o4-mini-2025-04-16Compare side by side →
- gpt-4.1-mini-2025-04-14Compare side by side →
gemini-2.5-flash-preview-04-17Compare side by side →
- gpt-4.1-mini-2025-04-14Compare side by side →