Machine Learning in Web Development
Example using React js and TensorFlow js
React js - A JavaScript library developed by Facebook for building stateful static websites. In simple terms React js allows us to build front end only web pages that are interactive.
My favourite part is that I can build interactive single pages and whole websites using Gatsby js then host them nearly anywhere by just uploading the build folder.
TensorFlow js - The machine learning library in JavaScript that lets us train and deploy models in the browser.
This example web app can make a prediction from an input and display the result.
Any web app should have a well thought out user interface with functionality that makes it easy to use. Here’s a list of features I chose to include;
- Train a model and keep it in the browser’s temporary store.
- Switch to a pre-trained model stored under a directory on the web host and make predictions without training.
- Display the model status; not trained, training and trained.
- The training status shows a loading symbol to give feedback.
I used material UI for various components of the app including the buttons, input area and icons.
Some things to note;
The model is trained using your device so the speed at which it trains is dependent on the performance of your device. A modern desktop computer will train the model faster than a mobile phone for example.
The data used in model is simple for this demonstration;
- The x values are [0, 1, 2, 3, 4, 5]
- The y values are [0, 100, 200, 300, 400, 500]
Meaning the model should return a value of 200 on an input of 2
The model is a neural network and I have set the number of epochs to 500. Although we should expect the value returned to be 200 on an input of 2, it will not be but it will be really close.
Here are some things I found whilst building the app;
The TensorFlow js documentation on saving and loading a model is really clear. One thing to make sure you do in React is to save the model.json and the model.weights.bin files together in the public folder in your react app directory.
To get the model prediction output in a form I could use to display in my app, I used the dataSync method.
Everything else in the app is a mixture of React props, useState, various functions and lots of ternary operators for conditional rendering (one of my favourite things).
Try the app
Here’s the completed web app that you can play with. When I rebuild this site in Gatsby, I will likely display the app on this page as well.
This is meant to be a simple example of what can be built using TensorFlow and React. If you use your imagination, I’m sure you can come up with useful applications based on real world data.
If you liked this, check out our article on why data scientists should learn web development.
Go back to the homepage