Foundations Updated 2026-09 View as Markdown

TensorFlow.js

TensorFlow.js is an open-source hardware-accelerated JavaScript library for training and deploying machine learning models.

TensorFlow.js Tutorial#

TensorFlow.js is an open-source hardware-accelerated JavaScript library for training and deploying machine learning models. It allows you to develop ML models in JavaScript and use them in the browser or in Node.js.

What You'll Learn#

  • Basic tensor operations and data manipulation
  • Creating and training simple neural networks
  • Using pre-trained models for image classification
  • Building a complete machine learning workflow

Installation#

You can use TensorFlow.js in your project by including it via a CDN:

javascript
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@latest"></script>

1. Understanding Tensors - The Building Blocks#

Tensors are the core data structure in TensorFlow.js. Let's start by understanding how to create and manipulate them.

javascript
<script>
// Creating different types of tensors
function exploreTensors() {
  // Scalar (0D tensor)
  const scalar = tf.scalar(3.14);
  
  // Vector (1D tensor)
  const vector = tf.tensor1d([1, 2, 3, 4, 5]);
  
  // Matrix (2D tensor)
  const matrix = tf.tensor2d([[1, 2], [3, 4], [5, 6]]);
  
  // 3D tensor
  const tensor3d = tf.tensor3d([[[1, 2], [3, 4]], [[5, 6], [7, 8]]]);
  
  // Display tensor information
  const output = document.getElementById('tensor-output');
  output.innerHTML = `
    <h4>Tensor Examples:</h4>
    <p>Scalar shape: [${scalar.shape}] - Value: ${scalar.dataSync()}</p>
    <p>Vector shape: [${vector.shape}] - Values: [${vector.dataSync()}]</p>
    <p>Matrix shape: [${matrix.shape}] - Values: [${matrix.dataSync()}]</p>
    <p>3D Tensor shape: [${tensor3d.shape}] - Values: [${tensor3d.dataSync()}]</p>
  `;
  
  // Clean up memory
  scalar.dispose();
  vector.dispose();
  matrix.dispose();
  tensor3d.dispose();
}

exploreTensors();
</script>
<div id="tensor-output"></div>

2. Tensor Operations#

Learn how to perform mathematical operations on tensors.

javascript
<script>
function tensorOperations() {
  // Create two tensors
  const a = tf.tensor2d([[1, 2], [3, 4]]);
  const b = tf.tensor2d([[5, 6], [7, 8]]);
  
  // Basic operations
  const sum = a.add(b);
  const product = a.mul(b);
  const matmul = a.matMul(b);
  
  // Element-wise operations
  const squared = a.square();
  const sqrt = a.sqrt();
  
  const output = document.getElementById('operations-output');
  output.innerHTML = `
    <h4>Tensor Operations:</h4>
    <p>A: [${a.dataSync()}]</p>
    <p>B: [${b.dataSync()}]</p>
    <p>A + B: [${sum.dataSync()}]</p>
    <p>A * B (element-wise): [${product.dataSync()}]</p>
    <p>A @ B (matrix multiplication): [${matmul.dataSync()}]</p>
    <p>A²: [${squared.dataSync()}]</p>
    <p>√A: [${sqrt.dataSync()}]</p>
  `;
  
  // Clean up
  [a, b, sum, product, matmul, squared, sqrt].forEach(t => t.dispose());
}

tensorOperations();
</script>
<div id="operations-output"></div>

3. Hello World Example: Linear Regression#

Let's create a simple linear regression model to predict a value based on a linear relationship.

javascript
<script>
async function learnLinear() {
  // Define a model for linear regression (y = mx + b)
  const model = tf.sequential();
  model.add(tf.layers.dense({units: 1, inputShape: [1]}));

  // Prepare the model for training
  model.compile({
    loss: 'meanSquaredError', 
    optimizer: tf.train.sgd(0.01),
    metrics: ['mse']
  });

  // Generate training data: y = 2x + 1
  const xs = tf.tensor2d([1, 2, 3, 4, 5, 6], [6, 1]);
  const ys = tf.tensor2d([3, 5, 7, 9, 11, 13], [6, 1]);

  // Train the model
  const output = document.getElementById('linear-output');
  output.innerHTML = '<p>Training model...</p>';
  
  await model.fit(xs, ys, {
    epochs: 100,
    callbacks: {
      onEpochEnd: (epoch, logs) => {
        if (epoch % 20 === 0) {
          output.innerHTML += `<p>Epoch ${epoch}: loss = ${logs.loss.toFixed(4)}</p>`;
        }
      }
    }
  });

  // Make predictions
  const prediction1 = model.predict(tf.tensor2d([7], [1, 1]));
  const prediction2 = model.predict(tf.tensor2d([10], [1, 1]));
  
  output.innerHTML += `
    <h4>Predictions:</h4>
    <p>Input: 7, Predicted: ${prediction1.dataSync()[0].toFixed(2)}, Expected: ~15</p>
    <p>Input: 10, Predicted: ${prediction2.dataSync()[0].toFixed(2)}, Expected: ~21</p>
  `;
  
  // Clean up
  xs.dispose();
  ys.dispose();
  prediction1.dispose();
  prediction2.dispose();
}

learnLinear();
</script>
<div id="linear-output"></div>
Exercise

Try it

ready

Expected output

<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/coco-ssd"></script>

<img id="detect-img" crossorigin="anonymous" src="https://images.unsplash.com/photo-1551963831-b3b1ca40c98e?w=400" width="400"/>
<canvas id="detect-canvas" width="400" height="300"></canvas>
<div id="detection-output"></div>

<script>
async function detectObjects() {
  // TODO: Load the COCO-SSD model
  const model = null; // Replace with: await cocoSsd.load();

  // TODO: Get image and canvas elements

  // TODO: Run object detection

  // TODO: Draw bounding boxes and labels

  document.getElementById('detection-output').innerHTML = 'TODO: Implement object detection';
}

detectObjects();
</script>

Get the JavaScript agent pack

A battle-tested AGENTS.md, the review checklist, and the failure-mode cheat sheet for JavaScript. One email, then occasional updates when the tooling shifts. No course pitch.

Unsubscribe in one click. We never sell the list. Or just take the AGENTS.md now — no email needed.