gpt-4.1-mini-2025-04-14· OpenAI
LMArena Human Preference 140K
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
Certainly! Below is a complete single HTML file that allows a user to upload a folder of images, resizes them to 64x64, and trains a simple Variational Autoencoder (VAE) using TensorFlow.js. The code includes:
- Folder upload input (using
webkitdirectory). - Image loading and resizing to 64x64 using canvas.
- Preprocessing images into tensors.
- A simple VAE model definition.
- Training loop with progress display.
Save this as
vae_trainer.htmland open it in a modern browser (Chrome or Edge recommended for folder upload support).<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <title>VAE Trainer with TensorFlow.js</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.8.0/dist/tf.min.js"></script> <style> body { font-family: Arial, sans-serif; margin: 20px; } #progress { margin-top: 10px; } canvas { display: none; } </style> </head> <body> <h1>Variational Autoencoder Trainer (64x64 images)</h1> <p>Upload a folder of images (will be resized to 64x64):</p> <input type="file" id="folderInput" webkitdirectory multiple accept="image/*" /> <br/><br/> <button id="trainBtn" disabled>Train VAE</button> <div id="progress"></div> <script> (async () => { const folderInput = document.getElementById('folderInput'); const trainBtn = document.getElementById('trainBtn'); const progressDiv = document.getElementById('progress'); let imageTensors = null; // Resize image to 64x64 and return a tensor normalized [0,1] async function imageFileToTensor(file) { return new Promise((resolve) => { const img = new Image(); img.onload = () => { // Draw to canvas and resize const canvas = document.createElement('canvas'); canvas.width = 64; canvas.height = 64; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, 64, 64); // Get image data and convert to tensor const imageData = ctx.getImageData(0, 0, 64, 64); const imgTensor = tf.browser.fromPixels(imageData).toFloat().div(255); resolve(imgTensor); }; img.onerror = () => { console.warn('Failed to load image:', file.name); resolve(null); }; img.src = URL.createObjectURL(file); }); } folderInput.addEventListener('change', async (e) => { const files = Array.from(e.target.files).filter(f => f.type.startsWith('image/')); if (files.length === 0) { alert('No images found in the selected folder.'); trainBtn.disabled = true; return; } progressDiv.textContent = `Loading and resizing ${files.length} images...`; const tensors = []; for (let i = 0; i < files.length; i++) { progressDiv.textContent = `Processing image ${i + 1} of ${files.length}...`; const tensor = await imageFileToTensor(files[i]); if (tensor) tensors.push(tensor); } if (tensors.length === 0) { alert('No valid images could be loaded.'); trainBtn.disabled = true; return; } // Stack all tensors into one 4D tensor [num_images, 64, 64, 3] imageTensors = tf.stack(tensors); tensors.forEach(t => t.dispose()); progressDiv.textContent = `Loaded ${imageTensors.shape[0]} images. Ready to train.`; trainBtn.disabled = false; }); // Define VAE model components function sampling(args) { const [zMean, zLogVar] = args; const epsilon = tf.randomNormal(zMean.shape); return zMean.add(tf.exp(zLogVar.mul(0.5)).mul(epsilon)); } function createVAE() { const inputShape = [64, 64, 3]; const latentDim = 32; // Encoder const encoderInputs = tf.input({shape: inputShape}); let x = tf.layers.conv2d({filters: 32, kernelSize: 3, strides: 2, padding: 'same', activation: 'relu'}).apply(encoderInputs); x = tf.layers.conv2d({filters: 64, kernelSize: 3, strides: 2, padding: 'same', activation: 'relu'}).apply(x); x = tf.layers.flatten().apply(x); x = tf.layers.dense({units: 128, activation: 'relu'}).apply(x); const zMean = tf.layers.dense({units: latentDim}).apply(x); const zLogVar = tf.layers.dense({units: latentDim}).apply(x); const z = new tf.layers.lambda({function: sampling}).apply([zMean, zLogVar]); const encoder = tf.model({inputs: encoderInputs, outputs: [zMean, zLogVar, z], name: 'encoder'}); // Decoder const decoderInputs = tf.input({shape: [latentDim]}); x = tf.layers.dense({units: 16 * 16 * 64, activation: 'relu'}).apply(decoderInputs); x = tf.layers.reshape({targetShape: [16, 16, 64]}).apply(x); x = tf.layers.conv2dTranspose({filters: 64, kernelSize: 3, strides: 2, padding: 'same', activation: 'relu'}).apply(x); x = tf.layers.conv2dTranspose({filters: 32, kernelSize: 3, strides: 2, padding: 'same', activation: 'relu'}).apply(x); const decoderOutputs = tf.layers.conv2d({filters: 3, kernelSize: 3, padding: 'same', activation: 'sigmoid'}).apply(x); const decoder = tf.model({inputs: decoderInputs, outputs: decoderOutputs, name: 'decoder'}); // VAE model const [zMeanOut, zLogVarOut, zOut] = encoder.apply(encoderInputs); const reconstructed = decoder.apply(zOut); // Custom loss layer function vaeLoss(xTrue, xPred) { const reconstructionLoss = tf.metrics.meanSquaredError(xTrue, xPred).mul(inputShape[0] * inputShape[1] * inputShape[2]); const klLoss = tf.tidy(() => { const kl = zLogVarOut.add(1).sub(zMeanOut.square()).sub(tf.exp(zLogVarOut)); return tf.sum(kl, 1).mul(-0.5); }); return tf.mean(reconstructionLoss.add(klLoss)); } const vae = tf.model({inputs: encoderInputs, outputs: reconstructed, name: 'vae'}); vae.compile({ optimizer: tf.train.adam(1e-3), loss: vaeLoss }); return {vae, encoder, decoder}; } trainBtn.addEventListener('click', async () => { if (!imageTensors) return; trainBtn.disabled = true; progressDiv.textContent = 'Creating model...'; const {vae} = createVAE(); const batchSize = 32; const epochs = 20; progressDiv.textContent = 'Starting training...'; await vae.fit(imageTensors, imageTensors, { batchSize, epochs, shuffle: true, callbacks: { onEpochBegin: (epoch) => { progressDiv.textContent = `Epoch ${epoch + 1} / ${epochs}...`; }, onEpochEnd: (epoch, logs) => { progressDiv.textContent = `Epoch ${epoch + 1} / ${epochs} - Loss: ${logs.loss.toFixed(4)}`; } } }); progressDiv.textContent += ' Training complete!'; trainBtn.disabled = false; }); })(); </script> </body> </html>
How to use:
- Open the file in a Chromium-based browser (Chrome, Edge).
- Click the file input and select a folder containing images.
- Wait for images to load and resize.
- Click Train VAE to start training.
- Watch the progress and loss updates.
Notes:
- This example uses a simple convolutional VAE with a 32-dimensional latent space.
- Images are normalized to [0,1].
- The loss combines reconstruction MSE and KL divergence.
- Training is done on CPU or GPU depending on your browser and hardware.
- For large datasets, memory may be a limitation in the browser.
If you want me to add visualization of reconstructions or latent space exploration, just ask!
- Folder upload input (using
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 →
- o3-2025-04-16Compare 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 →