Here’s a self-contained HTML file that lets you pick a folder of images, resizes them to 64×64, defines a simple convolutional Variational Autoencoder in TensorFlow.js, and runs a custom training loop in the browser. Just save this as index.html, open it in Chrome/Edge/Firefox, select your image folder, and hit “Train VAE.”
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>TensorFlow.js VAE Trainer</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>
<style>
body { font-family: sans-serif; margin: 20px; }
#reconstructions canvas { margin: 5px; border: 1px solid #ccc; }
#status { margin-top: 10px; }
</style>
</head>
<body>
<h1>Variational Autoencoder Trainer</h1>
<p>
1) Select a folder of images.<br>
2) Click “Train VAE”.<br>
3) Watch losses and reconstructed samples.
</p>
<input type="file" id="file-input" webkitdirectory multiple accept="image/*"/><br><br>
<button id="train-btn" disabled>Train VAE</button>
<p id="status">No images loaded.</p>
<div id="reconstructions"></div>
<script>
const IMG_SIZE = 64;
const BATCH_SIZE = 32;
const LATENT_DIM = 16;
const EPOCHS = 10;
let imageTensors = [];
document.getElementById('file-input')
.addEventListener('change', async (evt) => {
const files = Array.from(evt.target.files)
.filter(f => f.type.startsWith('image/'));
if (!files.length) return;
imageTensors = [];
document.getElementById('status').innerText = 'Loading images...';
for (const file of files) {
const t = await loadAndProcessImage(file);
imageTensors.push(t);
}
document.getElementById('status')
.innerText = `Loaded ${imageTensors.length} images. Ready to train.`;
document.getElementById('train-btn').disabled = false;
});
document.getElementById('train-btn')
.addEventListener('click', async () => {
document.getElementById('status').innerText = 'Preparing dataset...';
await trainVAE();
});
// Load an image file, draw to offscreen canvas, resize, normalize:
async function loadAndProcessImage(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = () => {
const img = new Image();
img.onload = () => {
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);
let imgTensor = tf.browser.fromPixels(canvas)
.toFloat()
.div(255.0);
resolve(imgTensor);
};
img.src = reader.result;
};
reader.readAsDataURL(file);
});
}
// Build encoder model: inputs → convs → [z_mean, z_log_var]
function buildEncoder() {
const i = tf.input({shape: [IMG_SIZE, IMG_SIZE, 3]});
let x = tf.layers.conv2d({filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(i);
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_DIM}).apply(x);
const zLogVar = tf.layers.dense({units: LATENT_DIM}).apply(x);
return tf.model({inputs: i, outputs: [zMean, zLogVar], name: 'encoder'});
}
// Sampling layer: z = μ + σ * ε
function sampleZ(zMean, zLogVar) {
return tf.tidy(() => {
const eps = tf.randomNormal(zMean.shape);
const std = zLogVar.mul(0.5).exp();
return zMean.add(std.mul(eps));
});
}
// Build decoder model: z→dense→deconv→image
function buildDecoder() {
const zInput = tf.input({shape: [LATENT_DIM]});
let x = tf.layers.dense({units: 16*16*64, activation: 'relu'}).apply(zInput);
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 output = tf.layers.conv2d({filters: 3, kernelSize: 3, padding: 'same', activation: 'sigmoid'}).apply(x);
return tf.model({inputs: zInput, outputs: output, name: 'decoder'});
}
async function trainVAE() {
// Prepare tf.data Dataset
const ds = tf.data.array(imageTensors)
.shuffle(imageTensors.length)
.batch(BATCH_SIZE)
.prefetch(1);
const encoder = buildEncoder();
const decoder = buildDecoder();
const optimizer = tf.train.adam(1e-3);
const statusEl = document.getElementById('status');
const reconDiv = document.getElementById('reconstructions');
reconDiv.innerHTML = '';
for (let epoch = 0; epoch < EPOCHS; epoch++) {
let batch = 0;
const epochLoss = [];
await ds.forEachAsync(async (x) => {
const loss = optimizer.minimize(() => {
// Forward pass
const [zMean, zLogVar] = encoder.apply(x);
const z = sampleZ(zMean, zLogVar);
const xRecon = decoder.apply(z);
// Reconstruction loss (MSE)
const reconLoss = tf.losses.meanSquaredError(x.flatten(), xRecon.flatten())
.mul(x.shape[0])
.mean();
// KL divergence
const klLoss = tf.tidy(() => {
const term = zLogVar.add(1).sub(zMean.square()).sub(zLogVar.exp());
return term.sum().mul(-0.5 / x.shape[0]);
});
return reconLoss.add(klLoss);
}, true);
epochLoss.push(loss.dataSync()[0]);
tf.dispose(loss);
batch++;
});
const avgLoss = epochLoss.reduce((a,b) => a+b, 0) / epochLoss.length;
statusEl.innerText = `Epoch ${epoch+1}/${EPOCHS} — loss: ${avgLoss.toFixed(4)}`;
// Show a reconstructed example
await tf.nextFrame();
showReconstruction(encoder, decoder, reconDiv);
}
statusEl.innerText += ' — Training complete!';
}
function showReconstruction(encoder, decoder, container) {
const zSample = tf.randomNormal([1, LATENT_DIM]);
const recon = decoder.predict(zSample);
const canvas = document.createElement('canvas');
canvas.width = IMG_SIZE; canvas.height = IMG_SIZE;
tf.browser.toPixels(recon.reshape([IMG_SIZE,IMG_SIZE,3]), canvas);
container.appendChild(canvas);
tf.dispose([zSample, recon]);
}
</script>
</body>
</html>
Feel free to tweak the architecture, hyperparameters (layers, filters, latent dim, learning rate, epochs), or loss functions for your own use case. Enjoy!