Coder Social home page Coder Social logo

react-tensorflow's Introduction

React-Tensorflow

Typed with TypeScript codecov CircleCI npm twitter-badge github-star-badge

A library of React hooks and HOCs written in Typescript to use Tensorflow models in your application! ๐Ÿค–๐Ÿง 

Demo application with Code Examples

Installation

yarn add react-tensorflow
npm i react-tensorflow -S

Peer dependencies

Basic usage

import { useModel } from 'react-tensorflow'

const MyModelComponent = () => {
  const model = useModel({ modelUrl: `${PATH_TO_MODEL}` })

  // ...do something with the model

  return null
}

API

useModel

useModel({
  model?: any,
  modelUrl?: string,
  layers?: boolean,
  onLoadCallback?: (model: GraphModel | LayersModel | null) => void
}): GraphModel | LayersModel | null

If model or modelUrl is omitted useModel will look to find the ModelProvider as it's context for returning the model. When loading a model with this hook, the layers boolean is passed if your TF model should be loaded with the function tf.loadLayersModel otherwise it is assumed the model should be loaded with tf.loadGraphModel. If a model is loaded with modelUrl and an onLoadCallback function is provided, it will be called with the loaded model. This function is intended to be used as a warm up function that could look like this โ€“

(model) => {
  const zeroTensor = tf.zeros([1, 300, 300, 3], 'int32');
  const result = await model.executeAsync(zeroTensor) as tf.Tensor[];
  await Promise.all(result.map(t => t.data()));
  result.map(t => t.dispose());
  zeroTensor.dispose();
}

ModelProvider

<ModelProvider url={string} layers={boolean} onLoadCallback={(model) => void}>
  <App />
</ModelProvider>

Wraps the children in a React Provider to be consumed by Context's in either the useModel hook or withModel HOC. The props passed to this provider are the same as the documented props for useModel.

withModel

withModel(Component: React.ComponentType): JSX.Element

Wraps the provided component in a React Context, passing the model give to the provider as a prop.

useWebcam

useWebcam (options?: {
    width?: number
    height?: number
    facingMode?: string
  }): [React.MutableRefObject<HTMLVideoElement>, tf.Tensor | null]

Provides a ref to be used on a video element, the hook then returns a tensor with shape [1, width, height, 3] where the width and height are either dictated by the element's width & height or the provided argument documented above. The options argument while documented above can infact take all the properties of the MediaStreamConstraints.

๐Ÿ‘‰ All the following hooks use useModel under the hood, therefore accepting any of the args passed to useModel ๐Ÿ‘ˆ

usePrediction

usePrediction (options?: {
  predictConfig?: {},
  useExecute?: boolean = false,
  outputName?: string,
  predictionFunction?: string,
  modelUrl?: string,
  layers?: boolean,
}): [(data: tf.Tensor) => void, tf.Tensor | tf.Tensor[] | tf.NamedTensorMap | null]

Provides a function to set the data you want to use to create a prediction. The data must be in the form of a tensor. It then returns a new tensor as the prediction using either the model set with the ModelProvider component or by passing a modelUrl as an argument as it uses useModel under the hood. You can then perform different actions such as normalizing the data for to classify the original input. By default usePrediction uses .predict, if you want to force the use of .executeAsync set useExecute: true and if you want to use a custom predict function, pass it's name via the predictionFunction key. If you're using a LayersModel you must set outputName.

๐Ÿšซ Using a @tensorflow/tfjs-models model with this hook will cause typescript errors if the model predicition method is called or will simply return null because the model either does not have an executeAsync or predict function or it does, and it has not returned a Tensor. ๐Ÿšซ

๐Ÿ‘‰ All the following hooks use usePrediction under the hood, therefore accepting any of the args passed to usePrediction ๐Ÿ‘ˆ

useClassifier

useClassifer(options?: {
  classes?: {},
  returns?: number,
  modelUrl?: string,
  layers?: boolean,
}): [(data: tf.Tensor) => void, Array<{class: number, probability: number}> | Array<{class: string, probability: number}> | null]

Returns a function to set the data which must be in the form of a tensor. After prediction has been made, returns an array of classifications (be default, the array will have length 5). If the classes argument is provided, the class key in the returned array will be the class at the index of the prediction.

useObjectDetect

useObjectDetect(options?:{
  returns?: number,
  minConfidence?: number,
  classes?: {},
  width?: number,
  height?: number,
  modelUrl?: string,
  layers?: boolean,
}): [(data: tf.Tensor) => void, Array<{class: number, probability: number, boundingBox: number[]}> | Array<{class: string, probability: number, boundingBox: number[]}> | null]

Returns an array with index 0 being a function to set the data. This data must be in the form of a tensor. After a prediction has been made, returns an array of objects detected. Both height and width of the media must be provided to recieve values inside bounding box which will be an array of four numbers โ€“ [left, top, width, height]. minConfidence must be a value between 0 - 1. The hook then returns an array of detected objects (by default, the array will be length 5). If the classes argument is provided, the class key in the returned array will be the class at the index of the prediction as a string.

Contributing

Contributions are very welcome and wanted.

Before submitting a new pull request, please make sure:

  1. Consider if the pull-request should be going to the master branch or the latest release branch.
  2. If merging to master, you have updated the package.json version.
  3. You report your changes into the CHANGELOG file.
  4. make sure you run the test and build script before submitting your merge request.
  5. make sure you've added the documentation of your changes.

react-tensorflow's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

react-tensorflow's Issues

usePrediction should be able to comfortably handle a @tensorflowjs-model model

Expected Behavior

Should be able to return a tensor when using usePrediction with a @tensorflowjs-model model.

Current Behavior

Currently you have to provide the prediction function within the @tensorflow-model library. These prediction functions typically return a data array specific to the model type. e.g. mobilenet returns an image classification. This is not inline with the return value of usePrediction โ€“ Tensor | Tensor[] | NamedTensorMap.

Possible Solution

The infer function in @tensorflowjs-models/mobilenet is exposed and if this is a common theme across the other models.

Steps to Reproduce (for bugs)

n/a

Context

n/a

Your Environment

n/a

  • Version used: n/a
  • Browser Name and version: n/a
  • Operating System and version (desktop or mobile): n/a
  • Link to your project: n/a

useModel hook & ModelProvider should warm up the model if passed modelUrl

Expected Behavior

Model should be warmed up when the model is loaded with modelUrl.

Current Behavior

The model is not warmed up at all.

Possible Solution

Could be something like the following taken from @tensorflow/tfjs-models โ€“

    // Warmup the model.
    const result = await this.model.executeAsync(zeroTensor) as tf.Tensor[];
    await Promise.all(result.map(t => t.data()));
    result.map(t => t.dispose());
    zeroTensor.dispose();

Steps to Reproduce (for bugs)

Context

Your Environment

  • Version used:
  • Browser Name and version:
  • Operating System and version (desktop or mobile):
  • Link to your project:

useDataRef does not update when ref updates

Expected Behavior

Current Behavior

Possible Solution

Steps to Reproduce (for bugs)

Context

Your Environment

  • Version used:
  • Browser Name and version:
  • Operating System and version (desktop or mobile):
  • Link to your project:

Potential memory leak from useWebcam

useWebcam returns a tensor from the webcam image. While it disposes the original image, it doesn't dispose of the processed image. This could be cause of the leak.

Feature request: Webcam object detection example

Webcam object detect example

Context

Looking through the examples / docs it's not really clear how to use useWebcamm with useObjectDetect. Perhaps a basic coco or mobilenet model that predicts from the webcam feed

Your Environment

N/A

usePrediction should not return a tensor

It makes most sense to mimic what tfjs-model libraries do which is convert the tensor.

However a boolean property could be used to not convert the tensor providing it is possible. i.e tfjs-models wouldn't be possible.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.