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.


  2. 2.


    • 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">
      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, {
              []: {
                  []: { $set: parseInt( }
      Adding new items
      const handleAddItem = () => {
              { x: 1, y: 1 }
      And also changes into the model's properties
      const handleModelChange = (e) => setModelState({
          []: [parseInt(],
    • 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>
          {, index) => {
              return (
                  <div key={index} className="row">
                          className="field field-x column"
                          type="number" pattern="[0-9]*" />
                          className="field field-y column"
                          type="number" />
              className="button-add-example button--green"
              className="button-train button--green"
    • 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>
              className="field element"
              placeholder="Enter an integer number" /><br />
          <div className="element">
              className="element button--green"
  3. 3.


    • 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) => {
          // 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.
, ys, { epochs: 250 }).then(() => {
                  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];
              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
      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.


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.

Integrating Nodejs and Maven using The Maven Frontend Plugin

In this tutorial I show how to integrate nodejs with maven using the Maven Frontend Plugin, above is the vid and below you will find some useful notes. 1. Pre-reqs Have access to an Adobe Experience Manager instance if you want to install the AEM application and test it. The same pom configs shown here can be used for different types of applications 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. Creating the base app