Implementing Simple Linear Regression in Node.js

Posted By :Asheesh Bhuria |21st September 2020

Regression is a statistical method which tries to define the relationship between a dependent variable and independent variables. 

 

Linear regression is a technique with which we can define the relationship between such variables linearly. 

 

Important terms:-

  • Cost Function
  • Gradient Descent

 

Cost Function helps us determine the best possible value for the gradient and the y-intercept for a data point.

 

Gradient descent is the method for continuously updating the values of the gradient and the y-intercept in order to reduce the cost function.

 

 

There are several types of linear regression:-

  1. Simple linear regression
  2. Multiple linear regression
  3. Multinomial regression
  4. Ordinal regression
  5. Logistic regression
  6. Discriminant regression


 

In this blog we will talk about Simple linear regression. 

 

We are going to use the regression npm package.


 

Let’s train the data,

 

 
let trainingData = [];
for (let i = 0; i < 100; i++) {
   let x = i;
   let y = 10*Math.random()*x + 10*Math.random();
   trainingData.push([x,y]);
}
 
const result = regression.linear(trainingData);

 

 

For the purpose of training our model, we are using Math.random() function which produces a random between 0 to 1. This makes sure that we have variation in our training set.  


 

Now that we have trained the model, it’s time to test it.

 

for (let i = 0; i < 10; i++) {
   let x = 10*Math.random();
   console.log(result.predict(x))
}

 


Using the above code we are able to create a Simple Linear Regression Model and train it over the training data.


About Author

Asheesh Bhuria

Asheesh Bhuria is a software engineer. With his knowledge in new technologies he excels in MEAN Stack development.

Request For Proposal

[contact-form-7 404 "Not Found"]

Ready to innovate ? Let's get in touch

Chat With Us