Skip to content

Instantly share code, notes, and snippets.

@sinri
Created September 8, 2015 09:05
Show Gist options
  • Save sinri/8b98b92a7ac3fc8ed5d3 to your computer and use it in GitHub Desktop.
Save sinri/8b98b92a7ac3fc8ed5d3 to your computer and use it in GitHub Desktop.
線形回帰の単回帰をPHPで実装 ref: http://qiita.com/sinri/items/fcca46db672ea3d9c1ea
/**
* Copyright 2015 Sinri Edogawa.
*/
class LinearRegression
{
private $xs;
private $ys;
private $element_count;
private $a;
private $b;
function __construct()
{
$this->xs=array();
$this->ys=array();
$this->element_count=0;
}
public function addElement($x,$y){
$this->xs[]=$x;
$this->ys[]=$y;
$this->element_count+=1;
}
//y=a+bx
public function getConstBase(){
return $this->a;
}
public function getParamFactor(){
return $this->b;
}
public function computeLR(){
if($this->element_count<=0)return false;
if($this->element_count!=count($this->xs) || $this->element_count!=count($this->ys))return false;
$x_sum=0;
$y_sum=0;
for ($i=0; $i < $this->element_count; $i++) {
$x_sum+=$this->xs[$i];
$y_sum+=$this->ys[$i];
}
$x_ave=1.0*$x_sum/$this->element_count;
$y_ave=1.0*$y_sum/$this->element_count;
$up=0;
$down=0;
for ($i=0; $i < $this->element_count; $i++) {
$up+=($this->xs[$i]-$x_ave)*($this->ys[$i]-$y_ave);
$down+=($this->xs[$i]-$x_ave)*($this->xs[$i]-$x_ave);
}
if($down==0)return false;
$this->b=$up/$down;
$this->a=$y_ave-$x_ave*$this->b;
return true;
}
}
$LR=new LinearRegression();
//xとyのペアを繰り返して記録する
$LR->addElement($x,$y);
$lr_done=$LR->computeLR();
if($lr_done){
echo "y=".$LR->getConstBase()."+".$LR->getParamFactor()."x";
}else{
echo "FAILED";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment