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

73 lines
1.4 KiB
PHP
Raw Normal View History

2016-04-25 20:55:34 +00:00
<?php
declare (strict_types = 1);
namespace Phpml\Regression;
2016-04-27 21:51:14 +00:00
use Phpml\Math\Statistic\Correlation;
use Phpml\Math\Statistic\StandardDeviation;
use Phpml\Math\Statistic\Mean;
2016-04-25 20:55:34 +00:00
class LeastSquares implements Regression
{
/**
* @var array
*/
private $features;
/**
* @var array
*/
private $targets;
/**
* @var float
*/
private $slope;
/**
* @var
*/
private $intercept;
2016-04-25 20:55:34 +00:00
/**
* @param array $features
* @param array $targets
*/
public function train(array $features, array $targets)
{
$this->features = $features;
$this->targets = $targets;
2016-04-27 21:51:14 +00:00
$this->computeSlope();
$this->computeIntercept();
2016-04-25 20:55:34 +00:00
}
/**
2016-04-27 21:51:14 +00:00
* @param float $feature
2016-04-25 20:55:34 +00:00
*
* @return mixed
*/
2016-04-27 21:51:14 +00:00
public function predict($feature)
{
return $this->intercept + ($this->slope * $feature);
}
private function computeSlope()
2016-04-25 20:55:34 +00:00
{
2016-04-27 21:51:14 +00:00
$correlation = Correlation::pearson($this->features, $this->targets);
$sdX = StandardDeviation::population($this->features);
$sdY = StandardDeviation::population($this->targets);
$this->slope = $correlation * ($sdY / $sdX);
}
private function computeIntercept()
{
$meanY = Mean::arithmetic($this->targets);
$meanX = Mean::arithmetic($this->features);
$this->intercept = $meanY - ($this->slope * $meanX);
2016-04-25 20:55:34 +00:00
}
}