html Copy code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>VAE Trainer with TensorFlow.js</title>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@4.12.0/dist/tf.min.js"></script>
</head>
<body>
<h2>Upload Image Folder to Train a Variational Autoencoder</h2>
<input type="file" id="upload" webkitdirectory directory multiple />
<br><br>
<button id="trainButton" disabled>Train VAE</button>
<p id="status"></p>
<canvas id="canvas" width="64" height="64" style="display: none;"></canvas>
<script>
const uploadInput = document.getElementById('upload');
const trainButton = document.getElementById('trainButton');
const statusEl = document.getElementById('status');
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let imageTensors = [];
// Resize image to 64x64 and convert to tensor
function processImage(file) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = function (e) {
const img = new Image();
img.onload = function () {
ctx.clearRect(0, 0, 64, 64);
ctx.drawImage(img, 0, 0, 64, 64);
const imageData = ctx.getImageData(0, 0, 64, 64);
const imgTensor = tf.browser.fromPixels(imageData).toFloat().div(255).expandDims(0); // shape: [1, 64, 64, 3]
resolve(imgTensor);
};
img.src = e.target.result;
};
reader.readAsDataURL(file);
});
}
uploadInput.addEventListener('change', async (event) => {
imageTensors = [];
const files = Array.from(event.target.files).filter(f => f.type.startsWith('image/'));
statusEl.textContent = `Loading ${files.length} images...`;
for (const file of files) {
const tensor = await processImage(file);
imageTensors.push(tensor);
}
statusEl.textContent = `Loaded ${imageTensors.length} images. Ready to train.`;
trainButton.disabled = false;
});
// VAE model definition
function buildEncoder() {
const input = tf.input({shape: [64, 64, 3]});
let x = tf.layers.conv2d({filters: 32, kernelSize: 3, activation: 'relu', strides: 2, padding: 'same'}).apply(input);
x = tf.layers.conv2d({filters: 64, kernelSize: 3, activation: 'relu', strides: 2, padding: 'same'}).apply(x);
x = tf.layers.flatten().apply(x);
const zMean = tf.layers.dense({units: 32}).apply(x);
const zLogVar = tf.layers.dense({units: 32}).apply(x);
function sampling(args) {
const [zMean, zLogVar] = args;
const epsilon = tf.randomNormal([32]);
return tf.add(zMean, tf.mul(tf.exp(tf.mul(0.5, zLogVar)), epsilon));
}
const z = tf.layers.lambda({function: sampling}).apply([zMean, zLogVar]);
return tf.model({inputs: input, outputs: [z, zMean, zLogVar]});
}
function buildDecoder() {
const input = tf.input({shape: [32]});
let x = tf.layers.dense({units: 16 * 16 * 64, activation: 'relu'}).apply(input);
x = tf.layers.reshape({targetShape: [16, 16, 64]}).apply(x);
x = tf.layers.conv2dTranspose({filters: 64, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(x);
x = tf.layers.conv2dTranspose({filters: 32, kernelSize: 3, strides: 2, activation: 'relu', padding: 'same'}).apply(x);
const output = tf.layers.conv2d({filters: 3, kernelSize: 3, activation: 'sigmoid', padding: 'same'}).apply(x);
return tf.model({inputs: input, outputs: output});
}
function computeVaeLoss(x, xDecodedMean, zMean, zLogVar) {
const reconLoss = tf.losses.meanSquaredError(x, xDecodedMean).mean();
const klLoss = tf.tidy(() =>
tf.mean(tf.sum(tf.add(tf.sub(tf.exp(zLogVar), zLogVar), tf.square(zMean)).sub(1), 1).mul(0.5))
);
return tf.add(reconLoss, klLoss);
}
trainButton.addEventListener('click', async () => {
trainButton.disabled = true;
statusEl.textContent = "Building models...";
const encoder = buildEncoder();
const decoder = buildDecoder();
const optimizer = tf.train.adam(0.001);
const xs = tf.concat(imageTensors); // shape: [batch, 64, 64, 3]
statusEl.textContent = "Training started...";
const numEpochs = 20;
const batchSize = 16;
for (let epoch = 0; epoch < numEpochs; epoch++) {
const numBatches = Math.ceil(xs.shape[0] / batchSize);
let totalLoss = 0;
for (let i = 0; i < numBatches; i++) {
const start = i * batchSize;
const end = (i + 1) * batchSize;
const xBatch = xs.slice(start, end - start);
await tf.nextFrame(); // yield to keep UI responsive
const loss = await optimizer.minimize(() => {
const [z, zMean, zLogVar] = encoder.apply(xBatch);
const xDecoded = decoder.apply(z);
return computeVaeLoss(xBatch, xDecoded, zMean, zLogVar);
}, true);
totalLoss += (await loss.data())[0];
}
statusEl.textContent = `Epoch ${epoch + 1}/${numEpochs}, Loss: ${(totalLoss / numBatches).toFixed(4)}`;
await tf.nextFrame();
}
statusEl.textContent += "\nTraining complete.";
console.log("Encoder:", encoder);
console.log("Decoder:", decoder);
});
</script>
</body>
</html>
Let me know if you want support for grayscale images, saving the model, or visualizing reconstructions!