Created
February 14, 2017 17:01
-
-
Save mockiemockiz/813f6e553546d74b41fc000f64df7d3e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Helpers; | |
/* | |
* This class is an implementation of http://stackoverflow.com/questions/787496/what-is-the-best-way-to-compute-trending-topics-or-tags/826509#826509 in PHP. | |
*/ | |
class ZScore { | |
// The rate at which the historic data's effect will diminish | |
private $decay; | |
// The population (data) | |
private $pop; | |
private $avg; | |
private $sqrAvg; | |
public function __construct($decay, $pop) { | |
$this->sqrAvg = $this->avg = 0; | |
$this->decay = $decay; | |
$this->pop = $pop; | |
foreach($this->pop as $x) { | |
$this->update($x); | |
} | |
} | |
private function update($value) { | |
if($this->avg == 0 && $this->sqrAvg == 0) { | |
// Set initial averages to the first value in the sequence. | |
$this->avg = $value; | |
$this->sqrAvg = pow($value, 2); | |
} else { | |
// Calculate the average of the rest of the values using a floating average. | |
$this->avg = $this->avg * $this->decay + $value * (1 - $this->decay); | |
$this->sqrAvg = $this->sqrAvg * $this->decay + pow($value, 2) * (1 - $this->decay); | |
} | |
return $this; | |
} | |
private function std() { | |
// Somewhat ad-hoc standard deviation calculation. | |
return sqrt($this->sqrAvg - pow($this->avg, 2)); | |
} | |
public function score($obs) { | |
if($this->std() == 0) { | |
return ($obs - $this->avg) * 1.8e308; | |
} else { | |
return ($obs - $this->avg) / $this->std(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment