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
|
|
|
|
{
|
|
|
|
/**
|
|
|
|
* @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)) {
|
2016-04-18 20:58:43 +00:00
|
|
|
throw InvalidArgumentException::arraySizeNotMatch();
|
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;
|
|
|
|
}
|
|
|
|
}
|