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)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.