How to use tensorflow.js in react.js — Sentimental Analysis | by Manfye Goh | Towards Data Science

In March 2018, Google announced Tensorflow.js version 1.0, which enable developer to use machine learning (ML) models directly in browser or in Node.js via JavaScript.
Since then I always want to use those fancy pre-trained model published by google in my project such as object detection, pose estimation and etc. It is however, those example and demo are shown in pure JavaScript and there are a less guide on how to use it in a react application.
Inspired by Benson Rua code in Tensorflow.js Community “Show & Tell”. I had decided to write something on using create-react-app + tensorflow.js to encourage more people to join the community:
The ultimate ending of this tutorial is to create a sentimental analysis calculator which can calculate the positivity (1) or negativity (0) of the written sentences. This is particular useful when you need to detect and prevent negative comments in your application.
Demo app here
Create a Create-React-App via the following commands in your terminal:
npx create-react-app tfjs-sentimentcd tfjs-sentiment
Install tensorflow.js as below:
npm install @tensorflow/tfjs 
and start the app
npm start
The model we will be using here is the convolution neural network (CNN) model from tensorflow.js Sentimental Analysis example. It was trained on a set of 25,000 movie reviews from IMDB dataset, labelled as having positive or negative sentiment.
The Model is available here and the metadata is available here. Take a look before we begin our coding.
Basically the model is the trained neural network that will be the “special algorithm” that function to classified your sentences input into positive (1) and negative (0) class.
We must fit the correct input into the model to enable our model to work smoothly. First thing you must know is the model work as a mathematical logic and being trained using mathematical input, it doesn’t understand “words” or “English language” literally. We must change our sentences into some mathematical input in order to get it works. Here come the metadata, the metadata convert the words input into numerical input for example:
book >>> 274cutely >>> 68327
Note: As this tutorial focus on how to use in react, the theory behind these model can refer to word2vec or other NLP theories
A sentences is coded into these numerical input by splitting each words into numerical token:
this is a book >>> 14,9,6,274
Then the numerical tokens are changed to a fixed length (100) sequence in order to change to a 2d tensor
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,9,6,274
Finally, this sequence is then converted to a 2D tensor (basically a matrix) to feed into the model and the magic happens, the model will automatically classified the sentences into positive or negative statement.
If you understand the logic above, it is easily convert it into action.
3.1 Load model and metadata
import * as tf from '@tensorflow/tfjs';//Model and metadata URLconst url = {model: 'https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/model.json',metadata: 'https://storage.googleapis.com/tfjs-models/tfjs/sentiment_cnn_v1/metadata.json'};async function loadModel(url) {try {const model = await tf.loadLayersModel(url.model);setModel(model);} catch (err) {console.log(err);}}async function loadMetadata(url) {try {const metadataJson = await fetch(url.metadata);const metadata = await metadataJson.json();setMetadata(metadata);} catch (err) {console.log(err);}}//React Hookconst [metadata, setMetadata] = useState();const [model, setModel] = useState();useEffect(()=>{tf.ready().then(()=>{loadModel(url)loadMetadata(url)});},[])
3.2 Convert sentences to tensor input:
Here we will setup a function to process the input text function by function according to theory above:
Tokenize each word in the sentences:
const inputText = text.trim().toLowerCase().replace(/(\.|\,|\!)/g, '').split(' ');
Convert the alphabetical token to numerical token using metadata:
//Convert the alphabetical token to numerical token using metadataconst OOV_INDEX = 2;const sequence = inputText.map(word => {let wordIndex = metadata.word_index[word] + metadata.index_from;if (wordIndex > metadata.vocabulary_size) {wordIndex = OOV_INDEX;}return wordIndex;});
Fix the sequence into fix length (truncation and padding) via a padSequences function
const PAD_INDEX = 0;const padSequences = (sequences, maxLen, padding = 'pre', truncating = 'pre', value = PAD_INDEX) => {return sequences.map(seq => {if (seq.length > maxLen) {if (truncating === 'pre') {seq.splice(0, seq.length - maxLen);} else {seq.splice(maxLen, seq.length - maxLen);}}if (seq.length < maxLen) {const pad = [];for (let i = 0; i < maxLen - seq.length; ++i) {pad.push(value);}if (padding === 'pre') {seq = pad.concat(seq);} else {seq = seq.concat(pad);}}return seq;});}const paddedSequence = padSequences([sequence], metadata.max_len);
Lastly, convert the paddedSequence into our tensor2D matrix
const input = tf.tensor2d(paddedSequence, [1, metadata.max_len]);
3.3 Load tensor2D into our model
After you get all the input right, it is the last easy step to use model.predict to classified your input.
const predictOut = model.predict(input);const score = predictOut.dataSync()[0];predictOut.dispose();setScore(score)return score;
3.4 Setup TextField and Button
Install material-ui via npm
npm install @material-ui/core
Then put the code below into your react app, a text box will appear and happy playing with the model!
import {TextField,Button} from '@material-ui/core'const [testText, setText] = useState("");<TextFieldid="standard-read-only-input"label="Type your sentences here"onChange={(e)=> setText(e.target.value)}defaultValue=""value={testText}multilinerows={4}variant="outlined"/>{testText !== "" ?<Button style={{width:"20vh", height:"5vh"}} variant= "outlined" onClick={()=>getSentimentScore(testText)}>Calculate</Button>: <></>}
As a react front-end developer and a data science student, I’m actively seeking a solution to integrate both my data science knowledge and react skill together.
TF.js provide an ease to integrate deep learning model in react, the advantage of this is everything can be done in front end, we don’t need a backend server (e.g fastAPI, flask) or a server-less feature (e.g AWS lambda) to integrate our python based model in which we can take advantage of current free hosting provider such as netlify and vercel.
The drawback of using TF.js is that without a server, all the model of deep learning must be downloaded before they can be use, some model are worth more than 100Mb which is a bad experience to the users as compared to the model that pre-loaded in the server.
Lastly, the developer should choose the appropriate implementation of deep learning model according to the needs.
Thank you for reading, Hope you enjoy it.
Source code is available here