Follow our step-by-step guide on client-side ML with TensorFlow.js and build AI models directly in your browser.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
This guide will walk you through technical challenges you might face when implementing machine learning directly within the client (browser) environment using TensorFlow.js. It covers loading the library, preparing data, constructing models, running inference, handling on-device training, integrating with UI events, and managing memory. Every technical term is explained along the way for clarity.
// Include TensorFlow.js via CDN in your HTML file
// Optionally, for pre-trained models, you can include additional libraries such as the layers library
// Example: Converting an image from an HTML canvas into a tensor
const canvas = document.getElementById('canvasElement'); // Your canvas element
const imageData = canvas.getContext('2d').getImageData(0, 0, canvas.width, canvas.height);
// tf.browser.fromPixels converts image data (pixels) into a tensor representation
const tensor = tf.browser.fromPixels(imageData).toFloat();
// Normalize the tensor between 0 and 1 if necessary for your model
const normalizedTensor = tensor.div(tf.scalar(255));
// Load a model from a URL
const modelUrl = 'https://example.com/path/to/your/model.json';
tf.loadLayersModel(modelUrl)
.then(model => {
// Model is loaded and ready for inference
console.log('Model loaded successfully!');
// Example: run inference on preprocessed tensor image
const prediction = model.predict(normalizedTensor.expandDims(0));
prediction.print();
})
.catch(error => {
console.error('Error loading the model:', error);
});
// Define a simple sequential model
const model = tf.sequential();
// Add a dense layer with 16 neurons and input shape corresponding to your data features
model.add(tf.layers.dense({units: 16, activation: 'relu', inputShape: [10]}));
// Add an output layer with a softmax function for classification (e.g., 3 classes)
model.add(tf.layers.dense({units: 3, activation: 'softmax'}));
// Compile the model with an optimizer and loss function
model.compile({
optimizer: 'adam', // Adam is an optimization algorithm that adjusts learning rates dynamically
loss: 'categoricalCrossentropy', // Suitable for multi-class classification
metrics: ['accuracy']
});
// Dummy training data
const xs = tf.randomNormal([100, 10]); // 100 samples, 10 features each
const ys = tf.oneHot(tf.floor(tf.randomUniform([100], 0, 3)), 3); // 100 samples, 3 classes one-hot encoded
// Train the model in the browser
model.fit(xs, ys, {
epochs: 10, // Number of training iterations over the entire dataset
callbacks: {
onEpochEnd: (epoch, logs) => {
console.log(`Epoch ${epoch}: loss = ${logs.loss}`);
}
}
}).then(() => {
console.log('Training complete.');
});
// Assume you have a function that captures an image frame from a video element
async function runInference() {
// Capture image data from a video element
const video = document.getElementById('videoElement');
// Create a tensor from the video frame
const videoTensor = tf.browser.fromPixels(video).toFloat().div(tf.scalar(255));
const resizedTensor = tf.image.resizeBilinear(videoTensor, [224, 224]); // Resize to match model input
// Expand dimensions to match model's input shape (batch size of 1)
const input = resizedTensor.expandDims(0);
// Run prediction
const output = model.predict(input);
// Process the output, e.g. pick the class with the highest probability
output.argMax(-1).print();
// Dispose unused tensors to free memory
tf.dispose([videoTensor, resizedTensor, input, output]);
// Request the next frame to prevent blocking UI
requestAnimationFrame(runInference);
}
runInference();
function processFrame() {
tf.tidy(() => {
const video = document.getElementById('videoElement');
const videoTensor = tf.browser.fromPixels(video).toFloat().div(tf.scalar(255));
const resizedTensor = tf.image.resizeBilinear(videoTensor, [224, 224]);
const input = resizedTensor.expandDims(0);
// Make a prediction inside the tidy block
const output = model.predict(input);
output.argMax(-1).print();
});
requestAnimationFrame(processFrame);
}
processFrame();
// Example: Start training when a user clicks a button
document.getElementById('trainButton').addEventListener('click', () => {
model.fit(xs, ys, {
epochs: 10,
callbacks: {
onEpochEnd: (epoch, logs) => {
// Update UI element with the current loss value
document.getElementById('status').innerText = `Epoch ${epoch}: loss = ${logs.loss}`;
}
}
}).then(() => {
document.getElementById('status').innerText = 'Training complete!';
});
});
From startups to enterprises and everything in between, see for yourself our incredible impact.
Need a dedicated strategic tech and growth partner? Discover what RapidDev can do for your business! Book a call with our team to schedule a free, no-obligation consultation. We’ll discuss your project and provide a custom quote at no cost.Â