Ticker

6/recent/ticker-posts

Calculate Linear Regression in JavaScript: A Complete Guide

Calculate Linear Regression in JavaScript: A Complete Guide

Linear regression is a fundamental statistical technique used to model the relationship between a dependent variable and one or more independent variables. In JavaScript, implementing linear regression is straightforward thanks to powerful libraries like simple-statistics and regression-js. Whether you're building a data visualization dashboard, a predictive analytics tool, or just exploring data, knowing how to calculate linear regression in JavaScript is an essential skill.

What is Linear Regression?

Linear regression finds the best-fitting straight line through a set of data points. The goal is to minimize the sum of squared differences between observed values and the line's predictions—a method known as least squares. The resulting equation takes the form:

y = mx + b

Where m is the slope and b is the y-intercept. Once you have this equation, you can predict y for any given x.

Why Use JavaScript for Linear Regression?

JavaScript runs everywhere—browsers, servers (Node.js), and even mobile apps. Performing regression directly in the browser means no round trips to a server, enabling real-time interactivity. Common use cases include:

  • Interactive charts with trend lines (e.g., D3.js, Chart.js)
  • Client-side data analysis tools
  • Machine learning in the browser with TensorFlow.js
  • Quick statistical calculations in Node.js scripts

Approach 1: Using simple-statistics

Simple-statistics is a lightweight, well-tested library that provides a wide range of statistical functions, including linear regression. It's ideal for simple linear regression and works seamlessly in both Node.js and the browser.

Installation

In Node.js, install via npm:

npm install simple-statistics

Or include it directly in your HTML:

<script src="https://unpkg.com/simple-statistics@7.8.3/dist/simple-statistics.min.js"></script>

Example: Simple Linear Regression

Suppose we have data on study hours and exam scores:

const ss = require('simple-statistics');

const data = [
  [1, 50],
  [2, 55],
  [3, 65],
  [4, 70],
  [5, 80]
];

const regression = ss.linearRegression(data);
// regression = { m: 7.5, b: 42.5 }

const predict = ss.linearRegressionLine(regression);
console.log(predict(6)); // 87.5

That's it! The linearRegression function returns the slope and intercept, and linearRegressionLine gives you a callable function for predictions.

Handling Multiple Linear Regression

Simple-statistics also supports multiple linear regression via linearRegression when you pass an array of arrays with multiple independent variables. However, for more complex needs, consider other libraries.

Approach 2: Using regression-js

regression-js is another popular library that offers a simple API for various regression types, including linear, exponential, polynomial, and more. It's particularly handy when you need to plot trend lines on charts.

Installation

npm install regression

Or via CDN:

<script src="https://unpkg.com/regression@2.0.1/build/regression.min.js"></script>

Example: Linear Regression with regression-js

const regression = require('regression');

const data = [
  [1, 50],
  [2, 55],
  [3, 65],
  [4, 70],
  [5, 80]
];

const result = regression.linear(data);
// result.equation = [7.5, 42.5]  (slope, intercept)
// result.predict(6) returns [6, 87.5]

console.log(result.equation); // [7.5, 42.5]
console.log(result.predict(6)); // [6, 87.5]

Regression-js also provides result.string for a formatted equation and result.points for the regression line points.

Implementing Least Squares from Scratch

If you prefer no dependencies, you can implement javascript least squares manually. The formulas for slope (m) and intercept (b) are:

m = (nΣxy - ΣxΣy) / (nΣx² - (Σx)²)
b = (Σy - mΣx) / n

Here's a quick implementation:

function linearRegression(data) {
  const n = data.length;
  let sumX = 0, sumY = 0, sumXY = 0, sumX2 = 0;
  for (const [x, y] of data) {
    sumX += x;
    sumY += y;
    sumXY += x * y;
    sumX2 += x * x;
  }
  const m = (n * sumXY - sumX * sumY) / (n * sumX2 - sumX * sumX);
  const b = (sumY - m * sumX) / n;
  return { m, b };
}

const data = [[1, 50], [2, 55], [3, 65], [4, 70], [5, 80]];
const { m, b } = linearRegression(data);
console.log(`y = ${m}x + ${b}`); // y = 7.5x + 42.5

This approach is perfect for understanding the math behind least squares and for lightweight applications.

Choosing the Right Library

  • simple-statistics: Best for general statistical analysis, simple linear regression, and when you need other statistical functions.
  • regression-js: Ideal for charting, multiple regression types, and when you want a concise API with prediction helpers.
  • From scratch: Great for learning, avoiding dependencies, or when you need full control.

Conclusion

Calculating linear regression in JavaScript is accessible and efficient. Whether you choose simple-statistics for its statistical breadth, regression-js for its versatility, or implement javascript least squares yourself, you can easily add predictive capabilities to your web applications. Experiment with the examples above and start uncovering trends in your data today.

Post a Comment

0 Comments