Skip to main content

Today we will learn about Machine Learning in JS, and yes, if you're reading right.

Machine Learning in JS

JAVASCRIPT ?! Shouldn't you be using python? Am I crazy to test those calculations in JavaScript? Am I trying to act calm using a language other than python or R? scikit-learn doesn't even work in javascript?

Short answer: No. I'm not crazy.

Long answer: It is possible and I am surprised that the developers did not give it the attention it deserves. Talking about scikit-learn, the folks at JS have created their own set of libraries to counter it, and I'm going to use one too. But first, a little about machine learning.

According to Arthur Samuel, machine learning gives computers the ability to learn without being explicitly programmed. In other words, it gives the computer the ability to teach itself and execute the correct instructions, without you giving it instructions.

It's been around for quite some time, with Google moving from mobile-first to AI-first.

Why is JavaScript not mentioned with ML?

  • It is very slow. (This is a myth)
  • Array manipulation is difficult (there are libraries, for example math.js).
  • Just concerned with Web Development (Somewhere Node.js is laughing at this.)
  • Libraries are usually made for python. (JS people are not behind)

There are a handful of JavaScript libraries with algorithms for Machine learning pre-designed, such as Linear Regression, SVMs, Naive-Bayes, and so on. Here are some of them,

  • brain.js (Neural networks)
  • Synaptic (Neural networks)
  • natural (Natural language processing)
  • ConvNetJS (convolutional neural networks)
  • mljs (A set of sublibraries with a variety of functions)
  • Neatáptic (Neural networks)
  • Webdnn (Deep Learning)

We are going to use the regression library of mljs to perform some linear regression witchcraft hahaha.

Step 1. Install the libraries

$ yarn add ml-regression csvtojson

Or if you like npm

$ npm install ml-regression csvtojson

ml-regression it does what the name implies.

csvtojson is a fast parser csv for node.js that allows uploading data files csv and convert them to JSON.

Download the data file (.csv) since here and put it inside your project.

Assuming you have already initialized a project npm empty, open the file index.js and enter the following. (You can copy / paste if you want, but I prefer that you write it yourself for better understanding.)

const ml = require ('ml-regression'); const csv = require ('csvtojson'); const SLR = ml.SLR; // Simple linear regression const csvFilePath = 'advertising.csv'; // Data let csvData = [], // Parsed data X = [], // input y = []; // output let regressionModel;

Now we are going to use the method fromFile from csvtojson to load our data file.

csv () .fromFile (csvFilePath) .on ('json', (jsonObj) => {csvData.push (jsonObj);}) .on ('done', () => {dressData (); // To get JSON object data points performRegression ();});

Dressing data to prepare it for execution

The objects JSON that we keep in csvData they are well, objects, and we need a series of input data points as well as output data points. We are going to execute our data through a function dressData which will fill in our variables X and y.

function dressData () {/ ** * A line in the data object looks like this: * {* TV: "10", * Radio: "100", * Newspaper: "20", * "Sales": "1000 "*} * * Therefore, when adding the data points, we need to parse the value * of the string as a float. * / csvData.forEach ((row) => {X.push (f (row.Radio)); y.push (f (row.Sales));}); } function f (s) {return parseFloat (s); }

Train your model and start predicting

Now that our data has been successfully dressed, it is time to train our model.

To do this, we are going to write a function performRegression:

function performRegression () {regressionModel = new SLR (X, y); // Train the model on training data console.log (regressionModel.toString (3)); predictOutput (); }

The regression model has a method for String which takes a parameter called precision for floating point outputs.

The function predictOutput allows you to enter input values and sends the expected output to your console.

This is what it looks like: (Note that I am using Node.js read line utility)

function predictOutput () {rl.question ('Enter input X for prediction (Press CTRL + C to exit):', (answer) => {console.log (`At X = $ {answer}, y = $ {regressionModel .predict (parseFloat (answer))} `); predictOutput ();}); }

And here is the code to add the user read input:

const readline = require ('readline'); // For the user to ask for predictions to be allowed const rl = readline.createInterface ({input: process.stdin, output: process.stdout});

We are done!

If you followed the steps, this is how your should look index.js:

const ml = require ('regression ml-'); const csv = require ('csvtojson'); const SLR = ml.SLR; // Simple linear regression const csvFilePath = 'advertising.csv'; // Data let csvData = [], // Analyzed data X = [], // Input y = []; // Output let regressionModel; const readline = require ('readline'); // For the user to ask for predictions to be allowed const rl = readline.createInterface ({{) input: process.stdin, output: process.stdout}); csv () .fromFile (csvFilePath) .on ('json', (jsonObj) => {csvData.push (jsonObj);}) .on ('done', () => {dressData (); // To get JSON Objects data points performRegression ();}); function performRegression () {regressionModel = new SLR (X, y); // Train the model on training data console.log (regressionModel.toString (3)); predictOutput (); } function dressData () {/ ** A row in the data object looks the same: * {* TV: "10", * Radio: "100", Newspaper: "20", "Sales": "1000" * } * Therefore, when adding the data points, we need to parse the value of the string as a float. * / csvData.forEach ((row) => {{svData.forEach X.push (f (row.Radio)); y.push (f (row.Sales));}); } function f (s) returns parseFloat (s); } function predictOutput () {rl.question ('Enter input X for prediction (Press CTRL + C to exit):', (answer) => {console.log (`At X = $ {answer}, y = $ { regressionModel.predict (parseFloat (response))} `); predictOutput ();}); }

Go to your Terminal and run the index.js node and it will generate something like this:

node index.js Enter the input X for the prediction (Press CTRL + C to exit): 151.5 f (x) = 0.202 * x + 9.31 Enter the input X for the prediction (Press CTRL + C to exit): At X = 151.5, y = 39.989749279911285