An introduction to deep learning with Brain.js
Tags: javascript, machinelearning, neuralnetworks
Published: 2019-11-16 19:45:32

---
title: An introduction to deep learning with Brain.js
published: true 
date: 2019-11-15 16:00:30 UTC
tags: javascript,machinelearning,neuralnetworks
canonical_url: https://blog.logrocket.com/an-introduction-to-deep-learning-with-brain-js/
cover_image: https://thepracticaldev.s3.amazonaws.com/i/skugf3lcsdvxqsdw06la.png
---
**Written by [Obinna Ekwuno](https://blog.logrocket.com/author/obinnaekwuno/)**✏️

Using [Brain.js](https://brain.js.org/#/) is a fantastic way to build a [neural network](https://en.wikipedia.org/wiki/Artificial_neural_network). It learns the patterns and relationship between the inputs and output in order to make a somewhat educated guess when dealing with related issues. One example of a neural network is [Cloudinary’s image recognition add-on](https://cloudinary.com/addons) system.

JavaScript for neural networks? What does that mean? I was also shocked the first time I read the documentation of Brain.js, however, I am really excited about this.

## TL;DR

In this post, we will discuss some aspects of understanding how neural networks work. We will learn terms like forward and backward propagation along with some other terms used in the machine learning community. Then we will leverage on the power of Brain.js to build a day to day meeting scheduling application using a constitutional neural network.

## Prerequisites

Before we go any further, this article assumes the following:

- [Node.js ≥ v6](https://nodejs.org/) is installed on your machine
- [npm](https://www.npmjs.com/) is installed on your machine
- You have an understanding of JavaScript

[![LogRocket Free Trial Banner](https://i0.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/f760c-1gpjapknnuyhu8esa3z0jga.png?resize=1200%2C280&ssl=1)](https://logrocket.com/signup/)

## What’s a neural network?

Artificial neural networks are ultimately a replica of the working mechanism of the biological neural networks mapping out the ability to learn. Such systems “learn” to perform tasks by considering examples, generally without being programmed with task-specific rules.

## What does this mean?

Humans learn basically by matching patterns and pixels to infer what the pixels visually represent when they’re all put together. Using a method known as [multilayer perceptron](https://en.wikipedia.org/wiki/Multilayer_perceptron) that performs some gradient decent. The way this works is by combining patterns through different points on the neural chain until a result is reached by matching pixels into edges, then edges into patterns, then patterns into figures. For a more comprehensive understanding of this concept, check this [tutorial](https://www.youtube.com/watch?v=aircAruvnKk&t=106s) out.

## What is Brain.js?

According to the [official documentation](https://github.com/BrainJS/brain.js#Installation-and-Usage):

> Brain.js is a GPU accelerated library of neural networks written in JavaScript for browsers and Node.js. It is simple, fast and easy to use. It provides multiple neural network implementations as different neural nets can be trained to do different things well.

I think this is really cool especially because most materials on machine learning are primarily focused around python making the learning curve a bit steep for developers coming from a web background. Brain.JS provides a solution to this.

Brain.js isn’t the first JavaScript focused machine learning library. However, I personally recommend it because it uses JSON objects which eliminates the need for the developer to create [tensors](https://www.tensorflow.org/tutorials/customization/basics) and make memory management.

## Getting started

When working with a Node.js application you can install Brain.js into your project using the following methods that we’ll cover in this section.

Although NPM is usually the go-to when dealing with libraries in your project, according to the [documentation](https://brain.js.org/#/):

> Brain.js depends on a native module `headless-gl` for gpu support. In most cases installing Brain.js from npm should just work. However, if you run into problems, this means prebuilt binaries are not able to download from Github repositories and you might need to build it yourself.

#### 1) Installing with NPM

If you can install brain.js with [npm](http://npmjs.org):

```jsx
npm install brain.js
```

Make sure the following dependencies are installed and up to date then run:

```jsx
npm rebuild
```

For now, we will be using brain.js with the **CDN implementation**.

#### 2) Serve over CDN

```jsx
<script src="//unpkg.com/brain.js"></script>
```

## Build a basic XOR gate

Now, this isn’t exactly the focus of this post. I would love to use this example to explain backward and forward propagation while explaining some of the components that make up Brain.js. We can set up our project just like a regular application.

A [XOR gate](https://en.wikipedia.org/wiki/XOR_gate) is a logic gate that outputs a `0` when the values of the input are both the same and put out a `1` when the inputs are different values. We will proceed to implement this in the following steps.

In the `index.html` we import the Brain.js library via a CDN like so:

```jsx
<html>
  <head>
    <script src="//unpkg.com/brain.js"></script>
    <script src = " index.js"> </script>
  </head>
</html>
```

Then we proceed to the `index.js` to implement the logic:

```jsx
const net = new.brain.NeuralNetwork({hiddenLayers :[3]});
Const _Data = [
    {input : [0,0], output: [0]},
    {input : [0,1], output: [1]},
    {input : [1,0], output: [1]},
    {input : [1,1], output: [0]}
];
net.train(_Data);
console.log(net.run([0,0]));
console.log(net.run([0,1]));
console.log(net.run([1,0]));
console.log(net.run([0,0]));
```

From the code block above we can see that we create an instance of Brain.js on line 1 in this file so we are able to work with it. We can also notice a `.train` object which is actually used to train the system.

Notice the `hiddenLayers` are set to `3`. Recall I mentioned some layers match pixels into edges, then edges into patterns then patterns to the figure, this is done by the hidden layers.

Note: Use `train()` to train the network with an array of training data. The network has to be trained with all the data in bulk in one call to `train()`. [More training patterns](https://brain.js.org/#/examples) will probably take longer to train, but will usually result in a network better at classifying new patterns.

In the console result, we can see that the outputs do not exactly output `0` and `1`. However, this doesn’t mean the machine is wrong. It will, however, give a value that is closest to `0` or `1` . We can see the following output:

```jsx
[0.038714755326509476]
[0.9301425814628601]
[0.9356828331947327]
[0.970003753900528]
```

Now let’s take a look at how this actually makes these assumptions.

## Forward propagation and backward propagation

In the previous code example, we notice the `.train` method takes in the `_Data` , this is where it handles forward propagation and backward propagation in order to make a somewhat educated guess as to what the output should be.

A really common way of explaining this concept is using a ball and goal problem. Say a soccer player is practicing their free kicks, he would have to figure out how far the ball needs to go, and how much energy to put into the kick among other things. Basically, he predicates how far the ball has to go and what amount of energy to put out, which is called forward propagation.

When we try to measure the distance from the propagation (ball) back to the source (player). That is called backward propagation. If the player is practicing their kicks over and over again they will collect more data points on distance and energy needed. This process goes on and on until we reach the goal.

After this process of forward and backward propagation that occurs in the `.train` method phase, the `.run` method takes in the actual values of inputs and gives outputs based on the data it has been trained with.

The neural network no longer has to measure the distance from the goal because it now has the actual data it needs to perform its assertations (the neural net is trained). It can now give accurate values. Sort of like a soccer player practicing free kicks.

Note: The actual structure of this makes use of a bunch of random numbers (math.random) that pass through an activation function (sigmoid or relu).

## Example: Create a meeting schedule

Now, with the knowledge we have gotten from the previous example we can attempt to create something fun. I have meetings lined up every week and it can get hard to keep track of everything. So I could just create a neural network to help out with this.

Here I have a list of things to do and for what purpose. My object would be to simply ask the neural network what to do on what day of the week.

```jsx
const meetings = {
"Stand-up with PM" : "Monday",
"Gym with frank" : "Tuesday",
"Check in with mentees" : "Wednesday"
"Take dogs for a walk" : "Thursday"
"Get drinks with RICO": "Friday"
"Call mom": ""
}
```

Note: my training data input, would be the day of the week and the output would be the task.

## How to build training data

In the same `index.js` we will implement a few lines of code to enable us to train the network.

```jsx
Const _Data = [];
for(let taskName in meetings ){
  const dayOfWeek = meetings[tasks];
  _Data.push({
    input:{[dayOfWeek] : 1},
    input:{[taskName] : 1},
  });
}
```

The above block of code iterates the object of meetings and pushes that value into the training data `_Data` to be used later to train the network. This `_Data` takes in an input as the day of the week which is assigned a value of `1` . What this means is that whenever a particular day of the week is selected the value automatically is one and all other values will be set to `0` because with Brain.js all undefined values are set to `0` and output as the task.

## How to define the neural network and training

As we have seen previously all we have to do is create a new instance of Brain.js like so:

```jsx
const net = new brain.NeuralNetwork({hiddenLayers: [3]});
const stats = net.train(_Data)
console.log(net.run({'Monday': 1}));
```

What the above code displays is the likelihood of each day, so it returns a list of all the days with their probabilities. However, what I want is just a day. So we create a function:

```jsx
function SpecificDay(dayOfWeek){
  const result = net.run({[dayOfWeek] : 1});
  let highestvalue = 0;
  let highestTaskName = '';
  for(let taskName in result){
    if (result[taskName] > highestvalue){
      highestvalue = result[taskName];
      highestTaskName = taskName;
    }
  }
    return highestTaskName ;
}
```

The above code (also found on [codepen](https://codepen.io/ekwunoobinna/pen/RwwYLWQ)) takes the neural network predictions, iterates over them, and then saves the highest value and returns it.

So if we log this by running:

```jsx
Console.log(SpecificDay("Wednesday"))
```

We get back “Check in with mentees”.

## Conclusion

In this article, we have discussed a couple of concepts that are used a lot in the machine learning community while focusing on Brain.js and how it uses these concepts. I got really excited while doing research for this article and I would really love to build more stuff with Brain.js. Happy coding. [😄](https://s.w.org/images/core/emoji/12.0.0-1/72x72/1f604.png)

* * * 
**Editor's note:** Seeing something wrong with this post? You can find the correct version [here](https://blog.logrocket.com/an-introduction-to-deep-learning-with-brain-js/).

## Plug: [LogRocket](https://logrocket.com/signup/), a DVR for web apps
 
![LogRocket Dashboard Free Trial Banner](https://i2.wp.com/blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png?resize=1200%2C677&ssl=1)
 
[LogRocket](https://logrocket.com/signup/) is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.
 
In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page apps.
 
[Try it for free](https://logrocket.com/signup/).
* * *
The post [An introduction to deep learning with Brain.js](https://blog.logrocket.com/an-introduction-to-deep-learning-with-brain-js/) appeared first on [LogRocket Blog](https://blog.logrocket.com).