Below is a complete HTML file that allows users to upload a folder of images, resizes them to 64x64 pixels, and trains a Variational Autoencoder (VAE) using TensorFlow.js. This example is designed to be self-contained and functional in a browser environment.
html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Train VAE with TensorFlow.js</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
#output {
margin-top: 20px;
white-space: pre-wrap;
}
canvas {
display: none;
}
</style>
</head>
<body>
<h1>Variational Autoencoder Training</h1>
<p>Upload a folder of images to train a VAE:</p>
<input type="file" id="fileInput" webkitdirectory directory multiple />
<button id="trainButton" disabled>Train Model</button>
<div id="output"></div>
<canvas id="resizeCanvas" width="64" height="64"></canvas>
<script>
// Utility function to log messages to the output div
function log(message) {
const outputDiv = document.getElementById('output');
outputDiv.textContent += message + '\n';
}
// Function to resize an image to 64x64
async function resizeImage(image) {
const canvas = document.getElementById('resizeCanvas');
const ctx = canvas.getContext('2d');
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(image, 0, 0, canvas.width, canvas.height);
const resizedImageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
return tf.browser.fromPixels(resizedImageData).div(255.0).expandDims(0); // Normalize to [0, 1]
}
// Load images from the uploaded files
async function loadImages(files) {
const images = [];
for (const file of files) {
if (file.type.startsWith('image/')) {
const img = new Image();
const url = URL.createObjectURL(file);
img.src = url;
await new Promise((resolve) => (img.onload = resolve));
const resizedTensor = await resizeImage(img);
images.push(resizedTensor);
URL.revokeObjectURL(url);
}
}
return tf.concat(images, 0); // Concatenate all tensors into one batch tensor
}
// Define the Variational Autoencoder model
function createVAE() {
const latentDim = 16;
// Encoder
const encoder = tf.sequential();
encoder.add(tf.layers.conv2d({ filters: 32, kernelSize: 3, strides: 2, activation: 'relu', inputShape: [64, 64, 3] }));
encoder.add(tf.layers.conv2d({ filters: 64, kernelSize: 3, strides: 2, activation: 'relu' }));
encoder.add(tf.layers.flatten());
encoder.add(tf.layers.dense({ units: latentDim * 2 }));
// Decoder
const decoder = tf.sequential();
decoder.add(tf.layers.dense({ units: 16 * 16 * 64, activation: 'relu', inputShape: [latentDim] }));
decoder.add(tf.layers.reshape({ targetShape: [16, 16, 64] }));
decoder.add(tf.layers.conv2dTranspose({ filters: 64, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same' }));
decoder.add(tf.layers.conv2dTranspose({ filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same' }));
decoder.add(tf.layers.conv2dTranspose({ filters: 3, kernelSize: 3, strides: 1, activation: 'sigmoid', padding: 'same' }));
// Sampling function
function sample(latentParams) {
const mean = latentParams.slice([0, 0], [-1, latentDim]);
const logVar = latentParams.slice([0, latentDim], [-1, latentDim]);
const epsilon = tf.randomNormal(mean.shape);
return mean.add(logVar.mul(0.5).exp().mul(epsilon));
}
// Full VAE model
const inputs = tf.input({ shape: [64, 64, 3] });
const latentParams = encoder.apply(inputs);
const z = tf.tidy(() => sample(latentParams));
const outputs = decoder.apply(z);
const vae = tf.model({ inputs, outputs });
// Loss function
function vaeLoss(yTrue, yPred) {
const reconstructionLoss = tf.losses.meanSquaredError(yTrue, yPred);
const mean = latentParams.slice([0, 0], [-1, latentDim]);
const logVar = latentParams.slice([0, latentDim], [-1, latentDim]);
const klLoss = tf.mean(
tf.mul(0.5, tf.sum(tf.add(tf.square(mean), tf.exp(logVar)).sub(logVar).sub(1), 1))
);
return reconstructionLoss.add(klLoss);
}
return { vae, encoder, decoder, loss: vaeLoss };
}
// Handle file upload and training
document.getElementById('fileInput').addEventListener('change', async (event) => {
const files = Array.from(event.target.files);
log(`Loaded ${files.length} files.`);
const dataset = await loadImages(files);
log(`Resized images to 64x64. Dataset shape: ${dataset.shape}`);
document.getElementById('trainButton').disabled = false;
document.getElementById('trainButton').addEventListener('click', async () => {
log('Starting training...');
const { vae, loss } = createVAE();
const optimizer = tf.train.adam(0.001);
const batchSize = 32;
const epochs = 10;
for (let epoch = 0; epoch < epochs; epoch++) {
const batchesPerEpoch = Math.ceil(dataset.shape[0] / batchSize);
let totalLoss = 0;
for (let i = 0; i < batchesPerEpoch; i++) {
const batchStart = i * batchSize;
const batchEnd = Math.min(batchStart + batchSize, dataset.shape[0]);
const batch = dataset.slice([batchStart, 0, 0, 0], [batchEnd - batchStart, 64, 64, 3]);
const history = await vae.fit(batch, batch, {
batchSize: batch.shape[0],
epochs: 1,
shuffle: true,
callbacks: {
onBatchEnd: (batch, logs) => {
totalLoss += logs.loss;
},
},
});
}
log(`Epoch ${epoch + 1}/${epochs} completed. Average Loss: ${(totalLoss / batchesPerEpoch).toFixed(4)}`);
}
log('Training complete.');
});
});
</script>
</body>
</html>