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

Creating Docker containers for Adobe Experience Manager

This is a Docker tutorial for creating a docker image for the Galen framework, above is the vid and below you will find some of the steps followed. Adobe experience manager is a content management system which in a nutshell is an application that allows us to create web sites to be consumed by end users. You might be familiar with other such applications like wordpress or drupal which serves the same purpose A typical deployment would be comprised of two AEM instances, the author instance used for creating and modifying content, the publish instance which serves the content and finally we have a dispatcher which is a static web server used for caching, load balancing and some security purposes. We can configure an AEM instance to work as an author or publish instance by either changing the file name for the jar file java -jar cq-author-450…

Creating a Mongo replicaset using docker: Mongo replicaset + Nodejs + Docker Compose

This is a Docker tutorial for creating a Mongo replica set using docker compose and also a couple more containers to experiment with the replica set, above is the vid and below you will find some of the steps followed.
StepsPre-reqsHave node.js installedAnd docker installed (make sure you have docker-compose as well)Create a container for defining configurations for a mongo instanceCreate a container for setting up the replica setCreate a simple node app using expressjs and mongoose (A modified version from the previous video)Create a docker-compose file with the mongo and setup containers and two additional containers for experimenting with the replica setBuild, Run and experiment with your new containers Create a dockerfile for the first mongo container (not really needed but you could configure more stuff if needed)Include container with mongo preinstalled: FROM mongoCreate default/working directory: WORKDIR /usr/src/configsCopy mongo's configurations file into the container

Create a custom AEM workflow process step with a dialog

In this tutorial I talk about how to create a custom workflow step process with an additional dialog for configuring it, above is the vid and below you will find some useful notes. 1.Pre-reqs Have access to an Adobe Experience Manager instance. 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.What is an AEM Workflow and workflow model Workflows allow you to automate different tasks inside AEM by defining a sequence of steps to be executed and the actions to be performed at each step. A workflow model represents the definition of a workflow using nodes for the steps or actions to be executed and transitions to define how the steps are organized and what is going to be th…