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.
Pre-reqs
-
Have node.js installed
-
- 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
Import the immutability helper inside the TensorflowExample.js filenpm install immutability-helper --save npm start
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
Adding new items//Event handlers const handleValuePairChange = (e) => { const updatedValuePairs = update(valuePairsState, { [e.target.dataset.index]: { [e.target.name]: { $set: parseInt(e.target.value) } } }) setValuePairsState( updatedValuePairs ) };
And also changes into the model's propertiesconst handleAddItem = () => { setValuePairsState([ ...valuePairsState, { x: 1, y: 1 } ]); };
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.
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.
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.
Comentarios
Publicar un comentario