I'll create a comprehensive HTML file with embedded JavaScript that uses TensorFlow.js to train a Variational Autoencoder (VAE) on uploaded image folders. Here's a complete implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image VAE Trainer</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.16.0/dist/tf.min.js"></script>
<style>
body { font-family: Arial, sans-serif; max-width: 800px; margin: auto; padding: 20px; }
#imagePreview { display: flex; flex-wrap: wrap; gap: 10px; }
#imagePreview img { max-width: 100px; max-height: 100px; }
</style>
</head>
<body>
<h1>Variational Autoencoder Image Trainer</h1>
<input type="file" id="imageUpload" webkitdirectory multiple accept="image/*">
<div id="imagePreview"></div>
<button id="trainButton" disabled>Train VAE</button>
<div id="trainingStatus"></div>
<script>
class VariationalAutoencoder {
constructor(inputShape) {
this.inputShape = inputShape;
this.latentDim = 32;
this.encoder = this.createEncoder();
this.decoder = this.createDecoder();
}
createEncoder() {
return tf.sequential({
layers: [
tf.layers.conv2d({
inputShape: this.inputShape,
filters: 32,
kernelSize: 3,
activation: 'relu',
strides: 2,
padding: 'same'
}),
tf.layers.conv2d({
filters: 64,
kernelSize: 3,
activation: 'relu',
strides: 2,
padding: 'same'
}),
tf.layers.flatten(),
tf.layers.dense({
units: this.latentDim * 2
})
]
});
}
createDecoder() {
return tf.sequential({
layers: [
tf.layers.dense({
inputShape: [this.latentDim],
units: 8 * 8 * 64
}),
tf.layers.reshape({targetShape: [8, 8, 64]}),
tf.layers.conv2dTranspose({
filters: 64,
kernelSize: 3,
strides: 2,
activation: 'relu',
padding: 'same'
}),
tf.layers.conv2dTranspose({
filters: 32,
kernelSize: 3,
strides: 2,
activation: 'relu',
padding: 'same'
}),
tf.layers.conv2dTranspose({
filters: this.inputShape[2],
kernelSize: 3,
activation: 'sigmoid',
padding: 'same'
})
]
});
}
async train(images, epochs = 50, batchSize = 32) {
const optimizer = tf.train.adam(0.001);
for (let epoch = 0; epoch < epochs; epoch++) {
for (let i = 0; i < images.length; i += batchSize) {
const batch = images.slice(i, i + batchSize);
const loss = tf.tidy(() => {
const encoderOutput = this.encoder.predict(batch);
const [mu, logVar] = tf.split(encoderOutput, 2, 1);
const sigma = tf.exp(logVar.mul(0.5));
const epsilon = tf.randomNormal(mu.shape);
const z = mu.add(sigma.mul(epsilon));
const reconstructed = this.decoder.predict(z);
const reconstructionLoss = tf.losses.meanSquaredError(batch, reconstructed);
const klLoss = tf.mean(
mu.square().add(sigma.square()).log()
.sub(logVar).sub(1).mul(0.5)
);
return reconstructionLoss.add(klLoss);
});
await optimizer.minimize(() => loss);
document.getElementById('trainingStatus').textContent =
`Epoch ${epoch + 1}/${epochs}, Batch ${i/batchSize + 1}`;
}
}
}
}
document.getElementById('imageUpload').addEventListener('change', async (e) => {
const files = e.target.files;
const imagePreview = document.getElementById('imagePreview');
const images = [];
for (let file of files) {
if (file.type.startsWith('image/')) {
const img = await createImageElement(file);
imagePreview.appendChild(img);
const canvas = document.createElement('canvas');
canvas.width = 64;
canvas.height = 64;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, 64, 64);
const tensor = tf.browser.fromPixels(canvas)
.toFloat()
.div(255.0)
.expandDims(0);
images.push(tensor);
}
}
const trainButton = document.getElementById('trainButton');
trainButton.disabled = false;
trainButton.onclick = async () => {
const vae = new VariationalAutoencoder([64, 64, 3]);
await vae.train(images);
alert('Training Complete!');
};
});
function createImageElement(file) {
return new Promise((resolve) => {
const img = document.createElement('img');
img.file = file;
img.onload = () => resolve(img);
const reader = new FileReader();
reader.onload = (e) => img.src = e.target.result;
reader.readAsDataURL(file);
});
}
</script>
</body>
</html>
This HTML file provides a complete implementation for training a Variational Autoencoder using TensorFlow.js with the following features:
-
Image Upload:
- Users can upload a folder of images
- Images are automatically resized to 64x64 pixels
- Thumbnails are displayed for preview
-
VAE Architecture:
- Convolutional encoder with 32 and 64 filters
- Latent space dimension of 32
- Convolutional decoder with transposed convolutions
- Reconstruction and KL divergence loss
-
Training Process:
- Uses Adam optimizer
- Configurable epochs (default 50)
- Batch training
- Real-time training status updates
-
Key Components:
- TensorFlow.js for tensor operations
- Image preprocessing
- VAE model definition
- Training loop with loss computation
To use:
- Open the HTML file in a modern browser
- Click "Choose Files" and select an image folder
- Click "Train VAE" to start training
Note: Performance depends on image dataset and browser capabilities. Large datasets might take significant time.
Recommendations for improvement:
- Add more hyperparameter controls
- Implement visualization of latent space
- Add model save/load functionality
Would you like me to elaborate on any part of the implementation?