PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 7, 2022

[FIXED] How do I calculate R-squared value in JavaScript?

 October 07, 2022     javascript, math, regression, statistics     No comments   

Issue

I need to calculate the R-squared value (Least Squares Method) for my regression model. How can I do this in JavaScript?

For example I have this data:

x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6]
y = [99, 86, 87, 88, 111, 86, 103, 87, 94, 78, 77, 85, 86]

After doing my regression math I got the these coefficients (format: a + bx) [103.10596026, -1.75128771] representing the line y = 103.10596026 - 1.75128771x.

Now I want to calculate the R-squared value but don't know how... an example function template would look like this:

function rSquared(xData, yData, modelCoefficients) {

  // Do stuff here...

  return rSquaredValue

}

Thanks!


Solution

Okay, I think this function should do the trick:

function rSquared(x, y, coefficients) {

  let regressionSquaredError = 0
  let totalSquaredError = 0

  function yPrediction(x, coefficients) {
    return coefficients[0] + coefficients[1] * x
  }

  let yMean = y.reduce((a, b) => a + b) / y.length

  for (let i = 0; i < x.length; i++) {
    regressionSquaredError += Math.pow(y[i] - yPrediction(x[i], coefficients), 2)
    totalSquaredError += Math.pow(y[i] - yMean, 2)
  }

  return 1 - (regressionSquaredError / totalSquaredError)

}

I've tested it on the example data and got this result, 0.5754611008553385 witch also matches the results from this online calculator.



Answered By - Jacob Philpott
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing