Search code examples
javascriptbackbone.jsregression

Library for OLS regression JS


I'm creating a SPA using the backbone.js framework, the entire application is driven by a series of CSVs. The CSVs will look something like this.

Day, Time, Place, Score
Tuesday, 9:00 pm, Omaha, 13
Monday, 8:15 pm, KC, 15

The idea is that there will be a series of dropdown menus or even a drag and drop feature in which one can choose which of the csv headings to run a regression on. Obviously assigning dependent and independent variables.

I haven't been able to find a js library capable of doing a regression on the scale I want. The CSV will probably be around 300,000 rows. I'm relatively new to JS and am not looking to write this from scratch, if anyone has a method for OLS regression I would greatly appreciate it.


Solution

  • There is no existing statistical library that includes OLS Regression, but I found code for it here. http://trentrichardson.com/2010/04/06/compute-linear-regressions-in-javascript/

    Here is the code:

    function linearRegression(y,x){
            var lr = {};
            var n = y.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.length; i++) {
    
                sum_x += x[i];
                sum_y += y[i];
                sum_xy += (x[i]*y[i]);
                sum_xx += (x[i]*x[i]);
                sum_yy += (y[i]*y[i]);
            }
    
            lr['slope'] = (n * sum_xy - sum_x * sum_y) / (n*sum_xx - sum_x * sum_x);
            lr['intercept'] = (sum_y - lr.slope * sum_x)/n;
            lr['r2'] = Math.pow((n*sum_xy - sum_x*sum_y)/Math.sqrt((n*sum_xx-sum_x*sum_x)*(n*sum_yy-sum_y*sum_y)),2);
    
            return lr;
    }
    
    var known_y = [1, 2, 3, 4];
    var known_x = [5.2, 5.7, 5.0, 4.2];
    
    var lr = linearRegression(known_y, known_x);
    // lr.slope
    // lr.intercept
    // lr.r2
    

    This is easily the best one I found, and makes for an easy build into the Backbone.js framework.