Convert Figma logo to code with AI

tensorflow logotfjs

A WebGL accelerated JavaScript library for training and deploying ML models.

18,355
1,918
18,355
510

Top Related Projects

ONNX Runtime: cross-platform, high performance ML inferencing and training accelerator

82,049

Tensors and Dynamic neural networks in Python with strong GPU acceleration

20,763

Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler; for Python, R, Julia, Scala, Go, Javascript and more

Turi Create simplifies the development of custom machine learning models.

29,761

Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more

🤗 Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX.

Quick Overview

TensorFlow.js is an open-source library for machine learning in JavaScript. It allows developers to define, train, and run machine learning models directly in the browser or on Node.js, making ML accessible to a wide range of developers and enabling new use cases for intelligent web applications.

Pros

  • Runs in browsers and Node.js, allowing for client-side ML and serverless deployments
  • Supports transfer learning from pre-trained models
  • Integrates well with the JavaScript ecosystem and existing web technologies
  • Offers both low-level and high-level APIs for flexibility and ease of use

Cons

  • Performance may be slower compared to native implementations on specialized hardware
  • Limited support for some advanced ML techniques compared to full TensorFlow
  • Larger file sizes can impact web application load times
  • Debugging can be challenging due to the nature of tensor operations

Code Examples

  1. Creating and training a simple model:
import * as tf from '@tensorflow/tfjs';

const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

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

model.fit(xs, ys, {epochs: 10}).then(() => {
  model.predict(tf.tensor2d([5], [1, 1])).print();
});
  1. Loading a pre-trained model:
import * as tf from '@tensorflow/tfjs';

async function loadModel() {
  const model = await tf.loadLayersModel('https://example.com/model.json');
  return model;
}

loadModel().then(model => {
  const input = tf.tensor2d([[1, 2, 3, 4]]);
  const prediction = model.predict(input);
  prediction.print();
});
  1. Performing transfer learning:
import * as tf from '@tensorflow/tfjs';

async function performTransferLearning() {
  const baseModel = await tf.loadLayersModel('https://example.com/mobilenet.json');
  
  const layer = baseModel.getLayer('conv_pw_13_relu');
  const truncatedModel = tf.model({inputs: baseModel.inputs, outputs: layer.output});
  
  const newModel = tf.sequential();
  newModel.add(truncatedModel);
  newModel.add(tf.layers.globalAveragePooling2d());
  newModel.add(tf.layers.dense({units: 10, activation: 'softmax'}));
  
  newModel.compile({optimizer: 'adam', loss: 'categoricalCrossentropy'});
  
  return newModel;
}

Getting Started

To get started with TensorFlow.js, follow these steps:

  1. Install the library using npm:

    npm install @tensorflow/tfjs
    
  2. Import TensorFlow.js in your JavaScript file:

    import * as tf from '@tensorflow/tfjs';
    
  3. Create a simple model:

    const model = tf.sequential();
    model.add(tf.layers.dense({units: 1, inputShape: [1]}));
    model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
    
  4. Train the model with some data:

    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});
    
  5. Make predictions:

    const output = model.predict(tf.tensor2d([5], [1, 1]));
    output.print();
    

Competitor Comparisons

ONNX Runtime: cross-platform, high performance ML inferencing and training accelerator

Pros of ONNX Runtime

  • Broader model support: Works with models from various frameworks, not just TensorFlow
  • Better performance optimization: Offers advanced optimizations for different hardware
  • Cross-platform compatibility: Supports a wider range of deployment targets

Cons of ONNX Runtime

  • Steeper learning curve: Requires more setup and configuration compared to TFJS
  • Less JavaScript-specific features: TFJS is tailored for web and JavaScript environments
  • Smaller community: Less extensive ecosystem and community support than TFJS

Code Comparison

ONNX Runtime (Python):

import onnxruntime as ort
session = ort.InferenceSession("model.onnx")
input_name = session.get_inputs()[0].name
output = session.run(None, {input_name: input_data})

TensorFlow.js (JavaScript):

const model = await tf.loadGraphModel('model.json');
const input = tf.tensor(inputData);
const output = model.predict(input);

Both libraries offer ways to load and run models, but ONNX Runtime requires more explicit setup while TFJS provides a more streamlined API for JavaScript developers. ONNX Runtime's approach allows for greater flexibility across different environments, while TFJS is optimized for web-based scenarios.

82,049

Tensors and Dynamic neural networks in Python with strong GPU acceleration

Pros of PyTorch

  • Dynamic computational graphs allow for more flexible and intuitive model development
  • Easier debugging due to Python-native execution and standard debugging tools
  • Strong community support and extensive ecosystem of libraries and tools

Cons of PyTorch

  • Slower deployment in production environments compared to TensorFlow.js
  • Less optimized for mobile and web platforms
  • Steeper learning curve for developers without a strong Python background

Code Comparison

PyTorch:

import torch

x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
z = torch.add(x, y)

TensorFlow.js:

import * as tf from '@tensorflow/tfjs';

const x = tf.tensor([1, 2, 3]);
const y = tf.tensor([4, 5, 6]);
const z = x.add(y);

Summary

PyTorch offers more flexibility and ease of use for research and prototyping, while TensorFlow.js excels in web and mobile deployment. PyTorch's dynamic graphs and Python integration make it popular among researchers, but TensorFlow.js has advantages in production environments and JavaScript ecosystems. The choice between them depends on the specific project requirements and target platforms.

20,763

Lightweight, Portable, Flexible Distributed/Mobile Deep Learning with Dynamic, Mutation-aware Dataflow Dep Scheduler; for Python, R, Julia, Scala, Go, Javascript and more

Pros of MXNet

  • Better performance on distributed systems and multi-GPU setups
  • Supports a wider range of programming languages (Python, C++, R, Julia, etc.)
  • More flexible and customizable for advanced users

Cons of MXNet

  • Smaller community and ecosystem compared to TensorFlow.js
  • Less comprehensive documentation and tutorials
  • Steeper learning curve for beginners

Code Comparison

MXNet (Python):

import mxnet as mx
from mxnet import nd, autograd, gluon

x = nd.array([[1, 2], [3, 4]])
y = nd.array([[5, 6], [7, 8]])
z = x + y

TensorFlow.js (JavaScript):

import * as tf from '@tensorflow/tfjs';

const x = tf.tensor2d([[1, 2], [3, 4]]);
const y = tf.tensor2d([[5, 6], [7, 8]]);
const z = x.add(y);

Both frameworks offer similar basic tensor operations, but MXNet provides more low-level control and flexibility for advanced users. TensorFlow.js is designed specifically for browser and Node.js environments, making it more accessible for web developers. MXNet excels in distributed computing scenarios, while TensorFlow.js focuses on client-side machine learning applications.

Turi Create simplifies the development of custom machine learning models.

Pros of Turicreate

  • Easier to use for beginners with high-level APIs and built-in visualization tools
  • Supports a wider range of machine learning tasks out-of-the-box (e.g., object detection, image classification)
  • Optimized for Apple devices, providing better performance on macOS and iOS

Cons of Turicreate

  • Limited to Python programming language, while TensorFlow.js supports JavaScript
  • Smaller community and ecosystem compared to TensorFlow.js
  • Less frequent updates and potentially slower adoption of cutting-edge ML techniques

Code Comparison

Turicreate (Python):

import turicreate as tc
data = tc.SFrame('data.csv')
model = tc.image_classifier.create(data, target='label', model='resnet-50')
predictions = model.predict(test_data)

TensorFlow.js (JavaScript):

const model = await tf.loadLayersModel('model.json');
const img = tf.browser.fromPixels(imageElement);
const resized = tf.image.resizeBilinear(img, [224, 224]);
const predictions = model.predict(resized);

Both libraries offer straightforward ways to load data, create or load models, and make predictions. Turicreate provides a more high-level API, while TensorFlow.js offers more flexibility and integration with web technologies.

29,761

Composable transformations of Python+NumPy programs: differentiate, vectorize, JIT to GPU/TPU, and more

Pros of JAX

  • Higher performance and better GPU utilization
  • More flexible and customizable for advanced research
  • Supports automatic differentiation and just-in-time compilation

Cons of JAX

  • Steeper learning curve for beginners
  • Smaller ecosystem and fewer pre-built models
  • Less focus on deployment and production use cases

Code Comparison

JAX:

import jax.numpy as jnp
from jax import grad, jit

def f(x):
    return jnp.sum(jnp.sin(x))

grad_f = jit(grad(f))

TFJS:

import * as tf from '@tensorflow/tfjs';

const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

JAX offers a more functional approach with automatic differentiation, while TFJS provides a higher-level API for building and training neural networks in JavaScript. JAX is better suited for research and custom implementations, whereas TFJS excels in web-based machine learning applications and deployment.

🤗 Transformers: State-of-the-art Machine Learning for Pytorch, TensorFlow, and JAX.

Pros of Transformers

  • Extensive pre-trained model library for various NLP tasks
  • Easier to use for complex NLP tasks and transfer learning
  • Strong community support and frequent updates

Cons of Transformers

  • Primarily focused on NLP, less versatile for other ML domains
  • Larger model sizes, potentially higher computational requirements
  • Steeper learning curve for beginners compared to TFJS

Code Comparison

Transformers example:

from transformers import pipeline

classifier = pipeline("sentiment-analysis")
result = classifier("I love this product!")[0]
print(f"Label: {result['label']}, Score: {result['score']:.4f}")

TFJS example:

import * as tf from '@tensorflow/tfjs';

const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});
model.fit(xs, ys, {epochs: 10}).then(() => {
  model.predict(tf.tensor2d([5], [1, 1])).print();
});

Transformers excels in NLP tasks with its pre-trained models, while TFJS offers broader ML capabilities and browser-based deployment. Transformers is Python-centric, whereas TFJS caters to JavaScript developers. Choose based on your project requirements and target environment.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

TensorFlow.js

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

Develop ML in the Browser
Use flexible and intuitive APIs to build models from scratch using the low-level JavaScript linear algebra library or the high-level layers API.

Develop ML in Node.js
Execute native TensorFlow with the same TensorFlow.js API under the Node.js runtime.

Run Existing models
Use TensorFlow.js model converters to run pre-existing TensorFlow models right in the browser.

Retrain Existing models
Retrain pre-existing ML models using sensor data connected to the browser or other client-side data.

About this repo

This repository contains the logic and scripts that combine several packages.

APIs:

Backends/Platforms:

If you care about bundle size, you can import those packages individually.

If you are looking for Node.js support, check out the TensorFlow.js Node directory.

Examples

Check out our examples repository and our tutorials.

Gallery

Be sure to check out the gallery of all projects related to TensorFlow.js.

Pre-trained models

Be sure to also check out our models repository where we host pre-trained models on NPM.

Benchmarks

  • Local benchmark tool. Use this webpage tool to collect the performance related metrics (speed, memory, etc) of TensorFlow.js models and kernels on your local device with CPU, WebGL or WASM backends. You can benchmark custom models by following this guide.
  • Multi-device benchmark tool. Use this tool to collect the same performance related metrics on a collection of remote devices.

Getting started

There are two main ways to get TensorFlow.js in your JavaScript project: via script tags or by installing it from NPM and using a build tool like Parcel, WebPack, or Rollup.

via Script Tag

Add the following code to an HTML file:

<html>
  <head>
    <!-- Load TensorFlow.js -->
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs/dist/tf.min.js"> </script>


    <!-- Place your code in the script tag below. You can also use an external .js file -->
    <script>
      // Notice there is no 'import' statement. 'tf' is available on the index-page
      // because of the script tag above.

      // Define a model for linear regression.
      const model = tf.sequential();
      model.add(tf.layers.dense({units: 1, inputShape: [1]}));

      // Prepare the model for training: Specify the loss and the optimizer.
      model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

      // Generate some synthetic data for training.
      const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
      const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

      // Train the model using the data.
      model.fit(xs, ys).then(() => {
        // Use the model to do inference on a data point the model hasn't seen before:
        // Open the browser devtools to see the output
        model.predict(tf.tensor2d([5], [1, 1])).print();
      });
    </script>
  </head>

  <body>
  </body>
</html>

Open up that HTML file in your browser, and the code should run!

via NPM

Add TensorFlow.js to your project using yarn or npm. Note: Because we use ES2017 syntax (such as import), this workflow assumes you are using a modern browser or a bundler/transpiler to convert your code to something older browsers understand. See our examples to see how we use Parcel to build our code. However, you are free to use any build tool that you prefer.

import * as tf from '@tensorflow/tfjs';

// Define a model for linear regression.
const model = tf.sequential();
model.add(tf.layers.dense({units: 1, inputShape: [1]}));

// Prepare the model for training: Specify the loss and the optimizer.
model.compile({loss: 'meanSquaredError', optimizer: 'sgd'});

// Generate some synthetic data for training.
const xs = tf.tensor2d([1, 2, 3, 4], [4, 1]);
const ys = tf.tensor2d([1, 3, 5, 7], [4, 1]);

// Train the model using the data.
model.fit(xs, ys).then(() => {
  // Use the model to do inference on a data point the model hasn't seen before:
  model.predict(tf.tensor2d([5], [1, 1])).print();
});

See our tutorials, examples and documentation for more details.

Importing pre-trained models

We support porting pre-trained models from:

Various ops supported in different backends

Please refer below :

Find out more

TensorFlow.js is a part of the TensorFlow ecosystem. For more info:

Thanks, BrowserStack, for providing testing support.

NPM DownloadsLast 30 Days