php-ml/src/Phpml/Metric/Accuracy.php

40 lines
863 B
PHP
Raw Normal View History

2016-04-08 20:11:59 +00:00
<?php
2016-04-08 20:49:17 +00:00
declare (strict_types = 1);
2016-04-08 20:11:59 +00:00
namespace Phpml\Metric;
use Phpml\Exception\InvalidArgumentException;
class Accuracy
{
/**
* @param array $actualLabels
* @param array $predictedLabels
2016-04-08 20:49:17 +00:00
* @param bool $normalize
2016-04-08 20:11:59 +00:00
*
* @return float|int
*
* @throws InvalidArgumentException
*/
public static function score(array $actualLabels, array $predictedLabels, bool $normalize = true)
{
if (count($actualLabels) != count($predictedLabels)) {
throw InvalidArgumentException::sizeNotMatch();
}
$score = 0;
foreach ($actualLabels as $index => $label) {
2016-04-09 13:33:05 +00:00
if ($label == $predictedLabels[$index]) {
2016-04-08 20:49:17 +00:00
++$score;
2016-04-08 20:11:59 +00:00
}
}
2016-04-08 20:49:17 +00:00
if ($normalize) {
2016-04-08 20:11:59 +00:00
$score = $score / count($actualLabels);
}
return $score;
}
}