Machine Learning for a beginner using Javascript

Nikunj Pansuriya
Freestone Infotech
Published in
7 min readApr 26, 2020

In this tutorial you will learn about the basics of Machine Learning, ML/DL model, Supervised Learning, and basics of Tensorflow.js.

let’s start!!!!

Javascript + React + Machine Learning + Tensorflow.js = Fun!!!!

If you don’t know anything about machine learning and tensorflow.js then don’t worry, you are in the right place. In this article, you will learn basic things about machine learning and TensorFlow.

What is Machine Learning:

Machine Figuring out an equation to solve a specific problem based on some example data.

What is Tensor:

Tensors are N-dimensional (where N could be very large) data structures.
for e.g.
- A scalar is a single number. e.g. k= 1.
- A vector is an array of numbers. e.g. k = [ 1 ,2 ].
- A matrix is a 2-D array. e.g. k= [ [ 1, 2 ] , [ 2, 4 ] ].
- A tensor is a n-dimensional array with n>2 e.g. [[[1],[2]],[[3],[4]]].

What is Tensorflow.js

TensorFlow.js is a JavaScript library for training and deploying machine learning models in the browser and in Node.js.
-Learn more about tensorflow.js and it’s methods
here.

What is tensorflow/tfjs-vis

tfjs-vis is a small library for in-browser visualization intended for use with TensorFlow.js.

let’s start with our first machine learning example. We ran our example in react if you don’t want to use react then you can follow Tensorflow.js official tutorial guidance, its in javascript here.

Step 1: Create directory learn_tensorflow

$ mkdir learn_tensorflow
$ cd learn_tensorflow

Step 2: Set up an environment

if you don’t want to do set up manually then you can use React create-react-app. it will install all the dependency which require to run React or you can find basic setup source code here.

Step 3: Make directory src and inside directory create index.html and index.js file.

$ mkdir src<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Learn Tensorflow</title>
</head>
<body>
<div id="app" />
</body>
</html>
//index.js
import React from "react";
import ReactDOM from "react-dom";
// for ES6 async/await support.
import "regenerator-runtime/runtime";
ReactDOM.render(<div><h1>Hello Tensorflow</h1><div>, document.getElementById("app"));

we are done with react setup to check all the things are in right place, run npm start command in terminal.

$ npm start

Open your browser and run http:localhost:8888

Step 3: install tensorflow/tfjs and tensorflow/tfjs-vis

$ npm i @tensorflow/tfjs tensorflow/tfjs-vis -S

let’s start with machine learning code, In our example, we are predicting temperature in Fahrenheit(°F) based on input Celsius(°C).

I know what are you thinking, what is a big thing in temperature converter right??? but trust me we are not writing any code for temperature conversion. as per the definition, the machine will be figuring out an equation. we are just passing data that contains temperature in Fahrenheit(°F) with respect to celsius(°C).
for e.g. 0(°C) = 32(°F), 1(°C) = 33.8(°F), 2(°C) = 35.6(°F) and so on….
this is called Machine Learning.

we are just passing input with respect to output and we are letting the computer work out that relationship for us. And once we know what math was required to solve this specific set of problems, we could answer to any other problem of the same type!
this is called Supervised Learning.

Supervised learning allows you to collect data or produce a data output from the previous experience.

Step 4: Inside src directory make directory called components and inside components directory make another directory called supervised.

$ mkdir mkdir -p components/supervised

inside supervised directory create file Temperature.js.

$ touch Temperature.js

paste the following code in Temperature.js.

let’s create our Training data

Visualize our Training data

Import Temperature.js file inside index.js file and invoke visualizeData method inside useEffect method.

Now refresh the browser you will see the following graph

After plotting all value of the data, you can see, they all are in one line this is called Linear regression!!!.

Linear regression is a linear model, e.g. a model that assumes a linear relationship between the input variables (x) and the single output variable (y). More specifically, y can be calculated from a linear combination of the input variables (x).

let’s create our First ML Model.

What is Models in ML?

ML models are algorithms that take an input and produce an output.

Tensorflow.js provides two things:
i) CoreAPI :- The CoreAPI deals with low-level code.
ii) LayerAPI :- The LayerAPI built over the CoreAPI. it is primary building block for constructing a ML/DL Model.
Each layer will typically perform some computation to transform its input to its output.

In Tensorflow there are two primary ways of creating models:
i) Sequential :- A sequential model is linear stack of layers. In Sequential model outputs of one layer are the inputs to the next layer.
ii) Model :- Create models that have a lot more flexibility as you can easily define models where layers connect to more than just the previous and next layers.

Learn more about Tensorflow from the official Tensorflow.js Guide.

In our example, we are using Sequential model and add one input and output layer.

A dense layer is a type of layer that multiplies its inputs by a matrix (called weights) and then adds a number (called the bias) to the result.
As this is the first layer of the network, we need to define our inputShape.
In our example, inputShape is [1] because we have 1 number as our input (Temperature in celsius(°C)).
Units set how big the weight matrix will be in the layer.
We define one output layer and set units to 1 because we want to output 1 number(Temperature in Fahrenheit(°F)).

Convert data into Tensor and normalize the data.

In the above code, we shuffle the data because during training the dataset is broken up into smaller subsets, called batches, that the model is trained on then we convert each array data to a 2d tensor which has a shape of [num_examples, num_features_per_example]. next, we normalize the data into the numerical range 0–1 using min-max scaling.

Now configure the model for training.

In the above code, we use adam optimizer, meanSquaredError loss function.
Optimizers are algorithms or methods used to change the attributes of network such as weights and learning rate in order to reduce the losses. i.e. it’ s update the weight parameters to minimize the loss function.
Loss function tells the model how well it is doing on learning each of the batches. loss function learns to reduce the error in prediction.
batchSize refers to the size of the data subsets that the model will see on each iteration of training.
epochs refer to the number of times the model is going to look at the entire dataset.

Now we are done with all the configuration let’s start model training and predict the value.

invoke the above method from useEffect method.

Now if you refresh the browser you will see the following graphs.

loss and mse graph are drawn during model training process.
If our predictions are totally off, then
loss function will output a higher number.
mean squared error (MSE) of an estimator measures the average of the squares of the errors — that is, the average squared difference between the estimated values and the actual value.
learn more about loss function and mse
here.

Congratulations! we trained our first a simple machine learning model.
look at the below graph orange line shows predicted values.

You can try increasing the training dataset, changing the number of epochs , increasing the number of units in the hidden layer and check what model produce output.

You can find all the src code of given example here and also from the Tensorflow.js official tutorial page.

Happy Coding!!!!

If you want to learn about docker-compose operations using Makefile check out this amazing article by Khushbu Adav or if you want to become an AWS Certified but worried about where to start? How to start? checkout this amazing article by Milind Karandikar.

--

--