A small PHP library for fitting a straight line to paired data with ordinary least squares. It uses brick/math and BCMath for precise intermediate arithmetic and provides predictions, residuals, cumulative residuals, regression-line points, and the coefficient of determination.
Originally forked from davebarnwell/ml-regression-least-squares.
- PHP 8.1 or later
- BCMath extension
composer require luminsports/linear-regressionuse LuminSports\LinearRegression\LeastSquares;
$targets = [1, 2, 3, 4];
$observations = [2.1, 4.0, 6.2, 7.9];
$regression = new LeastSquares($targets, $observations);
$slope = $regression->getSlope();
$intercept = $regression->getIntercept();
$rSquared = $regression->getRSquared();
$predictedObservation = $regression->predictY(5);
$predictedTarget = $regression->predictX(10);
$residuals = $regression->getDifferencesFromRegressionLine();
$cumulativeResiduals = $regression->getCumulativeSumOfDifferencesFromRegressionLine();
$linePoints = $regression->getRegressionLinePoints();The X series represents target or independent values; the Y series represents observed or dependent values. Both arrays must contain the same number of elements or SeriesCountMismatch is thrown.
The optional constructor precision controls division and rounding:
$regression = new LeastSquares($targets, $observations, precision: 12);
$regression->setPrecision(10);composer install
composer test
composer phpstan
composer check-styleGenerate an HTML coverage report with composer coverage. Apply formatting intentionally with composer fix-style.
Keep changes focused on the numerical library, preserve supported PHP compatibility, and add regression tests for calculation changes. See the Lumin Sports contributing guide.
Report security vulnerabilities privately through the repository security policy; do not disclose sensitive details in a public issue.
Released under the MIT License. See LICENSE.md and COPYRIGHT.