Okay, this is a substantial task for a single HTML file, but definitely achievable! We'll pack everything in: HTML for the UI, CSS for basic styling, and JavaScript with TensorFlow.js for the VAE logic.
Key Features:
- Folder Upload: User can select a folder of images.
- Image Preprocessing:
- Images are resized to 64x64 pixels.
- Converted to grayscale (simplifies the VAE, but can be RGB).
- Normalized to [0, 1].
- Variational Autoencoder (VAE):
- Encoder: Maps image to latent space parameters (mean and log-variance).
- Sampling Layer (Reparameterization Trick): Samples from the latent distribution.
- Decoder: Maps latent sample back to an image.
- Loss Function: Reconstruction loss (Mean Squared Error) + KL Divergence.
- Training:
- Uses TensorFlow.js
model.fit() or fitDataset().
- Displays training progress (epoch, loss).
- Visualization:
- Shows some original vs. reconstructed images during/after training.
- Allows generating new images from random latent vectors.
Limitations in a Single File:
- Memory: Loading and processing many large images in the browser can be memory-intensive. This example will work best with a moderate number of reasonably sized images initially.
- Performance: Training complex models in the browser is slower than on a dedicated backend with GPUs.
- Error Handling: Will be basic for brevity.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>VAE Image Trainer (TF.js)</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
<style>
body { font-family: sans-serif; margin: 20px; background-color: #f4f4f4; color: #333; }
.container { background-color: #fff; padding: 20px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
h1, h2 { color: #333; }
label { font-weight: bold; margin-right: 10px; }
input[type="file"], input[type="number"], button {
margin: 10px 0; padding: 8px; border-radius: 4px; border: 1px solid #ccc;
}
button { background-color: #007bff; color: white; cursor: pointer; }
button:hover { background-color: #0056b3; }
button:disabled { background-color: #ccc; cursor: not-allowed; }
#logs {
margin-top: 20px; padding: 10px; border: 1px solid #eee;
height: 200px; overflow-y: scroll; background-color: #f9f9f9;
font-family: monospace; white-space: pre-wrap;
}
.canvases { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 20px; }
.canvases canvas { border: 1px solid #ddd; }
.canvas-pair { display: flex; flex-direction: column; align-items: center; }
.canvas-pair p { margin: 2px 0; font-size: 0.8em; }
</style>
</head>
<body>
<div class="container">
<h1>Variational Autoencoder Training with TF.js</h1>
<div>
<label for="imageFolder">Upload Image Folder:</label>
<input type="file" id="imageFolder" webkitdirectory directory multiple accept="image/*">
</div>
<h2>Hyperparameters</h2>
<div>
<label for="latentDim">Latent Dim:</label>
<input type="number" id="latentDim" value="32" min="2">
</div>
<div>
<label for="epochs">Epochs:</label>
<input type="number" id="epochs" value="50" min="1">
</div>
<div>
<label for="batchSize">Batch Size:</label>
<input type="number" id="batchSize" value="16" min="1">
</div>
<div>
<label for="learningRate">Learning Rate:</label>
<input type="number" id="learningRate" value="0.001" step="0.0001" min="0.00001">
</div>
<div>
<label for="betaKL">KL Divergence Weight (Beta):</label>
<input type="number" id="betaKL" value="1.0" step="0.1" min="0.0">
</div>
<button id="startTrainingBtn" disabled>Load Images & Start Training</button>
<button id="generateSamplesBtn" disabled>Generate New Samples</button>
<h2>Training Logs</h2>
<div id="logs">Awaiting image upload and training...</div>
<h2>Original vs. Reconstructed Samples</h2>
<div id="reconstructionCanvases" class="canvases"></div>
<h2>Generated Samples (from random latent vectors)</h2>
<div id="generatedCanvases" class="canvases"></div>
</div>
<script>
const IMAGE_SIZE = 64;
const CHANNELS = 1; // Grayscale. For RGB, change to 3 and adjust preprocessing.
// UI Elements
const imageFolderInput = document.getElementById('imageFolder');
const latentDimInput = document.getElementById('latentDim');
const epochsInput = document.getElementById('epochs');
const batchSizeInput = document.getElementById('batchSize');
const learningRateInput = document.getElementById('learningRate');
const betaKLInput = document.getElementById('betaKL');
const startTrainingBtn = document.getElementById('startTrainingBtn');
const generateSamplesBtn = document.getElementById('generateSamplesBtn');
const logsDiv = document.getElementById('logs');
const reconstructionCanvasesDiv = document.getElementById('reconstructionCanvases');
const generatedCanvasesDiv = document.getElementById('generatedCanvases');
let imageTensors = [];
let vae, encoder, decoder; // To store model parts
function log(message) {
console.log(message);
logsDiv.textContent += message + '\n';
logsDiv.scrollTop = logsDiv.scrollHeight;
}
imageFolderInput.addEventListener('change', async (event) => {
const files = event.target.files;
if (!files || files.length === 0) {
log('No files selected.');
return;
}
log(`Processing ${files.length} files...`);
startTrainingBtn.disabled = true;
generateSamplesBtn.disabled = true;
imageTensors = []; // Reset
const promises = [];
for (const file of files) {
if (file.type.startsWith('image/')) {
promises.push(loadImageAndPreprocess(file));
}
}
try {
const loadedTensors = await Promise.all(promises);
imageTensors = loadedTensors.filter(t => t !== null); // Filter out any nulls from errors
log(`Successfully loaded and preprocessed ${imageTensors.length} images.`);
if (imageTensors.length > 0) {
startTrainingBtn.disabled = false;
} else {
log('No valid images could be processed.');
}
} catch (error) {
log(`Error loading images: ${error}`);
}
});
async function loadImageAndPreprocess(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
tf.tidy(() => {
const canvas = document.createElement('canvas');
canvas.width = IMAGE_SIZE;
canvas.height = IMAGE_SIZE;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, IMAGE_SIZE, IMAGE_SIZE);
// Get image data and convert to grayscale tensor
let tensor = tf.browser.fromPixels(canvas, CHANNELS);
tensor = tensor.toFloat().div(tf.scalar(255.0)); // Normalize to [0, 1]
// If CHANNELS = 1, fromPixels might still give 3 channels if original is color.
// So, explicitly average if needed.
if (tensor.shape[2] > 1 && CHANNELS === 1) {
tensor = tensor.mean(2, true); // Keep dimensions for consistency
}
tensor = tensor.reshape([IMAGE_SIZE, IMAGE_SIZE, CHANNELS]);
resolve(tensor);
});
};
img.onerror = (err) => {
log(`Error loading image ${file.name}: ${err}`);
resolve(null); // Resolve with null on error to not break Promise.all
};
img.src = event.target.result;
};
reader.onerror = (err) => {
log(`Error reading file ${file.name}: ${err}`);
resolve(null);
};
reader.readAsDataURL(file);
});
}
// --- VAE Model Definition ---
function buildEncoder(latentDim) {
const inputs = tf.input({shape: [IMAGE_SIZE, IMAGE_SIZE, CHANNELS]});
let x = tf.layers.conv2d({
filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'
}).apply(inputs); // 32x32x32
x = tf.layers.conv2d({
filters: 64, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'
}).apply(x); // 16x16x64
x = tf.layers.conv2d({
filters: 128, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'
}).apply(x); // 8x8x128
x = tf.layers.flatten().apply(x);
const zMean = tf.layers.dense({units: latentDim, name: 'z_mean'}).apply(x);
const zLogVar = tf.layers.dense({units: latentDim, name: 'z_log_var'}).apply(x);
return tf.model({inputs: inputs, outputs: [zMean, zLogVar]});
}
function buildDecoder(latentDim) {
const latentInputs = tf.input({shape: [latentDim]});
// Calculate the shape before flattening in encoder
// For 64 -> 32 -> 16 -> 8, the shape is 8x8x128
const denseUnits = 8 * 8 * 128;
let x = tf.layers.dense({units: denseUnits, activation: 'relu'}).apply(latentInputs);
x = tf.layers.reshape({targetShape: [8, 8, 128]}).apply(x);
x = tf.layers.conv2dTranspose({
filters: 128, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'
}).apply(x); // 16x16x128
x = tf.layers.conv2dTranspose({
filters: 64, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'
}).apply(x); // 32x32x64
x = tf.layers.conv2dTranspose({
filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'
}).apply(x); // 64x64x32
const outputs = tf.layers.conv2dTranspose({
filters: CHANNELS, kernelSize: 3, activation: 'sigmoid', padding: 'same'
}).apply(x); // 64x64xCHANNELS
return tf.model({inputs: latentInputs, outputs: outputs});
}
class VAE extends tf.LayersModel {
constructor(encoder, decoder, latentDim, betaKL) {
super({}); // Call parent constructor
this.encoder = encoder;
this.decoder = decoder;
this.latentDim = latentDim;
this.betaKL = tf.scalar(betaKL); // Weight for KL divergence
// Necessary to track layers for serialization, etc.
this.trainableWeights = [].concat(encoder.trainableWeights, decoder.trainableWeights);
}
// This is the forward pass
call(inputs, training = false) {
return tf.tidy(() => {
const [zMean, zLogVar] = this.encoder.apply(inputs, {training: training});
const batch = tf.shape(zMean)[0];
const dim = tf.shape(zMean)[1];
const epsilon = tf.randomNormal([batch, dim]);
// Reparameterization trick: z = z_mean + exp(0.5 * z_log_var) * epsilon
const z = zMean.add(tf.exp(zLogVar.mul(0.5)).mul(epsilon));
const reconstruction = this.decoder.apply(z, {training: training});
// Calculate KL divergence
// kl_loss = -0.5 * sum(1 + z_log_var - z_mean^2 - exp(z_log_var), axis=-1)
const klLoss = zLogVar.add(1).sub(zMean.square()).sub(tf.exp(zLogVar))
.sum(-1).mul(-0.5).mean(); // Mean over batch
this.addLoss(klLoss.mul(this.betaKL)); // Add KL loss to the model's losses
return reconstruction; // This will be yPred for the reconstruction loss
});
}
// Expose a method to get z_mean and z_log_var for other uses if needed
encode(inputs) {
return this.encoder.predict(inputs);
}
decode(z) {
return this.decoder.predict(z);
}
// Override computeLoss if you want full control.
// However, addLoss in call() and specifying reconstruction loss in compile() is often easier.
// For VAE, the 'loss' in compile is the reconstruction loss.
}
function reconstructionLoss(yTrue, yPred) {
// Using Mean Squared Error for reconstruction
return tf.losses.meanSquaredError(yTrue, yPred).mean(); // Ensure it's a scalar
}
// --- Training ---
startTrainingBtn.addEventListener('click', async () => {
if (imageTensors.length === 0) {
log('No images loaded to train.');
return;
}
startTrainingBtn.disabled = true;
generateSamplesBtn.disabled = true;
log('Starting training...');
const LATENT_DIM = parseInt(latentDimInput.value);
const EPOCHS = parseInt(epochsInput.value);
const BATCH_SIZE = parseInt(batchSizeInput.value);
const LEARNING_RATE = parseFloat(learningRateInput.value);
const BETA_KL = parseFloat(betaKLInput.value);
// Dispose previous models if any
if (vae) vae.dispose();
if (encoder) encoder.dispose();
if (decoder) decoder.dispose();
tf.disposeVariables(); // Clear any other lingering variables
encoder = buildEncoder(LATENT_DIM);
decoder = buildDecoder(LATENT_DIM);
vae = new VAE(encoder, decoder, LATENT_DIM, BETA_KL);
const optimizer = tf.train.adam(LEARNING_RATE);
vae.compile({
optimizer: optimizer,
loss: reconstructionLoss, // This is for the reconstruction part of the VAE loss
// metrics: ['mse'] // Can add metrics if desired
});
log('VAE model compiled.');
const trainData = tf.stack(imageTensors);
log(`Training data shape: ${trainData.shape}`);
const dataset = tf.data.array(trainData).shuffle(imageTensors.length).batch(BATCH_SIZE);
log(`Starting training for ${EPOCHS} epochs with batch size ${BATCH_SIZE}...`);
await vae.fitDataset(dataset, {
epochs: EPOCHS,
callbacks: {
onEpochEnd: async (epoch, logs) => {
const totalLoss = logs.loss; // This includes reconstruction + KL (scaled by beta)
log(`Epoch ${epoch + 1}/${EPOCHS} - Loss: ${totalLoss.toFixed(4)}`);
// Display some reconstructions
if ((epoch + 1) % Math.max(1, Math.floor(EPOCHS / 10)) === 0 || epoch + 1 === EPOCHS) {
await displayReconstructions(trainData, 5);
}
},
onTrainEnd: () => {
log('Training finished.');
startTrainingBtn.disabled = false;
generateSamplesBtn.disabled = false;
// Final reconstructions
displayReconstructions(trainData, 10);
trainData.dispose(); // Clean up training data tensor
}
}
});
});
async function displayReconstructions(originalData, numSamples = 5) {
if (!vae || originalData.isDisposed) {
log("Model not trained or data disposed, cannot show reconstructions.");
return;
}
reconstructionCanvasesDiv.innerHTML = ''; // Clear previous
tf.tidy(() => {
const samplesToShow = originalData.slice(0, numSamples);
const reconstructions = vae.predict(samplesToShow); // Get reconstructions
for (let i = 0; i < numSamples; i++) {
const pairDiv = document.createElement('div');
pairDiv.className = 'canvas-pair';
const pOrig = document.createElement('p');
pOrig.textContent = 'Original';
pairDiv.appendChild(pOrig);
const canvasOrig = document.createElement('canvas');
canvasOrig.width = IMAGE_SIZE;
canvasOrig.height = IMAGE_SIZE;
tf.browser.toPixels(samplesToShow.slice([i, 0, 0, 0], [1, IMAGE_SIZE, IMAGE_SIZE, CHANNELS]).squeeze(), canvasOrig);
pairDiv.appendChild(canvasOrig);
const pReco = document.createElement('p');
pReco.textContent = 'Recon.';
pairDiv.appendChild(pReco);
const canvasReco = document.createElement('canvas');
canvasReco.width = IMAGE_SIZE;
canvasReco.height = IMAGE_SIZE;
tf.browser.toPixels(reconstructions.slice([i, 0, 0, 0], [1, IMAGE_SIZE, IMAGE_SIZE, CHANNELS]).squeeze(), canvasReco);
pairDiv.appendChild(canvasReco);
reconstructionCanvasesDiv.appendChild(pairDiv);
}
});
}
generateSamplesBtn.addEventListener('click', () => {
if (!decoder) {
log('Decoder not available. Train the model first.');
return;
}
generatedCanvasesDiv.innerHTML = ''; // Clear previous
const LATENT_DIM = parseInt(latentDimInput.value);
const numSamplesToGenerate = 10;
log(`Generating ${numSamplesToGenerate} new samples...`);
tf.tidy(() => {
// Sample random points from the latent space (standard normal distribution)
const randomLatentVectors = tf.randomNormal([numSamplesToGenerate, LATENT_DIM]);
const generatedImages = decoder.predict(randomLatentVectors);
for (let i = 0; i < numSamplesToGenerate; i++) {
const canvas = document.createElement('canvas');
canvas.width = IMAGE_SIZE;
canvas.height = IMAGE_SIZE;
tf.browser.toPixels(generatedImages.slice([i, 0, 0, 0], [1, IMAGE_SIZE, IMAGE_SIZE, CHANNELS]).squeeze(), canvas);
generatedCanvasesDiv.appendChild(canvas);
}
});
log('New samples generated.');
});
// Initial message
log('TensorFlow.js version: ' + tf.version.tfjs);
if (tf.getBackend() === 'webgl') {
log('Using WebGL backend.');
} else if (tf.getBackend() === 'cpu') {
log('Using CPU backend. For better performance, ensure WebGL is enabled and available.');
} else {
log('Using backend: ' + tf.getBackend());
}
</script>
</body>
</html>
How to Use:
- Save the code above as a single
vae_trainer.html file.
- Open this HTML file in a modern web browser (like Chrome or Firefox).
- Click "Choose Files" (or similar, depending on browser phrasing for folder upload) next to "Upload Image Folder".
- Select a folder containing your images (e.g., JPEGs, PNGs).
- Adjust hyperparameters if desired.
- Click "Load Images & Start Training".
- Monitor the "Training Logs" and "Original vs. Reconstructed Samples".
- Once training is complete, click "Generate New Samples" to see what the VAE has learned to create.
Key JavaScript Sections Explained:
-
loadImageAndPreprocess(file):
- Uses
FileReader to load an image file.
- Creates an
Image object.
- Draws the image onto an offscreen
<canvas> to resize it to IMAGE_SIZExIMAGE_SIZE.
- Uses
tf.browser.fromPixels() to convert canvas content to a tensor.
- Normalizes pixel values to [0, 1].
- Converts to grayscale by averaging channels if
CHANNELS is 1 and the image is color.
- Returns the preprocessed tensor.
-
buildEncoder(latentDim):
- Defines the encoder part of the VAE using
tf.layers.conv2d, tf.layers.flatten, and tf.layers.dense.
- Outputs two tensors:
zMean (mean of the latent distribution) and zLogVar (log variance of the latent distribution).
-
buildDecoder(latentDim):
- Defines the decoder part.
- Takes a latent vector
z as input.
- Uses
tf.layers.dense, tf.layers.reshape, and tf.layers.conv2dTranspose (deconvolution) to reconstruct an image.
- The final layer uses a 'sigmoid' activation to ensure output pixels are in [0, 1].
-
class VAE extends tf.LayersModel:
- This is the core VAE model. TensorFlow.js allows creating custom models by extending
tf.LayersModel.
constructor: Stores the encoder, decoder, latent dimension, and the betaKL weight for the KL divergence.
call(inputs, training): This is the forward pass.
- It gets
zMean and zLogVar from the encoder.
- It performs the reparameterization trick:
z = zMean + exp(0.5 * zLogVar) * epsilon to sample z. epsilon is random noise.
- It passes
z to the decoder to get the reconstruction.
- It calculates the KL divergence loss between the learned latent distribution and a standard normal prior.
This comprehensive example should give you a solid starting point for VAE training in the browser! Remember that browser-based ML has its limits, especially with large datasets or very deep models.