Linear.php 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace MathPHP\Statistics\Regression;
  3. use MathPHP\Exception;
  4. /**
  5. * Simple linear regression - least squares method
  6. *
  7. * A model with a single explanatory variable.
  8. * Fits a straight line through the set of n points in such a way that makes
  9. * the sum of squared residuals of the model (that is, vertical distances
  10. * between the points of the data set and the fitted line) as small as possible.
  11. * https://en.wikipedia.org/wiki/Simple_linear_regression
  12. *
  13. * Having data points {(xᵢ, yᵢ), i = 1 ..., n }
  14. * Find the equation y = mx + b
  15. *
  16. * _ _ __
  17. * x y - xy
  18. * m = _________
  19. * _ __
  20. * (x)² - x²
  21. *
  22. * _ _
  23. * b = y - mx
  24. */
  25. class Linear extends ParametricRegression
  26. {
  27. use Methods\LeastSquares;
  28. use Models\LinearModel;
  29. /**
  30. * Calculates the regression parameters.
  31. *
  32. * @throws Exception\BadDataException
  33. * @throws Exception\IncorrectTypeException
  34. * @throws Exception\MatrixException
  35. * @throws Exception\MathException
  36. */
  37. public function calculate(): void
  38. {
  39. $this->parameters = $this->leastSquares($this->ys, $this->xs)->getColumn(0);
  40. }
  41. /**
  42. * Evaluate the regression equation at x
  43. * Uses the instance model's evaluateModel method.
  44. *
  45. * @param float $x
  46. *
  47. * @return float
  48. */
  49. public function evaluate(float $x): float
  50. {
  51. return $this->evaluateModel($x, $this->parameters);
  52. }
  53. }