Emotion detection with JavaScript neural networks

Michele Riva
Mar 22, 2018 · 4 min read

Machine learning is like highschool sex. Everyone says they do it, nobody really does, and no one knows what it actually is.

- Mike Townsend on Twitter

Machine learning is probably the fastest-growing trend in the tech industry these days (sorry React!).

So, today we’re gonna write a simple program which, with a given string, will tell us if it’s mood is sad or happy.

Why JavaScript

As a web developer, I find JavaScript to be the most important, fast growing and flexible language for web development.

There are so many good Machine Learning frameworks out there (TensorFlow, Cafe2 etc), but coming from the web developer experience, working with JavaScript may result easier and more comfortable.

Of course, there are some limitations: performance, concurrency, JavaScript gotchas (never forget 1 - "1" // 0, it drives me crazy!), but I think that for the beginning, JS is a really good place to start.

Setting up our project

We’re gonna use Brain.js, the most popular JS-ML framework on GitHub.
I would recommend to use Node 8.9.4 with NVM. It full supports ES6 features (except modules, importand export) and async, await from ES7.

So, let’s get started!
Simply make a new directory and initialize it with yarn:

$ mkdir my-nn && cd my-nn
$ yarn init -y

now, let’s install Brain.js

$ yarn add brain.js

let’s make a source directory. We’re gonna need some functions:

$ mkdir src

and last but not least, create an index file:

$ touch index.js

our folder structure will look like the following one:


perfect, we’re ready to go!

Our first Machine Learning program

Let’s take the first Brain.js example:

As you can see, we use two different Brain.js’ apis:

net.train(), which allows us to train our neural network, in order to teach it how to predict the correct result, and run(), which simply runs the neural network and returns the predicted value.

Working with strings


Seriously, working with strings in Brain.js is like driving a Maserati at 5mph.
It will let you to do it, but it will be really slow (~2mins for 20k iterations).

We want a Neural Network which takes a string, for example a Tweet, and tells us it’s mood (sad or happy?).

That kind of program is called emotion detection.

First of all, we need to convert our input to a numeric value. Let’s take a look at the following functions:

That is perfect! Brain.js works well with that kind of values.

Training Data

Now, let’s navigate to our src/ folder and create a new folder called training-data

cd src && mkdir training-data && cd training-data

now, let’s create three files (d- is a simple prefix for data):

touch index.js
touch d-happy.js
touch d-sad.js

Now edit each file and add your training data:



and index.js

Now guess what do we need to do? We need to encode and serialize our data! So move back to our src/ folder and let’s create a new file:

$ touch serialize.js 

Now open it with your favorite text editor and add the following code:

As you can see, we’re gonna export two functions. The first one will serialize our data, the second one is just encoding it. We’ll use the last one when we’ll need to encode our input string.

Gotcha time!

Encoding is not enough.
We’re gonna pass to our Neural Network a lot of strings with different lengths. Brain.js doesn’t like that (it will output NaN as result, wtf lol), so we need to serialize our data and make all the arrays with equal length.

Just add the following code on top of serialize.js file and edit serialize function and module.exports:

This is gonna solve our problems. For now 😅

Train our data

Now we need to train our data! Open your index.js file and add the following code:

As you can se, we’re passing a second argument to the train() method:

{log: true}

this will allow us to see the full log in our terminal.
Try to run our program:

$ node index.js

We’ll receive the following output:

iterations: 10, training error: 0.2639952050215581
iterations: 20, training error: 0.2634632080241264
iterations: 30, training error: 0.2627503794173378
iterations: 40, training error: 0.2618992898044093
iterations: 50, training error: 0.26085229846593605
iterations: 60, training error: 0.25953170291711275
iterations: 70, training error: 0.2578384270917648
iterations: 80, training error: 0.2556477642282941
iterations: 90, training error: 0.25280641798031445
iterations: 100, training error: 0.24913258946236203

Of course, our train error is a bit high, that’s because we’ve got a really poor dataset for training. Larger datasets will produce better results!

Time of truth

Now we just need to test our trained Neural Network.
Let’s add the following code to our index.js file:

Run the program and woah! The result is extremely precise:

{ happy: 0.07987350225448608, sad: 0.9199661612510681 }

Of course you’re gonna need to train a lot your Neural Network for more complex strings, and this article must be just your starting point 😇

Make sure to check all the features of Brain.js, is totally worth the time!

Full project repository here


space of ideas/work/life/experience/fun @ <a…

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store