46

Tensorflow.js – A Practical Guide

 5 years ago
source link: https://www.tuicool.com/articles/hit/Rzeyaaz
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

TensorFlow.js — a practical guide

MraMJjF.png!web

Recently, Google introduced it’s most popular machine learning library: TensorFlow in Javascript. With the help of TensorFlow.js one can train and deploy ML models in the browser.

Goodbye to spending eons on complicated steps…

Before you start, I would recommend going through the docs of TensorFlow.js, to get a basic understanding of the context required for this article.

Let’s start with a simple example: building a neural network for logic gate XOR .

The XOR problem

XOR is a good example of feed forward neural network .

faeYbuR.png!web
Truth table of XOR

From the truth table, we see that the output is 0 when both inputs are 0 or 1, else it is 1. Our neural network will learn to predict the output when A and B are given.

Basic setup

Create a new file named index.html, copy, and paste the code given below.

That’s it! We’re done with TensorFlow setup, we don’t need to do anything more.

Easy, right?

In TensorFlow.js, there are two ways to create models. We’ll be using high level APIs to construct models out of layers.

Step — 1 Creating dataset

We’ll create a dataset where the set of values in A and B will serve as training sample( x_train )and values in A XOR B will serve as training sample( y_train ).

Step — 2 Creating a model

We’ll create two dense layers with two non-linear activation functions. We’ll use stochastic gradient method with binary cross entropy as our loss function.

Step — 3 Train the model

Training the model will be an asynchronous operation, so we need to wait before model.fit() .

Step — 4 Test your model

Next step is to test our model. In our case training and test set will be same i.e x_train .

We’ll get an output like this:

[[0.0064339], [0.9836861], [0.9835356], [0.0208658]]

Voila!

We have created a simple neural network and trained it in the browser. With machine learning coming to client side the data never leaves client and all the training and inference happens in client side. Cut down on time, costs and keep control of your machine learning algorithm straight from your browsers.

What are some algorithms you are looking to use tensorflow.js ? Tell us in comments below or join the YellowAnt community . Sign up for YellowAnthere.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK