php-ml/src/Phpml/Regression/LeastSquares.php

81 lines
1.5 KiB
PHP
Raw Normal View History

2016-04-25 20:55:34 +00:00
<?php
declare (strict_types = 1);
namespace Phpml\Regression;
use Phpml\Math\Matrix;
2016-04-27 21:51:14 +00:00
2016-04-25 20:55:34 +00:00
class LeastSquares implements Regression
{
2016-04-29 21:03:08 +00:00
/**
* @var array
*/
private $samples;
2016-04-25 20:55:34 +00:00
/**
* @var array
*/
private $targets;
/**
* @var float
*/
private $intercept;
/**
* @var array
*/
private $coefficients;
2016-04-25 20:55:34 +00:00
/**
2016-04-29 21:03:08 +00:00
* @param array $samples
2016-04-25 20:55:34 +00:00
* @param array $targets
*/
2016-04-29 21:03:08 +00:00
public function train(array $samples, array $targets)
2016-04-25 20:55:34 +00:00
{
2016-04-29 21:03:08 +00:00
$this->samples = $samples;
2016-04-25 20:55:34 +00:00
$this->targets = $targets;
2016-04-27 21:51:14 +00:00
$this->computeCoefficients();
2016-04-25 20:55:34 +00:00
}
/**
* @param array $sample
2016-04-25 20:55:34 +00:00
*
* @return mixed
*/
2016-04-29 21:03:08 +00:00
public function predict($sample)
2016-04-27 21:51:14 +00:00
{
2016-04-29 21:03:08 +00:00
$result = $this->intercept;
foreach ($this->coefficients as $index => $coefficient) {
$result += $coefficient * $sample[$index];
2016-04-29 21:03:08 +00:00
}
return $result;
2016-04-27 21:51:14 +00:00
}
2016-04-29 21:03:08 +00:00
/**
* @return array
*/
public function getCoefficients()
2016-04-25 20:55:34 +00:00
{
return $this->coefficients;
2016-04-29 21:03:08 +00:00
}
/**
2016-04-29 22:59:10 +00:00
* coefficient(b) = (X'X)-1X'Y.
2016-04-29 21:03:08 +00:00
*/
private function computeCoefficients()
2016-04-29 21:03:08 +00:00
{
$samplesMatrix = new Matrix($this->samples);
$targetsMatrix = new Matrix($this->targets);
$ts = $samplesMatrix->transpose()->multiply($samplesMatrix)->inverse();
$tf = $samplesMatrix->transpose()->multiply($targetsMatrix);
2016-04-27 21:51:14 +00:00
$this->coefficients = $ts->multiply($tf)->getColumnValues(0);
$this->intercept = array_shift($this->coefficients);
2016-04-25 20:55:34 +00:00
}
}