Ir al contenido principal

Creating a tensorflow.js + react.js simple application in javascript

In this tutorial I will show how to create a really simple Tensorflow.js model and use it for predicting values using React.js, above is the video and below you will find some of the steps followed.
  1. 1.

    Pre-reqs

  2. 2.

    React.js

    • Reactjs is a javascript framework for building user interfaces which is mostly used for creating Single-Page Applications, I am going to use it to create a simple static but interactive site and then deploy it into github pages.
    • First we need to create a React.js app
      npx create-react-app <project-name>
      npx create-react-app simple-reactjs-tensorflow
      
    • Run the app in development mode so that we can make changes in the code and see the results on the browser
      npm start
      
    • Start by creating a simple empty component for the TensorflowExample.js (Don't forget to add it into the App.js file)
      import React, { useState } from 'react';
      
      const TensorflowExample = () => {
          return (
              <div className="tensorflow-example">
              </div>
          );
      };
      
      export default TensorflowExample;
      
    • Install the immutability helper for making changes to the model
      npm install immutability-helper --save
      npm start
      
      Import the immutability helper inside the TensorflowExample.js file
      import update from 'immutability-helper';
      
    • We need to keep the state for the value pairs to hold an array of inputs and outputs so that we can train our new model and the state to hold the properties related to the model.
      //Value pairs state
      const [valuePairsState, setValuePairsState] = useState([
          { x: -1, y: -3 },
          { x: 0, y: -1 },
          { x: 1, y: 1 },
          { x: 2, y: 3 },
          { x: 3, y: 5 },
          { x: 4, y: 7 },
      ]);
      
      //Define the model state
      const [modelState, setModelState] = useState({
          model: null,
          trained: false,
          predictedValue: 'Click on train!',
          valueToPredict: 1,
      });
      
    • Add the handlers for managing changes to the inputs and outputs
      //Event handlers
      const handleValuePairChange = (e) => {
          const updatedValuePairs = update(valuePairsState, {
              [e.target.dataset.index]: {
                  [e.target.name]: { $set: parseInt(e.target.value) }
              }
          })
      
          setValuePairsState(
              updatedValuePairs
          )
      };
      
      Adding new items
      const handleAddItem = () => {
          setValuePairsState([
              ...valuePairsState,
              { x: 1, y: 1 }
          ]);
      };
      
      And also changes into the model's properties
      const handleModelChange = (e) => setModelState({
          ...modelState,
          [e.target.name]: [parseInt(e.target.value)],
      });
      
    • Add the controls for training the model by iterating over the value pairs properties and rendering a field per input and output. Also create a button for adding new items and another one for training the model.
      <div className="train-controls">
          <h2 className="section">Training Data (x,y) pairs</h2>
          <div className="row labels">
              <div className="field-label column">X</div>
              <div className="field-label column">Y</div>
          </div>
      
          {valuePairsState.map((val, index) => {
              return (
                  <div key={index} className="row">
                      <input
                          className="field field-x column"
                          value={val.x}
                          name="x"
                          data-index={index}
                          onChange={handleValuePairChange}
                          type="number" pattern="[0-9]*" />
                      <input
                          className="field field-y column"
                          value={val.y}
                          name="y"
                          data-index={index}
                          onChange={handleValuePairChange}
                          type="number" />
                  </div>
              );
          })}
      
          <button
              className="button-add-example button--green"
              onClick={handleAddItem}>
              +
          </button>
          <button
              className="button-train button--green"
              onClick={handleTrainModel}>
              Train
          </button>
      </div>
      
    • For the prediction controls create an input field to allow the user to enter a value so that its output can be predicted, a field to show the predicted value and a button to perform the actual prediction which will only be enabled once the model has been trained.
      <div className="predict-controls">
          <h2 className="section">Predicting</h2>
          <input
              className="field element"
              value={modelState.valueToPredict}
              name="valueToPredict"
              onChange={handleModelChange}
              type="number"
              placeholder="Enter an integer number" /><br />
          <div className="element">
              {modelState.predictedValue}
          </div>
          <button
              className="element button--green"
              onClick={handlePredict}
              disabled={!modelState.trained}>
              Predict
          </button>
      </div>
      
  3. 3.

    Tensorflow.js

    • Tensorflowjs is a javascript library that allows us to train and use machine learning models on the browser and nodejs.
    • Install tensorflowjs
      npm install --save @tensorflow/tfjs
      
    • And import it into your react app
      import * as tf from '@tensorflow/tfjs';
      
    • Add the train handler and create a simple model that just has one layer, one hidden unit and also that will receive just one input. The model will be compiled using the mean squared error loss function, stochastic gradient descent and will run for 250 epochs.
      const handleTrainModel = () => {
          let xValues = [],
              yValues = [];
      
          valuePairsState.forEach((val, index) => {
              xValues.push(val.x);
              yValues.push(val.y);
          });
      
          // 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' });
          const xs = tf.tensor2d(xValues, [xValues.length, 1]);
          const ys = tf.tensor2d(yValues, [yValues.length, 1]);
      
          // Train the model using the data.
          model.fit(xs, ys, { epochs: 250 }).then(() => {
              setModelState({
                  ...modelState,
                  model: model,
                  trained: true,
                  predictedValue: 'Ready for making predictions',
              });
          });
      }
      
    • Add the predict handler and set the predictedValue property to the output from the model given the value to predict provided by the user.
      const handlePredict = () => {
          // Use the model to do inference on a data point the model hasn't seen before:
          const predictedValue = modelState.model.predict(tf.tensor2d([modelState.valueToPredict], [1, 1])).arraySync()[0][0];
      
          setModelState({
              ...modelState,
              predictedValue: predictedValue,
          });
      }
      
    • Go into the browser, add some more inputs, click on train and try different values.
  4. 4.

    Github Pages

    • To publish our code into github pages first make sure that the package.json file has the homepage property set to “.”
      "homepage": ".",
      
    • Generate the static site and make sure to create a new repository for your project inside GitHub
      npm run build
      
    • Initialize your local repository for the code, add all the files, commit the code, add the repository so that you can push the code into your repo and finally push the code.
      git init
      git add -A
      git commit -m "First version simple tensorflojs + react app"
      git remote add origin https://github.com/drginm/simple-reactjs-tensorflow.git
      git push origin master
      
    • Create a detached branch with the special name gh-pages
      git checkout --orphan gh-pages
      git status
      
    • Delete everything but the build directory and move its contents to the root of your git’s repository, then again add everything, commit the changes and push them into your new gh-pages branch
      git add -A
      git status
      git commit -m "Static site for - simple tensorflojs + react app"
      git push origin gh-pages
      
    • Go into your page by using your github username and the name for the repository we just created and test that the application is working
  5. 5.

Comentarios

Entradas populares de este blog

How to copy files from and to a running Docker container

Sometimes you want to copy files to or from a container that doesn’t have a volume previously created, in this quick tips episode, you will learn how. Above is the vid and below you will find some useful notes. 1. Pre-reqs Have Docker installed 2. Start a Docker container For this video I will be using a Jenkins image as an example, so let’s first download it by using docker pull docker pull jenkins/jenkins:lts

How to create an AEM component using Reactjs

In this tutorial, I will show how to use use Adobe's archetype to create an AEM application with React.js support and also how to add a new React.js component so that it can be added into a page, above is the vid and below you will find some useful notes. In the second part we will see how to configure the Sling Model for the AEM React component. 1. Pre-reqs Have access to an Adobe Experience Manager instance. You will need aem 6.4 Service Pack 2 or newer. Have Maven installed, understand how it works and also understand how to use Adobe's archetype, you can watch my video about maven here: Creating an AEM application using Maven and Adobe's archetype 2.

House price prediction 3/4: What is One Hot Encoding

A series about creating a model using Python and Tensorflow and then importing the model and making predictions using Javascript in a Vue.js application, above is the vid and below you will find some useful notes. Here, in part 3 of this series, I will show what is and how does one hot encoding works. In the first post, called House price prediction 1/4: Using Keras/Tensorflow and python , I talked about how to create a model in python, pre-process a dataset I've already created, train a model, post-process, predict, and finally about creating different files for sharing some information about the data for use on the second part. Then in part 2, called House price prediction 2/4: Using Tensorflow.js, Vue.js and Javascript , I took the model, the data for pre and post processing and after loading everything we were finally able to predict