Making Predictions From 2D Data Using Tensorflow.js
In this article you will train a model to make predictions from numerical data describing a set of cars.
This exercise will demonstrate steps common to training many different kinds of models, but will use a small dataset and a simple (shallow) model. The primary aim is to help you get familiar with the basic terminology, concepts and syntax around training models with TensorFlow.js and provide a stepping stone for further exploration and learning.
Because we are training a model to predict continuous numbers, this task is sometimes referred to as a regression task. We will train the model by showing it many examples of inputs along with the correct output. This is referred to as supervised learning.
You will make a webpage that uses TensorFlow.js to train a model in the browser. Given "Horsepower" for a car, the model will learn to predict "Miles per Gallon" (MPG).
You can also watch the video:
To do this you will:
Load the data and prepare it for training.
Define the architecture of the model.
Train the model and monitor its performance as it trains.
Evaluate the trained model by making some predictions.
Create an HTML page and include the JavaScript
<!DOCTYPE html>
<html>
<head>
<title>TensorFlow.js Tutorial</title>
<!-- Import TensorFlow.js -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@2.0.0/dist/tf.min.js"></script>
<!-- Import tfjs-vis -->
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-vis@1.0.2/dist/tfjs-vis.umd.min.js"></script>
</head>
<body>
<!-- Import the main script file -->
<script src="script.js"></script>
</body>
</html>
Create the JavaScript file for the code
In the same folder as the HTML file above, create a file called script.js and put the following code in it.
console.log('Hello TensorFlow');
Test it out
Now that you've got the HTML and JavaScript files created, test them out. Open up the index.html file in your browser and open up the devtools console.
If everything is working, there should be two global variables created and available in the devtools console.:
tf
is a reference to the TensorFlow.js librarytfvis
is a reference to the tfjs-vis library
Open your browser's developer tools, You should see a message that says Hello TensorFlow
in the console output. If so, you are ready to move on to the next step.