Regression.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. <?php
  2. namespace MathPHP\Statistics\Regression;
  3. /**
  4. * Base class for regressions.
  5. */
  6. abstract class Regression
  7. {
  8. /**
  9. * Array of x and y points: [ [x, y], [x, y], ... ]
  10. * @var array<array{float, float}>
  11. */
  12. protected $points;
  13. /**
  14. * X values of the original points
  15. * @var array<float>
  16. */
  17. protected $xs;
  18. /**
  19. * Y values of the original points
  20. * @var array<float>
  21. */
  22. protected $ys;
  23. /**
  24. * Number of points
  25. * @var int
  26. */
  27. protected $n;
  28. /**
  29. * Constructor - Prepares the data arrays for regression analysis
  30. *
  31. * @param array<array{float, float}> $points [ [x, y], [x, y], ... ]
  32. */
  33. public function __construct(array $points)
  34. {
  35. $this->points = $points;
  36. $this->n = \count($points);
  37. // Get list of x points and y points.
  38. // This will be fine for linear or polynomial regression, where there is only one x,
  39. // but if expanding to multiple linear, the format will have to change.
  40. $this->xs = \array_map(function ($point) {
  41. return $point[0];
  42. }, $points);
  43. $this->ys = \array_map(function ($point) {
  44. return $point[1];
  45. }, $points);
  46. }
  47. /**
  48. * Evaluate the regression equation at x
  49. *
  50. * @param float $x
  51. *
  52. * @return float
  53. */
  54. abstract public function evaluate(float $x): float;
  55. /**
  56. * Get points
  57. *
  58. * @return array<array{float, float}>
  59. */
  60. public function getPoints(): array
  61. {
  62. return $this->points;
  63. }
  64. /**
  65. * Get Xs (x values of each point)
  66. *
  67. * @return array<float> of x values
  68. */
  69. public function getXs(): array
  70. {
  71. return $this->xs;
  72. }
  73. /**
  74. * Get Ys (y values of each point)
  75. *
  76. * @return array<float> of y values
  77. */
  78. public function getYs(): array
  79. {
  80. return $this->ys;
  81. }
  82. /**
  83. * Get sample size (number of points)
  84. *
  85. * @return int
  86. */
  87. public function getSampleSize(): int
  88. {
  89. return $this->n;
  90. }
  91. /**
  92. * Ŷ (yhat)
  93. * A list of the predicted values of Y given the regression.
  94. *
  95. * @return array<float>
  96. */
  97. public function yHat(): array
  98. {
  99. return \array_map([$this, 'evaluate'], $this->xs);
  100. }
  101. }