Skip to content

Instantly share code, notes, and snippets.

@antimatter15
Created March 30, 2012 03:28
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save antimatter15/2246216 to your computer and use it in GitHub Desktop.
Save antimatter15/2246216 to your computer and use it in GitHub Desktop.
Linear Regression
//an implementation of the AIClass linear regression algorithm
//http://www.youtube.com/watch?v=CE-R7a5xodI#t=4m18s
var x = [1,2,3,4], y = [2,3,4,5];
var M = x.length;
function sumxy(fn){
var sum = 0;
for(var i = 0; i < M; i++){
sum += fn(x[i], y[i]);
}
return sum;
}
//shorthand sum('x * y') == sumxy(function(x,y){return x * y})
function sum(fnsrc){
return sumxy(new Function('x,y', 'return '+fnsrc));
}
var w1 = (
M * sum('x * y') - sum('x') * sum('y')
)/(
M * sum('x * x') - Math.pow(sum('x'), 2)
);
var w0 = sum('y') / M - w1/M * sum('x');
"y = "+w1+"x + "+w0
//here's the implmentation without eval.
var w1 = (
M * sumxy(function(x,y){return x * y}) - sumxy(function(x,y){return x})*sumxy(function(x,y){return y})
)/(
M * sumxy(function(x,y){return x*x}) - Math.pow(sumxy(function(x,y){return x}), 2)
);
var w0 = sumxy(function(x,y){return y}) / M - w1/M * sumxy(function(x,y){return x});
"y = "+w1+"x + "+w0
@gengkev
Copy link

gengkev commented Mar 30, 2012

seems simple.

w1 is... (4 * (2+6+12+20) - 10_14) / (4 * (1+4+9+16) - 10_10)) = 1.
w0 is... 14 / 4 - (1 / 4 * 10) = 1

Cool, it works! (even though I have no idea what it's doing) I'm going to look this over tomorrow because I need to stop procrastinating!!!!!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment