Intermediate
TensorFlow.js
Train and deploy machine learning models directly in the browser and Node.js using Google's TensorFlow.js library.
Getting Started
HTML - CDN
<!-- Add to your HTML --> <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
Terminal - npm
npm install @tensorflow/tfjs # For Node.js with native C++ bindings (faster): npm install @tensorflow/tfjs-node # For Node.js with GPU support: npm install @tensorflow/tfjs-node-gpu
Loading Pre-trained Models
JavaScript
import * as tf from '@tensorflow/tfjs'; import * as mobilenet from '@tensorflow-models/mobilenet'; // Load MobileNet for image classification const model = await mobilenet.load(); // Classify an image element const img = document.getElementById('my-image'); const predictions = await model.classify(img); predictions.forEach(p => { console.log(`${p.className}: ${(p.probability * 100).toFixed(1)}%`); });
Training in the Browser
JavaScript
// Build a simple model const model = tf.sequential({ layers: [ tf.layers.dense({ inputShape: [4], units: 16, activation: 'relu' }), tf.layers.dense({ units: 3, activation: 'softmax' }) ] }); model.compile({ optimizer: 'adam', loss: 'categoricalCrossentropy', metrics: ['accuracy'] }); // Train with data const xs = tf.tensor2d([[5.1, 3.5, 1.4, 0.2], ...]); const ys = tf.tensor2d([[1, 0, 0], ...]); await model.fit(xs, ys, { epochs: 50, batchSize: 32, validationSplit: 0.2, callbacks: tf.callbacks.earlyStopping({ patience: 5 }) });
Transfer Learning
JavaScript
// Load MobileNet and remove the top layer const mobilenet = await tf.loadLayersModel( 'https://storage.googleapis.com/tfjs-models/tfjs/mobilenet_v1/model.json' ); const layer = mobilenet.getLayer('conv_pw_13_relu'); const truncated = tf.model({ inputs: mobilenet.inputs, outputs: layer.output }); // Add custom classification head const model = tf.sequential(); model.add(tf.layers.flatten({ inputShape: truncated.outputs[0].shape.slice(1) })); model.add(tf.layers.dense({ units: 64, activation: 'relu' })); model.add(tf.layers.dense({ units: 3, activation: 'softmax' })); // Train only the new layers on your custom data
Model Conversion
Terminal
# Convert a Keras/TF model to TensorFlow.js format
pip install tensorflowjs
tensorflowjs_converter \
--input_format=keras \
my_model.h5 \
./tfjs_model/
Memory management: Always dispose of tensors when done with
tensor.dispose() or wrap code in tf.tidy(() => { ... }) to automatically clean up intermediate tensors and prevent memory leaks.
Lilly Tech Systems