Certainly! Below is a complete 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.
Features:
- Folder upload (multiple images)
- Images resized to 64x64 and normalized
- Simple convolutional VAE architecture
- Training progress displayed
- After training, you can encode and decode images (basic example)
Save this as vae.html and open in a modern browser (Chrome/Edge/Firefox).
<!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; }
#imagesPreview img { margin: 2px; width: 64px; height: 64px; object-fit: cover; border: 1px solid #ccc; }
#status { margin-top: 10px; }
#trainBtn { margin-top: 10px; padding: 10px 20px; font-size: 16px; }
</style>
</head>
<body>
<h1>Variational Autoencoder Trainer (64x64 images)</h1>
<input type="file" id="fileInput" webkitdirectory multiple accept="image/*" />
<div id="imagesPreview"></div>
<button id="trainBtn" disabled>Train VAE</button>
<div id="status"></div>
<script>
(async () => {
const IMG_SIZE = 64;
const LATENT_DIM = 16;
const BATCH_SIZE = 32;
const EPOCHS = 20;
const fileInput = document.getElementById('fileInput');
const imagesPreview = document.getElementById('imagesPreview');
const trainBtn = document.getElementById('trainBtn');
const status = document.getElementById('status');
let imageTensors = [];
// Utility: Load image file and resize to 64x64 tensor normalized [0,1]
async function loadAndProcessImage(file) {
return new Promise((resolve) => {
const img = new Image();
img.onload = () => {
// Draw to canvas and get resized image data
const canvas = document.createElement('canvas');
canvas.width = IMG_SIZE;
canvas.height = IMG_SIZE;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, IMG_SIZE, IMG_SIZE);
const imageData = ctx.getImageData(0, 0, IMG_SIZE, IMG_SIZE);
// Convert to tensor and normalize
const imgTensor = tf.browser.fromPixels(imageData).toFloat().div(255);
resolve(imgTensor);
};
img.onerror = () => {
resolve(null);
};
img.src = URL.createObjectURL(file);
});
}
// Load all images from files
async function loadImages(files) {
imagesPreview.innerHTML = '';
imageTensors = [];
status.textContent = 'Loading images...';
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!file.type.startsWith('image/')) continue;
const tensor = await loadAndProcessImage(file);
if (tensor) {
imageTensors.push(tensor);
// Show preview
const imgElem = document.createElement('img');
imgElem.src = URL.createObjectURL(file);
imagesPreview.appendChild(imgElem);
}
}
if (imageTensors.length === 0) {
status.textContent = 'No valid images found.';
trainBtn.disabled = true;
} else {
status.textContent = `Loaded ${imageTensors.length} images. Ready to train.`;
trainBtn.disabled = false;
}
}
fileInput.addEventListener('change', async (e) => {
await loadImages(e.target.files);
});
// VAE model components
// Sampling layer for reparameterization trick
class Sampling extends tf.layers.Layer {
constructor() {
super({});
}
computeOutputShape(inputShape) {
return inputShape[0];
}
call(inputs) {
const [zMean, zLogVar] = inputs;
const batch = zMean.shape[0];
const dim = zMean.shape[1];
const epsilon = tf.randomNormal([batch, dim]);
return zMean.add(tf.exp(zLogVar.mul(0.5)).mul(epsilon));
}
getClassName() {
return 'Sampling';
}
}
// Encoder model
function buildEncoder() {
const inputs = tf.input({shape: [IMG_SIZE, IMG_SIZE, 3]});
let x = tf.layers.conv2d({filters: 32, kernelSize: 3, strides: 2, padding: 'same', activation: 'relu'}).apply(inputs);
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: LATENT_DIM}).apply(x);
const zLogVar = tf.layers.dense({units: LATENT_DIM}).apply(x);
const z = new Sampling().apply([zMean, zLogVar]);
return tf.model({inputs, outputs: [zMean, zLogVar, z], name: 'encoder'});
}
// Decoder model
function buildDecoder() {
const latentInputs = tf.input({shape: [LATENT_DIM]});
let x = tf.layers.dense({units: 16 * 16 * 64, activation: 'relu'}).apply(latentInputs);
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 outputs = tf.layers.conv2d({filters: 3, kernelSize: 3, padding: 'same', activation: 'sigmoid'}).apply(x);
return tf.model({inputs: latentInputs, outputs, name: 'decoder'});
}
// VAE model combining encoder and decoder
function buildVAE(encoder, decoder) {
const inputs = encoder.inputs[0];
const [zMean, zLogVar, z] = encoder.apply(inputs);
const reconstructed = decoder.apply(z);
// Custom loss layer
function vaeLoss(x, xDecodedMean) {
const reconstructionLoss = tf.metrics.meanSquaredError(x.flatten(), xDecodedMean.flatten());
const klLoss = tf.tidy(() => {
return tf.mean(
tf.sub(
tf.add(1, zLogVar),
tf.square(zMean),
tf.exp(zLogVar)
).mul(-0.5)
);
});
return reconstructionLoss.add(klLoss);
}
const vae = tf.model({inputs, outputs: reconstructed});
vae.compile({
optimizer: tf.train.adam(),
loss: vaeLoss
});
return vae;
}
trainBtn.addEventListener('click', async () => {
trainBtn.disabled = true;
status.textContent = 'Building model...';
const encoder = buildEncoder();
const decoder = buildDecoder();
const vae = buildVAE(encoder, decoder);
status.textContent = 'Preparing dataset...';
// Stack all images into a single tensor
const xs = tf.stack(imageTensors);
status.textContent = 'Training started...';
await vae.fit(xs, xs, {
epochs: EPOCHS,
batchSize: BATCH_SIZE,
shuffle: true,
callbacks: {
onEpochEnd: (epoch, logs) => {
status.textContent = `Epoch ${epoch + 1} / ${EPOCHS} - Loss: ${logs.loss.toFixed(4)}`;
}
}
});
status.textContent = 'Training complete!';
// Clean up
xs.dispose();
// Optionally: show reconstruction of first image
const firstImage = imageTensors[0].expandDims(0);
const reconstructed = vae.predict(firstImage);
const reconstructedImg = await tf.browser.toPixels(reconstructed.squeeze());
// Show original and reconstructed side by side
const container = document.createElement('div');
container.style.marginTop = '20px';
container.innerHTML = '<h3>Original vs Reconstructed</h3>';
const origCanvas = document.createElement('canvas');
origCanvas.width = IMG_SIZE;
origCanvas.height = IMG_SIZE;
const origCtx = origCanvas.getContext('2d');
origCtx.drawImage(imagesPreview.querySelector('img'), 0, 0, IMG_SIZE, IMG_SIZE);
const reconCanvas = document.createElement('canvas');
reconCanvas.width = IMG_SIZE;
reconCanvas.height = IMG_SIZE;
const reconCtx = reconCanvas.getContext('2d');
const imageData = reconCtx.createImageData(IMG_SIZE, IMG_SIZE);
imageData.data.set(reconstructedImg);
reconCtx.putImageData(imageData, 0, 0);
container.appendChild(origCanvas);
container.appendChild(reconCanvas);
document.body.appendChild(container);
trainBtn.disabled = false;
});
})();
</script>
</body>
</html>
How to use:
- Open the file in a browser.
- Click the file input and select a folder of images (Chrome supports folder upload with
webkitdirectory).
- Wait for images to load and preview.
- Click Train VAE to start training.
- After training, you will see the original and reconstructed image side by side.
Notes:
- This is a minimal example for demonstration.
- Training on many images or large datasets in-browser can be slow.
- You can extend the model or add saving/loading weights as needed.
- The loss function combines reconstruction MSE and KL divergence for the VAE.
If you want me to add features like saving the model or interactive encoding/decoding, just ask!