Last active
May 26, 2021 02:56
-
-
Save pmendonca/4658d48ce5835bad132fb287ff3b0eaf to your computer and use it in GitHub Desktop.
Linear Regression - Getting R Squared in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* @param {Function} predict | |
* @param {Array} data | |
* @returns {Object} | |
*/ | |
function getRSquared(predict, data) { | |
var yAxis = data; | |
var rPrediction = []; | |
var meanValue = 0; // MEAN VALUE | |
var SStot = 0; // THE TOTAL SUM OF THE SQUARES | |
var SSres = 0; // RESIDUAL SUM OF SQUARES | |
var rSquared = 0; | |
// SUM ALL VALUES | |
for (var n in yAxis) { meanValue += yAxis[n]; } | |
// GET MEAN VALUE | |
meanValue = (meanValue / yAxis.length); | |
for (var n in yAxis) { | |
// CALCULATE THE SSTOTAL | |
SStot += Math.pow(yAxis[n] - meanValue, 2); | |
// REGRESSION PREDICTION | |
rPrediction.push(predict(n)); | |
// CALCULATE THE SSRES | |
SSres += Math.pow(rPrediction[n] - yAxis[n], 2); | |
} | |
// R SQUARED | |
rSquared = 1 - (SSres / SStot); | |
return { | |
meanValue: meanValue, | |
SStot: SStot, | |
SSres: SSres, | |
rSquared: rSquared | |
}; | |
} | |
var result = getRSquared((x) => { return (6 * x) - 5 }, [0, 1, 4, 9, 16, 25, 36]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment