Okay, here is a single HTML file that contains the necessary HTML, CSS, and JavaScript to implement a Variational Autoencoder (VAE) using TensorFlow.js. It allows the user to select a folder, loads images, resizes them to 64x64, converts them to tensors, builds and trains a VAE model, and displays training progress using TensorFlow.js Vis.
Important Considerations & Limitations:
- Memory Usage: Loading a large folder of images directly into browser memory as tensors (
tf.tensor4d) can consume significant resources and potentially crash the browser, especially for high-resolution images or many files. This implementation is a simple demonstration and might not be suitable for very large datasets.
- Training Time: Training a VAE in the browser can be slow depending on the dataset size, model complexity, and the user's hardware.
- Folder Upload: The
webkitdirectory attribute is non-standard but widely supported by modern browsers to enable folder selection.
- Model Architecture: The VAE architecture is a basic convolutional one suitable for 64x64 images. You might need to adjust it for different image sizes or complexities.
- Loss Calculation: VAE training requires a custom loss function (reconstruction loss + KL divergence). This is handled using
tf.variableGrads within a custom training loop.
- User Interface: The UI is minimal, focusing on file selection and status/progress display.
<!DOCTYPE html>
<html>
<head>
<title>TensorFlow.js VAE Trainer (Image Folder)</title>
<!-- TensorFlow.js Library -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest/dist/tf.min.js"></script>
<!-- TensorFlow.js Vis Library for Visualization -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis@latest/dist/tfjs-vis.umd.min.js"></script>
<style>
body { font-family: sans-serif; margin: 20px; }
#container { max-width: 800px; margin: auto; }
#status { margin-top: 15px; padding: 10px; border: 1px solid #ccc; min-height: 30px; }
#visorContainer { margin-top: 20px; }
button { margin-top: 10px; padding: 8px 15px; cursor: pointer; }
input[type="file"] { margin-top: 10px; }
</style>
</head>
<body>
<div id="container">
<h1>Train VAE with Image Folder</h1>
<p>Select a folder containing images (e.g., JPG, PNG). Images will be resized to 64x64 pixels.</p>
<input type="file" id="folderUpload" webkitdirectory directory multiple />
<div id="status">Select a folder to begin...</div>
<div id="visorContainer"></div>
</div>
<script>
// Global variables
let datasetTensor = null;
let encoder, decoder;
let statusElement;
let visContainer;
const IMAGE_SIZE = 64;
const LATENT_DIM = 64; // Dimension of the latent space
const BATCH_SIZE = 32;
const EPOCHS = 20; // Reduced epochs for faster demonstration
const LEARNING_RATE = 0.001;
document.addEventListener('DOMContentLoaded', () => {
statusElement = document.getElementById('status');
visContainer = document.getElementById('visorContainer');
document.getElementById('folderUpload').addEventListener('change', handleFiles);
// Initialize tfjs-vis
tfvis.visor().open(); // Open the visor pane by default
tfvis.visor().togglePinned(); // Pin it for easier viewing
});
async function handleFiles(event) {
const files = event.target.files;
if (files.length === 0) {
statusElement.innerText = 'No folder selected.';
return;
}
statusElement.innerText = `Processing ${files.length} files...`;
const imagePromises = [];
const validImageTypes = ['image/jpeg', 'image/png', 'image/gif']; // Add or remove types as needed
// Use a canvas for resizing
const canvas = document.createElement('canvas');
canvas.width = IMAGE_SIZE;
canvas.height = IMAGE_SIZE;
const ctx = canvas.getContext('2d');
for (let i = 0; i < files.length; i++) {
const file = files[i];
if (!validImageTypes.includes(file.type)) {
console.warn(`Skipping file ${file.name}: Not a supported image type.`);
continue;
}
imagePromises.push(new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => {
const img = new Image();
img.onload = () => {
// Draw image to canvas and resize
ctx.clearRect(0, 0, IMAGE_SIZE, IMAGE_SIZE);
ctx.drawImage(img, 0, 0, IMAGE_SIZE, IMAGE_SIZE);
const imageData = ctx.getImageData(0, 0, IMAGE_SIZE, IMAGE_SIZE);
// Convert ImageData to tensor (normalized [0, 1])
// tf.browser.fromPixels creates a [height, width, channels] tensor
const tensor = tf.browser.fromPixels(imageData).div(255.0);
// Add a batch dimension [1, height, width, channels]
resolve(tensor.expandDims(0));
};
img.onerror = reject;
img.src = e.target.result;
};
reader.onerror = reject;
reader.readAsDataURL(file);
}));
// Update status periodically during loading
if ((i + 1) % 50 === 0 || (i + 1) === files.length) {
statusElement.innerText = `Loading and resizing image ${i + 1} of ${files.length}...`;
// Allow the UI to update
await tf.nextFrame();
}
}
try {
const tensors = await Promise.all(imagePromises);
// Filter out any promises that might have failed
const validTensors = tensors.filter(t => t != null);
if (validTensors.length === 0) {
statusElement.innerText = 'No valid images found or processed.';
return;
}
// Concatenate all tensors into a single dataset tensor [numImages, 64, 64, 3]
// Dispose of individual tensors after concatenation
tf.tidy(() => {
if (datasetTensor) {
datasetTensor.dispose(); // Dispose previous dataset if exists
}
datasetTensor = tf.concat(validTensors, 0);
});
validTensors.forEach(t => t.dispose()); // Dispose the individual tensors
statusElement.innerText = `Loaded ${datasetTensor.shape[0]} images. Data shape: ${datasetTensor.shape}. Building and training model...`;
await tf.nextFrame(); // Allow status to update
// Start training
await trainVAE(datasetTensor);
} catch (error) {
console.error("Error processing files:", error);
statusElement.innerText = `Error processing files: ${error.message}`;
} finally {
// Clean up the temporary canvas
canvas.remove();
}
}
function buildVAE() {
const originalDim = IMAGE_SIZE * IMAGE_SIZE * 3; // 64*64*3
const inputShape = [IMAGE_SIZE, IMAGE_SIZE, 3];
// --- Encoder ---
// Input: (batch_size, 64, 64, 3)
// Output: z_mean (batch_size, latent_dim), z_log_var (batch_size, latent_dim)
encoder = tf.sequential({
layers: [
tf.layers.conv2d({
inputShape: inputShape,
filters: 32,
kernelSize: 3,
strides: 2,
activation: 'relu',
padding: 'same'
}), // 32x32x32
tf.layers.conv2d({
filters: 64,
kernelSize: 3,
strides: 2,
activation: 'relu',
padding: 'same'
}), // 16x16x64
tf.layers.conv2d({
filters: 128,
kernelSize: 3,
strides: 2,
activation: 'relu',
padding: 'same'
}), // 8x8x128
tf.layers.flatten(), // Flatten to a vector
tf.layers.dense({ units: LATENT_DIM, name: 'z_mean' }), // Output latent mean
tf.layers.dense({ units: LATENT_DIM, name: 'z_log_var' }) // Output latent log-variance
]
});
// --- Decoder ---
// Input: (batch_size, latent_dim) - This is z
// Output: (batch_size, 64, 64, 3) - The reconstructed image
const decoderInput = tf.layers.input({ shape: [LATENT_DIM] });
// Project latent space back to spatial dimension (e.g., 4x4 with filters)
const denseDecoder = tf.layers.dense({ units: 8 * 8 * 128, activation: 'relu' }).apply(decoderInput);
const reshapeDecoder = tf.layers.reshape({ targetShape: [8, 8, 128] }).apply(denseDecoder);
const convTranspose1 = tf.layers.conv2dTranspose({
filters: 64,
kernelSize: 3,
strides: 2,
activation: 'relu',
padding: 'same'
}).apply(reshapeDecoder); // 16x16x64
const convTranspose2 = tf.layers.conv2dTranspose({
filters: 32,
kernelSize: 3,
strides: 2,
activation: 'relu',
padding: 'same'
}).apply(convTranspose1); // 32x32x32
// Output layer: recreate 3 channels with sigmoid activation
const decoderOutput = tf.layers.conv2dTranspose({
filters: 3, // RGB channels
kernelSize: 3,
strides: 2,
activation: 'sigmoid', // Output values between 0 and 1
padding: 'same'
}).apply(convTranspose2); // 64x64x3
decoder = tf.model({ inputs: decoderInput, outputs: decoderOutput });
console.log("Encoder Model:");
encoder.summary();
console.log("Decoder Model:");
decoder.summary();
}
// Reparameterization trick: sample z from mean and log-variance
function sampling(args) {
return tf.tidy(() => {
const zMean = args[0];
const zLogVar = args[1];
const batchSize = zMean.shape[0];
const latentDim = zMean.shape[1];
// Epsilon from standard normal distribution
const epsilon = tf.randomNormal([batchSize, latentDim]);
// z = mean + stddev * epsilon
// stddev = exp(0.5 * log_var)
const z = zMean.add(tf.exp(zLogVar.mul(0.5)).mul(epsilon));
return z;
});
}
// VAE Loss function
function vaeLoss(original, reconstruction, zMean, zLogVar) {
return tf.tidy(() => {
// 1. Reconstruction Loss (Binary Cross-Entropy is common for VAEs on [0,1] pixel data)
// We sum over the spatial and channel dimensions and then take the mean over the batch.
// tf.losses.sigmoidCrossEntropy returns mean over trailing dims by default,
// but we want sum over image dims and mean over batch.
const reconstructionLoss = tf.sum(tf.losses.sigmoidCrossEntropy(original, reconstruction), [1, 2, 3]);
const meanReconstructionLoss = tf.mean(reconstructionLoss);
// 2. KL Divergence Loss
// KL = -0.5 * sum(1 + log(sigma^2) - mu^2 - sigma^2)
// In terms of z_mean (mu) and z_log_var (log(sigma^2))
const klLoss = tf.sum(
tf.mul(-0.5, tf.add(1, tf.sub(zLogVar, tf.add(tf.square(zMean), tf.exp(zLogVar)))))
, 1);
const meanKlLoss = tf.mean(klLoss);
// Total VAE Loss
// Note: Beta-VAE uses a weight 'beta' for the KL term. Using beta=1 here.
const totalLoss = meanReconstructionLoss.add(meanKlLoss);
return totalLoss;
});
}
async function trainVAE(data) {
buildVAE(); // Define the encoder and decoder models
const optimizer = tf.train.adam(LEARNING_RATE);
const numImages = data.shape[0];
const numBatches = Math.ceil(numImages / BATCH_SIZE);
statusElement.innerText = `Starting training for ${EPOCHS} epochs...`;
// Setup tfjs-vis for monitoring loss
const metrics = ['loss', 'reconstruction_loss', 'kl_loss'];
const container = {
name: 'VAE Training', tab: 'Training'
};
const fitCallbacks = tfvis.show.fitCallbacks(container, metrics, {
callbacks: ['onTrainBegin', 'onEpochEnd', 'onBatchEnd']
});
await tf.nextFrame(); // Allow UI to update
for (let epoch = 0; epoch < EPOCHS; epoch++) {
statusElement.innerText = `Epoch ${epoch + 1}/${EPOCHS}...`;
// Shuffle data at the start of each epoch
const shuffledIndices = tf.util.createShuffledIndices(numImages);
const shuffledData = tf.gather(data, shuffledIndices);
let epochLoss = 0;
await fitCallbacks.onEpochBegin(epoch);
for (let i = 0; i < numBatches; i++) {
const batchStartIndex = i * BATCH_SIZE;
const batchEndIndex = Math.min(batchStartIndex + BATCH_SIZE, numImages);
const batch = shuffledData.slice(batchStartIndex, batchEndIndex - batchStartIndex);
// Use tf.variableGrads to get gradients for custom loss
const grads = tf.variableGrads(() => {
const [zMean, zLogVar] = encoder.apply(batch);
const z = sampling([zMean, zLogVar]); // Use sampling function
const reconstruction = decoder.apply(z);
const loss = vaeLoss(batch, reconstruction, zMean, zLogVar);
// Optional: Separate losses for monitoring (only calculate here, not return for grad computation)
const recLossBatch = tf.mean(tf.sum(tf.losses.sigmoidCrossEntropy(batch, reconstruction), [1, 2, 3]));
const klLossBatch = tf.mean(tf.sum(tf.mul(-0.5, tf.add(1, tf.sub(zLogVar, tf.add(tf.square(zMean), tf.exp(zLogVar))))), 1));
// Report loss for the batch
fitCallbacks.onBatchEnd(i * BATCH_SIZE, {
loss: loss.dataSync()[0],
reconstruction_loss: recLossBatch.dataSync()[0],
kl_loss: klLossBatch.dataSync()[0]
});
// Dispose intermediate tensors used only for reporting
recLossBatch.dispose();
klLossBatch.dispose();
return loss; // The loss tensor needed for gradient calculation
}, encoder.trainableVariables.concat(decoder.trainableVariables)); // Train both encoder and decoder
// Apply gradients and dispose
optimizer.applyGradients(grads.grads);
tf.dispose(grads.grads); // Dispose gradients
// Accumulate loss for epoch reporting
const batchLossValue = grads.value.dataSync()[0];
epochLoss += batchLossValue;
// Dispose batch and value tensor
batch.dispose();
grads.value.dispose();
// Allow UI to update periodically or on every batch if desired
if (i % 10 === 0 || i === numBatches - 1) {
await tf.nextFrame();
}
}
const avgEpochLoss = epochLoss / numBatches;
console.log(`Epoch ${epoch + 1}/${EPOCHS}, Loss: ${avgEpochLoss.toFixed(4)}`);
await fitCallbacks.onEpochEnd(epoch, { loss: avgEpochLoss });
// Dispose shuffled data at the end of the epoch
shuffledData.dispose();
}
statusElement.innerText = `Training finished after ${EPOCHS} epochs.`;
// Optional: Display example reconstructions or generations here
// Requires adding more UI elements and logic
console.log("Training complete.");
console.log("Encoder and Decoder models are available globally for inspection/inference.");
}
// Helper function to resize image using canvas
// (Moved inside handleFiles to avoid global canvas and improve scope)
// function resizeImage(imgElement, targetSize) { ... }
// Helper function to convert ImageData to Tensor and normalize
// (Functionality moved inside handleFiles for inline processing)
// function imageDataToTensor(imageData) { ... }
</script>
</body>
</html>
How to Use:
- Save the code above as a single HTML file (e.g.,
vae_trainer.html).
- Open the file in a modern web browser that supports
webkitdirectory (Chrome, Firefox, Edge, Opera). Safari might require special settings or may not support it fully.
- Click the "Choose Folder" button.
- Select a folder containing your image files.
- The application will load, resize, and process the images into a TensorFlow.js tensor.
- The VAE model will be built and training will start.
- The TensorFlow.js Vis panel will appear (usually on the right side) showing the training loss curves.
- The status text below the button will update with progress information.
Customization:
- Image Types: Modify the
validImageTypes array in handleFiles to include/exclude image formats.
- Image Size: Change the
IMAGE_SIZE constant. You might need to adjust the buildVAE architecture (especially stride values and initial dense layer size) if you change this significantly.
- Latent Dimension: Adjust the
LATENT_DIM constant.
- Hyperparameters: Modify
BATCH_SIZE, EPOCHS, LEARNING_RATE.
- VAE Architecture: Modify the layers in the
encoder and decoder definitions in buildVAE.
- Visor: Use
tfvis.visor().close() or tfvis.visor().toggleVisible() if you don't want the visor open by default.
Remember the memory limitations, especially when dealing with large datasets. For professional use or very large datasets, server-side training is generally more appropriate.