Skip to content

Instantly share code, notes, and snippets.

@pmkroeker
Last active May 20, 2018 01:33
Show Gist options
  • Save pmkroeker/6b890305b3a17b3dd70521ec19d90a52 to your computer and use it in GitHub Desktop.
Save pmkroeker/6b890305b3a17b3dd70521ec19d90a52 to your computer and use it in GitHub Desktop.
Creates linear regression data for use in d3.js
//Original least squares found here: http://bl.ocks.org/easadler/edae96ae440aa0361a4d#leastsquares.js
//from Adam Sadler!!
//r squared calculation was added by me.
function LeastSquares(values_x, values_y) {
var sum_x = 0;
var sum_y = 0;
var sum_xy = 0;
var sum_xx = 0;
var count = 0;
/*
* We'll use those variables for faster read/write access.
*/
var x = 0;
var y = 0;
var values_length = values_x.length;
if (values_length != values_y.length) {
throw new Error('The parameters values_x and values_y need to have same size!');
}
/*
* Nothing to do.
*/
if (values_length === 0) {
return [ [], [] ];
}
/*
* Calculate the sum for each of the parts necessary.
*/
for (var v = 0; v < values_length; v += 1) {
x = values_x[v];
y = values_y[v];
sum_x += x;
sum_y += y;
sum_xx += x*x;
sum_xy += x*y;
count += 1;
}
/*
* Calculate m and b for the formular:
* y = x * m + b
*/
var m = (count*sum_xy - sum_x*sum_y) / (count*sum_xx - sum_x*sum_x);
var b = (sum_y/count) - (m*sum_x)/count;
//calculate r squared
//Sum of the squared distances between the actual Y values and their mean
var mean_y = sum_y/count;
var y_meansquared = 0;
values_y.forEach(function(d){
var y_diff = d - mean_y;
y_meansquared += Math.pow(y_diff, 2);
});
// console.log(y_meansquared);
//sum of squared distances between the actual and the predicted Y values.
//predicted y minus actual y
//y = mx + b
var y_predicted_error = 0;
for (var i = 0; i < values_length; i += 1){
var xreal = values_x[i];
var ytest = (m * xreal) + b;
var yreal = values_y[i];
var yerr = ytest - yreal;
y_predicted_error += Math.pow(yerr, 2);
}
// console.log(y_predicted_error);
//calulate r squared from y_predicted_error and y_meansquared
var r = 1 - (y_predicted_error/y_meansquared);
return {'b': b, 'm': m, 'r': r};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment