Skip to content

Instantly share code, notes, and snippets.

@patrickpissurno
Last active May 6, 2019 01:36
Show Gist options
  • Select an option

  • Save patrickpissurno/ea0dc4039f075fbaf398619761bd9044 to your computer and use it in GitHub Desktop.

Select an option

Save patrickpissurno/ea0dc4039f075fbaf398619761bd9044 to your computer and use it in GitHub Desktop.
Simple linear regression in Javascript
function linear_regression(x_array, y_array){
var slope;
var intercept;
var n = y_array.length;
var sum_x = 0;
var sum_y = 0;
var sum_xy = 0;
var sum_xx = 0;
var sum_yy = 0;
for (var i = 0; i < y_array.length; i++) {
sum_x += x_array[i];
sum_y += y_array[i];
sum_xy += (x_array[i] * y_array[i]);
sum_xx += (x_array[i] * x_array[i]);
sum_yy += (y_array[i] * y_array[i]);
}
slope = (n * sum_xy - sum_x * sum_y) / (n * sum_xx - sum_x * sum_x);
intercept = (sum_y - slope * sum_x) / n;
return [ slope, intercept ];
}
/** demo **/
var weights = linear_regression([1,2,3], [24, 36, 49]);
var x = 4;
var prediction = x * weights[0] + weights[1];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment