gpt-4.1-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
Absolutely! Below is a single HTML file that lets a user upload a folder of images, resizes them to 64x64, and trains a simple Variational Autoencoder (VAE) using TensorFlow.js. The code includes:
- File upload (folder support)
- Image resizing to 64x64
- VAE model definition and training
- Simple UI feedback
Note:
- Training a VAE in-browser is resource-intensive and may be slow for large datasets.
- This is a minimal example for educational purposes.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>VAE Trainer with TensorFlow.js</title> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.18.0/dist/tf.min.js"></script> <style> body { font-family: Arial, sans-serif; margin: 2em; } #images { display: flex; flex-wrap: wrap; gap: 4px; margin-bottom: 1em; } #images img { width: 32px; height: 32px; object-fit: cover; } #progress { margin-top: 1em; } </style> </head> <body> <h1>Train a Variational Autoencoder (VAE) in the Browser</h1> <input type="file" id="fileInput" webkitdirectory directory multiple accept="image/*"> <div id="images"></div> <button id="trainBtn" disabled>Train VAE</button> <div id="progress"></div> <script> const fileInput = document.getElementById('fileInput'); const imagesDiv = document.getElementById('images'); const trainBtn = document.getElementById('trainBtn'); const progressDiv = document.getElementById('progress'); let imageTensors = []; // Helper: Load and resize images async function loadAndResizeImages(files) { imageTensors = []; imagesDiv.innerHTML = ''; for (const file of files) { if (!file.type.startsWith('image/')) continue; const img = document.createElement('img'); img.src = URL.createObjectURL(file); await new Promise(res => img.onload = res); imagesDiv.appendChild(img); // Resize to 64x64 using canvas const canvas = document.createElement('canvas'); canvas.width = 64; canvas.height = 64; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0, 64, 64); const imageData = ctx.getImageData(0, 0, 64, 64); // Convert to tensor, normalize to [0,1] const imgTensor = tf.browser.fromPixels(imageData).toFloat().div(255.0); imageTensors.push(imgTensor); URL.revokeObjectURL(img.src); } if (imageTensors.length > 0) trainBtn.disabled = false; } fileInput.addEventListener('change', async (e) => { trainBtn.disabled = true; progressDiv.textContent = 'Loading and resizing images...'; await loadAndResizeImages(e.target.files); progressDiv.textContent = `Loaded ${imageTensors.length} images. Ready to train.`; }); // VAE Model Definition function sampling(args) { // [z_mean, z_log_var] return tf.tidy(() => { const [z_mean, z_log_var] = args; const batch = z_mean.shape[0]; const dim = z_mean.shape[1]; const epsilon = tf.randomNormal([batch, dim]); return z_mean.add(tf.exp(z_log_var.mul(0.5)).mul(epsilon)); }); } function createVAE(inputShape = [64, 64, 3], latentDim = 16) { // Encoder const encoderInputs = tf.input({shape: inputShape}); let x = tf.layers.conv2d({filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(encoderInputs); x = tf.layers.conv2d({filters: 64, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(x); x = tf.layers.flatten().apply(x); const z_mean = tf.layers.dense({units: latentDim}).apply(x); const z_log_var = tf.layers.dense({units: latentDim}).apply(x); // Sampling layer const z = tf.layers.lambda(sampling).apply([z_mean, z_log_var]); // Decoder let 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, activation: 'relu', padding: 'same'}).apply(x); x = tf.layers.conv2dTranspose({filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(x); const decoderOutputs = tf.layers.conv2d({filters: 3, kernelSize: 3, activation: 'sigmoid', padding: 'same'}).apply(x); // Models const encoder = tf.model({inputs: encoderInputs, outputs: [z_mean, z_log_var, z]}); const decoder = tf.model({inputs: decoderInputs, outputs: decoderOutputs}); // VAE Model const vaeInputs = encoderInputs; const [z_mean_out, z_log_var_out, z_out] = encoder.apply(vaeInputs); const vaeOutputs = decoder.apply(z_out); const vae = tf.model({inputs: vaeInputs, outputs: vaeOutputs}); // Custom loss function vaeLoss(x, x_decoded) { return tf.tidy(() => { const recon = tf.metrics.meanSquaredError(x.flatten(), x_decoded.flatten()); const kl = tf.scalar(-0.5).mul( tf.mean(tf.add(tf.add(tf.scalar(1).add(z_log_var_out), tf.neg(tf.square(z_mean_out))), tf.neg(tf.exp(z_log_var_out)))) ); return recon.add(kl); }); } return {encoder, decoder, vae, vaeLoss}; } // Training trainBtn.addEventListener('click', async () => { trainBtn.disabled = true; progressDiv.textContent = 'Preparing data...'; // Stack images into a single tensor const xs = tf.stack(imageTensors); // Create VAE const {vae, vaeLoss} = createVAE(); vae.compile({ optimizer: tf.train.adam(1e-3), loss: vaeLoss }); progressDiv.textContent = 'Training... (this may take a while)'; await vae.fit(xs, xs, { epochs: 10, batchSize: 8, shuffle: true, callbacks: { onEpochEnd: (epoch, logs) => { progressDiv.textContent = `Epoch ${epoch+1}: loss=${logs.loss.toFixed(4)}`; } } }); progressDiv.textContent = 'Training complete!'; xs.dispose(); }); </script> </body> </html>
How to use:
- Save the above code as an
.htmlfile. - Open it in your browser.
- Click the file input and select a folder of images (hold Shift/Ctrl to select multiple if needed).
- Wait for images to load, then click "Train VAE".
Let me know if you want to add image generation or visualization after training!
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 →
- 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 →