/** * @param array $samples * @param array $targets * * @throws InvalidArgumentException */ public function __construct(array $samples, array $targets) { if (count($samples) != count($targets)) { throw InvalidArgumentException::arraySizeNotMatch(); } $this->samples = $samples; $this->targets = $targets; }
/** * @param array $a * @param array $b * * @return float * * @throws InvalidArgumentException */ public function distance(array $a, array $b) : float { if (count($a) !== count($b)) { throw InvalidArgumentException::arraySizeNotMatch(); } $distance = 0; $count = count($a); for ($i = 0; $i < $count; ++$i) { $distance += abs($a[$i] - $b[$i]); } return $distance; }
/** * @param array $actualLabels * @param array $predictedLabels * @param bool $normalize * * @return float|int * * @throws InvalidArgumentException */ public static function score(array $actualLabels, array $predictedLabels, bool $normalize = true) { if (count($actualLabels) != count($predictedLabels)) { throw InvalidArgumentException::arraySizeNotMatch(); } $score = 0; foreach ($actualLabels as $index => $label) { if ($label == $predictedLabels[$index]) { ++$score; } } if ($normalize) { $score = $score / count($actualLabels); } return $score; }
/** * @param array|int[]|float[] $x * @param array|int[]|float[] $y * * @return float * * @throws InvalidArgumentException */ public static function pearson(array $x, array $y) { if (count($x) !== count($y)) { throw InvalidArgumentException::arraySizeNotMatch(); } $count = count($x); $meanX = Mean::arithmetic($x); $meanY = Mean::arithmetic($y); $axb = 0; $a2 = 0; $b2 = 0; for ($i = 0; $i < $count; ++$i) { $a = $x[$i] - $meanX; $b = $y[$i] - $meanY; $axb = $axb + $a * $b; $a2 = $a2 + pow($a, 2); $b2 = $b2 + pow($b, 2); } $corr = $axb / sqrt((double) ($a2 * $b2)); return $corr; }