Discover how to use TensorFlow.js in web development! Our step-by-step guide covers setup, integration, and tips for smarter sites.

Book a call with an Expert
Starting a new venture? Need to upgrade your web app? RapidDev builds application with your growth in mind.
// Include TensorFlow.js from CDN in your HTML file
tf.loadLayersModel or tf.loadGraphModel functions, depending on the model format.
// Load a pre-trained model from a URL
tf.loadLayersModel('https://example.com/model/model.json')
.then(model => {
// Model is loaded and ready for prediction
console.log('Model loaded successfully');
})
.catch(error => {
// Handle errors during model loading
console.error('Error loading model:', error);
});
tf.sequential API to specify the neural network layers.model.fit with your data. This function returns a promise, so ensure you handle asynchronous operations properly.
// Create a simple model with one dense layer
const model = tf.sequential();
model.add(tf.layers.dense({
units: 16, // Number of neurons in this layer
activation: 'relu',// Activation function to introduce non-linearity
inputShape: [10] // Input feature size
}));
// Compile the model with an optimizer and loss function
model.compile({
optimizer: 'sgd', // Stochastic Gradient Descent optimizer
loss: 'meanSquaredError'
});
// Assume we have some training data in tensors xTrain and yTrain
// Train the model; model.fit returns a promise for asynchronous handling
model.fit(xTrain, yTrain, {
epochs: 50, // Number of training iterations over the whole dataset
batchSize: 32, // Number of samples per gradient update
}).then(history => {
// Training complete. You can now perform predictions or further evaluations.
console.log('Model training complete');
});
// DOM element to display model prediction results
const predictButton = document.getElementById('predictBtn');
// Bind an event to the button to perform the prediction
predictButton.addEventListener('click', async () => {
// Preprocess input data. In this example, assume inputData is available.
const inputTensor = tf.tensor2d(inputData, [1, inputData.length]);
// Use the model to predict the output
const prediction = model.predict(inputTensor);
// Convert the tensor (prediction) to a regular JavaScript array for display
prediction.array().then(predictionArray => {
// Update the DOM or alert the user with prediction results
document.getElementById('result').innerText = 'Prediction: ' + predictionArray;
});
});
tf.tidy() to automatically clean up intermediate tensors and avoid memory leaks.
// Example of using async/await for prediction with memory management
async function performPrediction(inputData) {
return tf.tidy(() => {
const inputTensor = tf.tensor2d(inputData, [1, inputData.length]);
const prediction = model.predict(inputTensor);
return prediction.dataSync(); // Synchronously get prediction results as a typed array
});
}
// Using the function asynchronously
(async () => {
try {
const result = await performPrediction(someInputData);
console.log('Prediction Result:', result);
} catch (error) {
console.error('Error during prediction:', error);
}
})();
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.Â