php-ml/src/Metric/Accuracy.php

36 lines
770 B
PHP
Raw Normal View History

2016-04-08 20:11:59 +00:00
<?php
2016-04-08 20:49:17 +00:00
2016-11-20 21:53:17 +00:00
declare(strict_types=1);
2016-04-08 20:11:59 +00:00
namespace Phpml\Metric;
use Phpml\Exception\InvalidArgumentException;
class Accuracy
{
/**
* @return float|int
*
* @throws InvalidArgumentException
*/
public static function score(array $actualLabels, array $predictedLabels, bool $normalize = true)
{
if (count($actualLabels) != count($predictedLabels)) {
throw new InvalidArgumentException('Size of given arrays does not match');
2016-04-08 20:11:59 +00:00
}
$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-12-12 17:34:20 +00:00
$score /= count($actualLabels);
2016-04-08 20:11:59 +00:00
}
return $score;
}
}