Here's a single HTML file to train a Variational Autoencoder (VAE) using TensorFlow.js, which allows the user to upload a folder of images. The images are resized to 64x64, converted to tensors, and preprocessed before training.
✅ Features:
- Upload a folder using a file input (
webkitdirectory).
- Loads PNG/JPG images, resizes them to 64x64 using canvas.
- Builds and trains a simple VAE using TensorFlow.js.
- All in one file, runs completely in the browser.
📁 Save this as vae_trainer.html:
<!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.14.0"></script>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
canvas { display: none; }
</style>
</head>
<body>
<h1>Train a VAE in the Browser</h1>
<p>Select a folder of images (JPG/PNG):</p>
<input type="file" id="fileInput" webkitdirectory multiple />
<p id="status">Waiting for files...</p>
<canvas id="canvas" width="64" height="64"></canvas>
<script>
const fileInput = document.getElementById('fileInput');
const statusEl = document.getElementById('status');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let imageTensors = [];
// Util: Load image and resize to 64x64
async function processImage(file) {
return new Promise((resolve) => {
const img = new Image();
const reader = new FileReader();
reader.onload = () => {
img.onload = () => {
ctx.clearRect(0, 0, 64, 64);
ctx.drawImage(img, 0, 0, 64, 64);
let imageData = ctx.getImageData(0, 0, 64, 64);
let tensor = tf.browser.fromPixels(imageData).toFloat().div(255.0);
resolve(tensor);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
});
}
async function loadImages(files) {
const imageFiles = Array.from(files).filter(file =>
file.type.match('image.*'));
imageTensors = [];
statusEl.textContent = `Processing ${imageFiles.length} images...`;
for (let file of imageFiles) {
const imgTensor = await processImage(file);
imageTensors.push(imgTensor);
}
statusEl.textContent = `Loaded ${imageTensors.length} images. Starting training...`;
trainVAE();
}
// Encoder
function buildEncoder(latentDim) {
const input = tf.input({shape: [64, 64, 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: latentDim}).apply(x);
const zLogVar = tf.layers.dense({units: latentDim}).apply(x);
const z = new tf.layers.lambda({
func: (inputs) => {
const [zMean, zLogVar] = inputs;
const epsilon = tf.randomNormal(zMean.shape);
return zMean.add(tf.exp(zLogVar.mul(0.5)).mul(epsilon));
}
}).apply([zMean, zLogVar]);
const encoder = tf.model({inputs: input, outputs: [z, zMean, zLogVar], name: 'encoder'});
return encoder;
}
// Decoder
function buildDecoder(latentDim) {
const input = tf.input({shape: [latentDim]});
let x = tf.layers.dense({units: 16 * 16 * 64, activation: 'relu'}).apply(input);
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);
x = tf.layers.conv2d({filters: 3, kernelSize: 3, activation: 'sigmoid', padding: 'same'}).apply(x);
return tf.model({inputs: input, outputs: x, name: 'decoder'});
}
// VAE Loss
function vaeLoss(xTrue, xPred, zMean, zLogVar) {
const reconLoss = tf.metrics.meanSquaredError(xTrue, xPred).mean();
const klLoss = tf.tidy(() =>
tf.add(1, zLogVar).sub(tf.square(zMean)).sub(tf.exp(zLogVar)).sum(-1).mean().mul(-0.5)
);
return reconLoss.add(klLoss);
}
async function trainVAE() {
const latentDim = 16;
const encoder = buildEncoder(latentDim);
const decoder = buildDecoder(latentDim);
const inputs = tf.stack(imageTensors);
const optimizer = tf.train.adam(1e-3);
const batchSize = 8;
const epochs = 10;
const stepsPerEpoch = Math.floor(inputs.shape[0] / batchSize);
for (let epoch = 0; epoch < epochs; epoch++) {
let losses = [];
for (let i = 0; i < stepsPerEpoch; i++) {
const batch = inputs.slice([i * batchSize, 0, 0, 0], [batchSize, 64, 64, 3]);
const loss = await optimizer.minimize(() => {
const [z, zMean, zLogVar] = encoder.predict(batch);
const xDecoded = decoder.predict(z);
const totalLoss = vaeLoss(batch, xDecoded, zMean, zLogVar);
return totalLoss;
}, true);
losses.push(loss.dataSync()[0]);
}
statusEl.textContent = `Epoch ${epoch + 1}/${epochs} - Loss: ${tf.tensor(losses).mean().dataSync()[0].toFixed(4)}`;
await tf.nextFrame(); // allow UI updates
}
statusEl.textContent += "\nTraining complete!";
}
fileInput.addEventListener('change', (e) => {
loadImages(e.target.files);
});
</script>
</body>
</html>
⚠️ Notes:
- TensorFlow.js runs in the browser, so performance is limited. Don't upload hundreds of images — 50–100 small ones should work well.
- The encoder/decoder architectures are basic and meant for small-scale demos only.
- Use Chrome for best compatibility with
webkitdirectory and TensorFlow.js.
Let me know if you'd like:
✅ Sampling and visualization after training
✅ Saving and loading models
✅ Using webcam input for real-time testing
Happy VAExploring! 🧠✨