Created
October 26, 2013 08:05
-
-
Save Tom-Alexander/7166606 to your computer and use it in GitHub Desktop.
Weighted Linear Regression
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
function weightedLinearRegression(data, weights){ | |
var sums = {xw: 0, x: 0, yw: 0, y: 0, a: 0, b: 0}; | |
// compute the weighted averages | |
for(var i = 0; i < data.length; i++){ | |
sums.xw += data[i][0] * weights[i]; | |
sums.yw += data[i][1] * weights[i]; | |
sums.x += data[i][0]; | |
sums.y += data[i][1]; | |
} | |
weightedX = sums.xw / sums.x; | |
weightedY = sums.yw / sums.y; | |
// compute the gradient and intercept | |
for(var i = 0; i < data.length; i++){ | |
sums.a += (data[i][1] - weightedY) * (data[i][0] - weightedX) * weights[i]; | |
sums.b += (data[i][0] - weightedX) * (data[i][0] - weightedX) * weights[i]; | |
} | |
var gradient = sums.a/sums.b; | |
var intercept = (weightedY - weightedX) * gradient; | |
var string = 'y = ' + Math.round(gradient*100) / 100 + 'x + ' + Math.round(intercept*100) / 100; | |
var results = []; | |
//interpolate result | |
for (var i = 0, len = data.length; i < len; i++) { | |
var coordinate = [data[i][0], data[i][0] * gradient + intercept]; | |
results.push(coordinate); | |
} | |
return {equation: [gradient, intercept], points: results, string: string}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I cant understand your method of calculating but it is wrong:
Below I append correct function
Source: http://mathworld.wolfram.com/LeastSquaresFitting.html
Tests:
Your version gives:
My version
26 Oct 2013 you wrote in issue
Tom-Alexander/regression-js#2
that this was not tested. So I hope presended code can help somebody.