php-ml/src/Math/Statistic/Correlation.php

42 lines
894 B
PHP
Raw Normal View History

2016-04-27 21:28:01 +00:00
<?php
2016-11-20 21:53:17 +00:00
declare(strict_types=1);
2016-04-27 21:28:01 +00:00
namespace Phpml\Math\Statistic;
use Phpml\Exception\InvalidArgumentException;
class Correlation
{
/**
* @param int[]|float[] $x
* @param int[]|float[] $y
2016-04-27 21:28:01 +00:00
*
* @throws InvalidArgumentException
*/
public static function pearson(array $x, array $y): float
2016-04-27 21:28:01 +00:00
{
if (count($x) !== count($y)) {
throw new InvalidArgumentException('Size of given arrays does not match');
2016-04-27 21:28:01 +00:00
}
$count = count($x);
2016-04-27 21:57:05 +00:00
$meanX = Mean::arithmetic($x);
$meanY = Mean::arithmetic($y);
2016-04-27 21:28:01 +00:00
$axb = 0;
$a2 = 0;
$b2 = 0;
2016-11-20 21:53:17 +00:00
for ($i = 0; $i < $count; ++$i) {
2016-04-27 21:28:01 +00:00
$a = $x[$i] - $meanX;
$b = $y[$i] - $meanY;
2016-12-12 17:34:20 +00:00
$axb += ($a * $b);
$a2 += pow($a, 2);
$b2 += pow($b, 2);
2016-04-27 21:28:01 +00:00
}
return $axb / sqrt((float) ($a2 * $b2));
2016-04-27 21:28:01 +00:00
}
}