Skip to content

Instantly share code, notes, and snippets.

@greydnls
Last active May 7, 2021 07:48
Show Gist options
  • Save greydnls/a7c479accd97a7cabade to your computer and use it in GitHub Desktop.
Save greydnls/a7c479accd97a7cabade to your computer and use it in GitHub Desktop.
Least Squares Method
<?php
/**
* Created by PhpStorm.
* User: kayladnls
* Date: 12/19/14
* Time: 4:52 PM
*/
class LeastSquares
{
private $y_int;
private $slope;
/*
* A method to train the function. Pass in an array of points
* representing the data that you will be estimating against.
* ex: $data = [ 0 => [1, 2], 1 => [2, 4]]
*/
public function train(array $data)
{
list($x, $y) = $this->splitInput($data);
$mean_x = $this->mean($x);
$mean_y = $this->mean($y);
$mean_intercept = [$mean_x, $mean_y];
$barx = array_map(function($x) use($mean_x) {
return $x - $mean_x;
}, $x);
$bary = array_map(function($y) use($mean_y) {
return $y - $mean_y;
}, $y);
$this->slope = $this->calcSlope($barx, $bary);
$this->y_int = $this->calcYInt($this->slope, $mean_intercept);
}
public function estimate($x)
{
return $this->y_int + ($this->slope * $x);
}
private function calcYInt($slope, $mean_intercept)
{
return $mean_intercept[1] - ($slope * $mean_intercept[0]);
}
private function splitInput(array $data)
{
$x = [];
$y = [];
foreach ($data as $datum)
{
$x[] = $datum[0];
$y[] = $datum[1];
}
return [$x, $y];
}
private function calcSlope($barx, $bary)
{
$barxsq = $this->squareArr($barx);
$barx_times_bary = $this->multArrs($barx, $bary);
return array_sum($barx_times_bary) / array_sum($barxsq);
}
private function multArrs($array1, $arry2)
{
return array_map(function($x, $y) {
return $x*$y;
}, $array1, $arry2);
}
private function squareArr(array $vals)
{
return array_map(
function ($val)
{
return $val*$val;
},
$vals
);
}
private function mean(array $vals)
{
return array_sum($vals) / count($vals);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment