LoginSignup
3
4

More than 5 years have passed since last update.

線形回帰の単回帰をPHPで実装

Posted at

線形回帰の単回帰をPHPで実装してみた。

例のxとyの間に、y=a+bx+eというモデルで示せる関係を持てば、ある程度のxとyのペアの配列から、最小二乗分析によって最小二乗モデルを計算することができる。つまり、条件付き期待値をy=A+Bxとして表示できる。

コードは下の通りである。

/**
* 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";
}
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4