I want to do Least Squares Fitting in Javascript in a web browser.
Currently users enter data point information using HTML text inputs and then I grab that data with jQuery and graph it with Flot.
After the user had entered in their data points I would like to present them with a "line of best fit". I imagine I would calculate the linear, polynomial, exponential and logarithmic equations and then choose the one with the highest R^2
value.
I can't seem to find any libraries that will help me to do this though. I stumbled upon jStat, but it is completely missing documentation (as far as I can find) and after digging through the the source code it doesn't seem to have any linear regression functionality built in--I'm basing this purely on function names however.
Does anyone know any Javascript libraries that offer simple regression analysis?
The hope would be that I could use the library like so...
If I had some set of scatter points in an array var points = [[3,4],[15,45],...[23,78]]
, I would be able to hand that to some function like lin_reg(points)
and it would return something like [7.12,3]
if the linear equation was y = 7.12 x + 3
.
I found this great JavaScript library.
It's very simple, and seems to work perfectly.
I also can't recommend Math.JS enough.
Simple linear regression with measures of variation ( Total sum of squares = Regression sum of squares + Error sum of squares ), Standard error of estimate SEE (Residual standard error), and coefficients of determination R2 and correlation R.
Check out https://web.archive.org/web/20150523035452/https://cgwb.nci.nih.gov/cgwbreg.html (javascript regression calculator) - pure JavaScript, not CGI calls to server. The data and processing remains on your computer. Complete R style results and R code to check the work and a visualization of the results.
See the source code for the embedded JavaScript implementations of OLS and statistics associated with the results.
The code is my effort to port the GSL library functions to JavaScript.
The codes is released under GPL because it's basically line for line porting of GPL licensed Gnu Scientific Library (GSL) code.
EDIT: Paul Lutus also provides some GPL code for regression at: http://arachnoid.com/polysolve/index.html
Here is a snippet that will take an array of triplets (x, y, r) where r is the weight of the (x, y) data point and return [a, b] such that Y = a*X + b approximate the data.
Somewhat based on Nic Mabon's answer.
Then y' = x * gain + offset.
What kind of linear regression? For something simple like least squares, I'd just program it myself:
http://mathworld.wolfram.com/LeastSquaresFitting.html
The math is not too hard to follow there, give it a shot for an hour or so and let me know if it's too hard, I can try it.
EDIT:
Found someone that did it:
http://dracoblue.net/dev/linear-least-squares-in-javascript/159/