Friday, December 20, 2024

TensorFlow.js Tutorial

 TensorFlow.js is a JavaScript library for training and deploying machine learning models in the browser and on Node.js. Here's a step-by-step tutorial to help you get started:


1. What is TensorFlow.js?

TensorFlow.js enables you to:

  • Run pre-trained models in the browser.
  • Retrain existing models with new data.
  • Build and train models from scratch.

Advantages:

  • No server-side dependencies.
  • Exploit browser's GPU for computation.
  • Accessible to front-end developers.

2. Setup TensorFlow.js

In the Browser

Include the TensorFlow.js library in your HTML file:

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

In Node.js

Install TensorFlow.js via npm:

npm install @tensorflow/tfjs

3. Key Concepts

Tensors

Tensors are the core data structure in TensorFlow.js. They are multi-dimensional arrays.

const tensor = tf.tensor([1, 2, 3, 4], [2, 2]); // 2x2 matrix
tensor.print();

Operations

Perform mathematical operations on tensors.

const a = tf.tensor([1, 2]);
const b = tf.tensor([3, 4]);
const result = a.add(b);
result.print(); // [4, 6]

Memory Management

Dispose of tensors when they're no longer needed.

tensor.dispose();

4. Loading Pre-Trained Models

Load a Model from a URL:

const model = await tf.loadLayersModel('https://path-to-model/model.json');

Use the Model:

const prediction = model.predict(tf.tensor([data]));
prediction.print();

5. Building a Model

Sequential Model

Define a simple feedforward neural network.

const model = tf.sequential();
model.add(tf.layers.dense({units: 32, activation: 'relu', inputShape: [10]}));
model.add(tf.layers.dense({units: 1}));

Compile the Model

Specify the optimizer, loss function, and metrics.

model.compile({
  optimizer: 'sgd',
  loss: 'meanSquaredError',
  metrics: ['mse']
});

Train the Model

const xs = tf.tensor2d([[1], [2], [3], [4]], [4, 1]);
const ys = tf.tensor2d([[1], [3], [5], [7]], [4, 1]);

await model.fit(xs, ys, {
  epochs: 10
});

6. Deploying Models

In the Browser

Save the trained model locally or to a server.

await model.save('downloads://my-model');

In Node.js

Save the model to the file system.

await model.save('file://./my-model');

7. Visualization Tools

  • Use TensorBoard for training metrics.
  • Visualize tensors with .print().

8. Real-World Examples

Image Classification

Load a pre-trained MobileNet model for classifying images:

const model = await tf.loadGraphModel('https://tfhub.dev/google/tfjs-model/imagenet/mobilenet_v2_100_224/classification/3/default/1');
const img = tf.browser.fromPixels(document.getElementById('image'));
const resized = tf.image.resizeBilinear(img, [224, 224]);
const input = resized.expandDims(0).div(255);
const prediction = model.predict(input);
prediction.print();

This tutorial should help you get started with TensorFlow.js for both training and deployment. If you need further assistance or specific use cases, feel free to ask!

No comments:

Post a Comment

How will AI transform your life in the next 5 years?

 AI is already transforming how we live and work, and over the next 5 years, this transformation is expected to accelerate in several key ar...