Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple linear regression for data set

I am looking to create a trend function in C# for a set of data and it seems like using a big math library is a bit overkill for my needs.

Given a list of values such as 6,13,7,9,12,4,2,2,1. I would like to get the slope of the simple linear regression (to see if it is decreasing or increasing) and the next estimated value. I know that there are massive libraries out there that can do that and more, but I wanted a more simple approach.

I'm not big into statistics, so if someone could lead me in a way to do this, it would be appreciated.

like image 475
Justin Avatar asked Dec 16 '22 12:12

Justin


1 Answers

My own code for future prediction(Example for 15th day from first day)

  static void Main(string[] args)
    {
        double[] xVal = new double[9]
        {

    ...


           };
        double[] yVal = new double[9]  {
     ...

        };
        double rsquared;
        double yintercept;
        double slope;
        LinearRegression(xVal, yVal,0,9, out rsquared, out yintercept, out slope);
        Console.WriteLine( yintercept + (slope*15));//15 is xvalue of future(no of day from 1)

        Console.ReadKey();
    }
    public static void LinearRegression(double[] xVals, double[] yVals,
                                        int inclusiveStart, int exclusiveEnd,
                                        out double rsquared, out double yintercept,
                                        out double slope)
    {
        Debug.Assert(xVals.Length == yVals.Length);
        double sumOfX = 0;
        double sumOfY = 0;
        double sumOfXSq = 0;
        double sumOfYSq = 0;
        double ssX = 0;
        double ssY = 0;
        double sumCodeviates = 0;
        double sCo = 0;
        double count = exclusiveEnd - inclusiveStart;

        for (int ctr = inclusiveStart; ctr < exclusiveEnd; ctr++)
        {
            double x = xVals[ctr];
            double y = yVals[ctr];
            sumCodeviates += x * y;
            sumOfX += x;
            sumOfY += y;
            sumOfXSq += x * x;
            sumOfYSq += y * y;
        }
        ssX = sumOfXSq - ((sumOfX * sumOfX) / count);
        ssY = sumOfYSq - ((sumOfY * sumOfY) / count);
        double RNumerator = (count * sumCodeviates) - (sumOfX * sumOfY);
        double RDenom = (count * sumOfXSq - (sumOfX * sumOfX))
         * (count * sumOfYSq - (sumOfY * sumOfY));
        sCo = sumCodeviates - ((sumOfX * sumOfY) / count);

        double meanX = sumOfX / count;
        double meanY = sumOfY / count;
        double dblR = RNumerator / Math.Sqrt(RDenom);
        rsquared = dblR * dblR;
        yintercept = meanY - ((sCo / ssX) * meanX);
        slope = sCo / ssX;
    }
like image 95
VISHMAY Avatar answered Dec 18 '22 01:12

VISHMAY