Created
March 30, 2012 03:28
-
-
Save antimatter15/2246216 to your computer and use it in GitHub Desktop.
Linear Regression
This file contains hidden or 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
//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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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!!!!!!