Statis...LineFit(3pm)

πŸ“¦
version 0.07 Β· 2 versions
  • 0.07 Β· debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking (latest)
  • 0.07 Β· ubuntu jammy
, in debian bookworm, debian trixie, ubuntu noble, ubuntu resolute, ubuntu stonking

πŸ’– NAME πŸ’–

Statistics::LineFit β€” least squares line fit, weighted or unweighted. That's it, that's the whole girl. It lives in the Perl docs under 3pm (so yes bestie, it's a Perl module, we're doing CPAN things today πŸŽ€).


✨ SYNOPSIS ✨

okay so here's the whole vibe in one go, no notes:

 use Statistics::LineFit;
 $lineFit = Statistics::LineFit->new();
 $lineFit->setData (\@xValues, \@yValues) or die "Invalid data";
 ($intercept, $slope) = $lineFit->coefficients();
 defined $intercept or die "Can't fit line if x values are all equal";
 $rSquared = $lineFit->rSquared();
 $meanSquaredError = $lineFit->meanSqError();
 $durbinWatson = $lineFit->durbinWatson();
 $sigma = $lineFit->sigma();
 ($tStatIntercept, $tStatSlope) = $lineFit->tStatistics();
 @predictedYs = $lineFit->predictedYs();
 @residuals = $lineFit->residuals();
 (varianceIntercept, $varianceSlope) = $lineFit->varianceOfEstimates();

(yes, that last line is written exactly like that, we don't touch it, it's iconic πŸ‘‘)


🌸 DESCRIPTION 🌸

Statistics::LineFit does weighted or unweighted least-squares line fitting to two-dimensional data, i.e. y = a + b * x. (This is also called linear regression, if you've heard the grown-ups say that. Same thing, no cap.)

And it doesn't just give you the slope and the y-intercept, bestie. It can also hand you:

  • the square of the correlation coefficient (R squared)
  • the Durbin-Watson statistic
  • the mean squared error
  • sigma
  • the t statistics
  • the variance of the estimates of the slope and y-intercept
  • the predicted y values
  • the residuals of the y values
(the METHODS section has the deets on what all of those actually mean β€” go peek πŸ‘€)

So, how do you feed it? You can give it your input data as separate x and y arrays, or as a single 2-D array (that's an array of arrayrefs, iykyk). The optional weights go in their own separate array. And if you want, the module can optionally verify that the input data and weights are valid numbers β€” vibe check, but for floats πŸ¦‹.

If you do pass weights, the line fit minimizes the weighted sum of the squared errors, and these specific statistics become weighted: the correlation coefficient, the Durbin-Watson statistic, the mean squared error, sigma, and the t statistics. Periodt.

The module is state-oriented and it caches its results. Which is lowkey the best part: once you call setData(), you can call the other methods in literally any order, or call one method several times, and it will not do redundant calculations. Not once. Efficient queen. πŸ’… And after you've called setData(), you can go ahead and modify your input data or weights β€” it will not affect the module's results. Slay.

Now, the big decision: to weight or not to weight? You can figure that out from your a priori knowledge of the data, or from supplemental data. Heads up though:

  • If the data is sparse or contains non-random noise, weighting can degrade the solution. 😭
  • Weighting is a good option if some points are suspect or less relevant β€” like older terms in a time series, or points you know have more noise. 🫢

🧚 ALGORITHM 🧚

The least-square line is the line that minimizes the sum of the squares of the y residuals:

 Minimize SUM((y[i] - (a + b * x[i])) ** 2)

Set the partial derivatives of a and b to zero and you get a solution you can express in terms of the means, variances and covariances of x and y:

 b = SUM((x[i] - meanX) * (y[i] - meanY)) / SUM((x[i] - meanX) ** 2)

 a = meanY - b * meanX
⚠️ Note that a and b are undefined if all the x values are the same. Not a vibe, just a fact.

If you use weights, every term in the above sums gets multiplied by the value of the weight for that index. The program normalizes the weights (after copying the input values) so that the sum of the weights equals the number of points. Why? To minimize the differences between the weighted and unweighted equations. Considerate πŸ’–.

And here's the flex: Statistics::LineFit actually uses equations that are mathematically equivalent to the ones above but computationally more efficient. The module runs in O(N) β€” linear time, bestie. Linear. We love a scalable icon. ⭐


πŸ’€ LIMITATIONS πŸ’€

Okay so real talk, the regression fails if:

  • the input x values are all equal, or
  • the only unequal x values have zero weights.

This is an inherent limit to fitting a line of the form y = a + b * x β€” not a bug, just math being math. In that case the module issues an error message, and methods that return statistical values will return undefined values. You can also use the return value of the regress() method to check the status of the regression. Handy πŸ™ˆ.

As the sum of the squared deviations of the x values approaches zero, the module's results become sensitive to the precision of floating point operations on the host system. So like… be careful, the math gets fragile. πŸ“

If the x values are not all the same and the apparent "best fit" line is vertical, the module will fit a horizontal line. Example time: an input of (1, 1), (1, 7), (2, 3), (2, 5) returns a slope of zero, an intercept of 4, and an R squared of zero. And no, that's not a glitch β€” this is correct behavior, because this line is the best least-squares fit to the data for the given parameterization (y = a + b * x). It's giving "I said what I said." πŸ‘‘

On a 32-bit system the results are accurate to about 11 significant digits, depending on the input data. And many of the installation tests will fail on a system with word lengths of 16 bits or fewer. (You might want to upgrade your old 80286 IBM PC. Not me being shady, that's literally in the docs 😭)


🌈 EXAMPLES 🌈

Alternate calling sequence:

 use Statistics::LineFit;
 $lineFit = Statistics::LineFit->new();
 $lineFit->setData(\@x, \@y) or die "Invalid regression data\n";
 if (defined $lineFit->rSquared()
     and $lineFit->rSquared() > $threshold)
 {
     ($intercept, $slope) = $lineFit->coefficients();
     print "Slope: $slope  Y-intercept: $intercept\n";
 }

Multiple calls with same object, validate input, suppress error messages:

 use Statistics::LineFit;
 $lineFit = Statistics::LineFit->new(1, 1);
 while (1) {
     @xy = read2Dxy();  # User-supplied subroutine
     $lineFit->setData(\@xy);
     ($intercept, $slope) = $lineFit->coefficients();
     if (defined $intercept) {
         print "Slope: $slope  Y-intercept: $intercept\n";
     }
 }
See how the same object just keeps getting reused in that loop? That's the caching doing its main character thing. πŸ”₯

✨ METHODS ✨

okay so this module is state-oriented and it caches its results. Once you call the setData() method, you can call the other methods in any order or call a method several times without invoking redundant calculations. it's giving efficient, fr fr.

The regression fails if the x values are all the same. In this case, the module issues an error message and methods that return statistical values will return undefined values. You can also use the return value of the regress() method to check the status of the regression. lowkey important.


new() β€” create a new Statistics::LineFit object

$lineFit = Statistics::LineFit->new();
$lineFit = Statistics::LineFit->new($validate);
$lineFit = Statistics::LineFit->new($validate, $hush);
  • $validate = 1 β€” Verify input data is numeric (slower execution)
  • $validate = 0 β€” Don't verify input data (default, faster execution)
  • $hush = 1 β€” Suppress error messages
  • $hush = 0 β€” Enable error messages (default)

coefficients() β€” Return the slope and y intercept

($intercept, $slope) = $lineFit->coefficients();

The returned list is undefined if the regression fails. no cap.

durbinWatson() β€” Return the Durbin-Watson statistic

$durbinWatson = $lineFit->durbinWatson();

The Durbin-Watson test is a test for first-order autocorrelation in the residuals of a time series regression. The Durbin-Watson statistic has a range of 0 to 4; a value of 2 indicates there is no autocorrelation. iconic little range tbh.

The return value is undefined if the regression fails. If weights are input, the return value is the weighted Durbin-Watson statistic.

meanSqError() β€” Return the mean squared error

$meanSquaredError = $lineFit->meanSqError();

The return value is undefined if the regression fails. If weights are input, the return value is the weighted mean squared error.

predictedYs() β€” Return the predicted y values

@predictedYs = $lineFit->predictedYs();

The returned list is undefined if the regression fails.

regress() β€” Do the least squares line fit (if not already done)

$lineFit->regress() or die "Regression failed"

You don't need to call this method because it is invoked by the other methods as needed. After you call setData(), you can call regress() at any time to get the status of the regression for the current data. main character method behavior.

residuals() β€” Return predicted y values minus input y values

@residuals = $lineFit->residuals();

The returned list is undefined if the regression fails.

rSquared() β€” Return the square of the correlation coefficient

$rSquared = $lineFit->rSquared();

R squared, also called the square of the Pearson product-moment correlation coefficient, is a measure of goodness-of-fit. It is the fraction of the variation in Y that can be attributed to the variation in X. A perfect fit will have an R squared of 1; fitting a line to the vertices of a regular polygon will yield an R squared of zero. Graphical displays of data with an R squared of less than about 0.1 do not show a visible linear trend. the way that 0.1 cutoff is just sitting there.

The return value is undefined if the regression fails. If weights are input, the return value is the weighted correlation coefficient.

setData() β€” Initialize (x,y) values and optional weights

$lineFit->setData(\@x, \@y) or die "Invalid regression data";
$lineFit->setData(\@x, \@y, \@weights) or die "Invalid regression data";
$lineFit->setData(\@xy) or die "Invalid regression data";
$lineFit->setData(\@xy, \@weights) or die "Invalid regression data";

@xy is an array of arrayrefs; x values are $xy[$i][0], y values are $xy[$i][1]. (The module does not access any indices greater than $xy[$i][1], so the arrayrefs can point to arrays that are longer than two elements.) The method identifies the difference between the first and fourth calling signatures by examining the first argument.

The optional weights array must be the same length as the data array(s). The weights must be non-negative numbers; at least two of the weights must be nonzero. Only the relative size of the weights is significant: the program normalizes the weights (after copying the input values) so that the sum of the weights equals the number of points. If you want to do multiple line fits using the same weights, the weights must be passed to each call to setData(). iykyk.

The method will return zero if the array lengths don't match, there are less than two data points, any weights are negative or less than two of the weights are nonzero. If the new() method was called with validate = 1, the method will also verify that the data and weights are valid numbers. Once you successfully call setData(), the next call to any method other than new() or setData() invokes the regression. You can modify the input data or weights after calling setData() without affecting the module's results. slay, deep-copy-ish behavior.

sigma() β€” Return the standard error of the estimate

$sigma = $lineFit->sigma();

Sigma is an estimate of the homoscedastic standard deviation of the error. Sigma is also known as the standard error of the estimate.

The return value is undefined if the regression fails. If weights are input, the return value is the weighted standard error.

tStatistics() β€” Return the t statistics

(tStatIntercept, $tStatSlope) = $lineFit->tStatistics();

The t statistic, also called the t ratio or Wald statistic, is used to accept or reject a hypothesis using a table of cutoff values computed from the t distribution. The t-statistic suggests that the estimated value is (reasonable, too small, too large) when the t-statistic is (close to zero, large and positive, large and negative). not me reading this three times.

The returned list is undefined if the regression fails. If weights are input, the returned values are the weighted t statistics.

varianceOfEstimates() β€” Return variances of estimates of intercept, slope

(varianceIntercept, $varianceSlope) = $lineFit->varianceOfEstimates();

Assuming the data are noisy or inaccurate, the intercept and slope returned by the coefficients() method are only estimates of the true intercept and slope. The varianceofEstimate() method returns the variances of the estimates of the intercept and slope, respectively. See Numerical Recipes in C, section 15.2 (Fitting Data to a Straight Line), equation 15.2.9. math bestie moment.

The returned list is undefined if the regression fails. If weights are input, the returned values are the weighted variances.


πŸ‘€ SEE ALSO πŸ‘€

  • Mendenhall, W., and Sincich, T.L., 2003, A Second Course in Statistics: Regression Analysis, 6th ed., Prentice Hall.
  • Press, W. H., Flannery, B. P., Teukolsky, S. A., Vetterling, W. T., 1992, Numerical Recipes in C : The Art of Scientific Computing, 2nd ed., Cambridge University Press.
  • The man page for perl(1).
  • The CPAN modules Statistics::OLS, Statistics::GaussHelmert and Statistics::Regression.

Statistics::LineFit is simpler to use than Statistics::GaussHelmert or Statistics::Regression. Statistics::LineFit was inspired by and borrows some ideas from the venerable Statistics::OLS module. obsessed with a humble origin story.

The significant differences between Statistics::LineFit and Statistics::OLS (version 0.07) are:

  • Statistics::LineFit is more robust. Statistics::OLS returns incorrect results for certain input datasets. Statistics::OLS does not deep copy its input arrays, which can lead to subtle bugs. The Statistics::OLS installation test has only one test and does not verify that the regression returns correct results. In contrast, Statistics::LineFit has over 200 installation tests that use various datasets/calling sequences to verify the accuracy of the regression to within 1.0e-10.
  • Statistics::LineFit is faster. For a sequence of calls to new(), setData(\@x, \@y) and regress(), Statistics::LineFit is faster than Statistics::OLS by factors of 2.0, 1.6 and 2.4 for array lengths of 5, 100 and 10000, respectively.
  • Statistics::LineFit can do weighted or unweighted regression. Statistics::OLS lacks this option.
  • Statistics::LineFit has a better interface. Once you call the Statistics::LineFit::setData() method, you can call the other methods in any order and call methods multiple times without invoking redundant calculations. Statistics::LineFit lets you enable or disable data verification or error messages.
  • Statistics::LineFit has better code and documentation. The code in Statistics::LineFit is more readable, more object oriented and more compliant with Perl coding standards than the code in Statistics::OLS. The documentation for Statistics::LineFit is more detailed and complete. periodt.

πŸ’– AUTHOR πŸ’–

Richard Anderson, cpan(AT)richardanderson(DOT)org, http://www.richardanderson.org


πŸ“œ LICENSE πŸ“œ

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

The full text of the license can be found in the LICENSE file included in the distribution and available in the CPAN listing for Statistics::LineFit (see www.cpan.org or search.cpan.org).


⚠️ DISCLAIMER ⚠️

To the maximum extent permitted by applicable law, the author of this module disclaims all warranties, either express or implied, including but not limited to implied warranties of merchantability and fitness for a particular purpose, with regard to the software and the accompanying documentation. legal bestie has entered the chat.


okay bestie, that's the whole page β€” source/version/date: perl v5.36.0, 2022-12-12, Statis...LineFit(3pm). πŸ’…βœ¨

πŸ“¦ where this page comes from