php-ml/src/Metric/ConfusionMatrix.php

55 lines
1.3 KiB
PHP
Raw Normal View History

2016-07-06 22:29:58 +00:00
<?php
2016-11-20 21:53:17 +00:00
declare(strict_types=1);
2016-07-06 22:29:58 +00:00
namespace Phpml\Metric;
class ConfusionMatrix
{
public static function compute(array $actualLabels, array $predictedLabels, array $labels = []): array
2016-07-06 22:29:58 +00:00
{
$labels = !empty($labels) ? array_flip($labels) : self::getUniqueLabels($actualLabels);
2016-07-06 22:29:58 +00:00
$matrix = self::generateMatrixWithZeros($labels);
foreach ($actualLabels as $index => $actual) {
$predicted = $predictedLabels[$index];
if (!isset($labels[$actual]) || !isset($labels[$predicted])) {
continue;
}
if ($predicted === $actual) {
$row = $column = $labels[$actual];
} else {
$row = $labels[$actual];
$column = $labels[$predicted];
}
$matrix[$row][$column] += 1;
}
return $matrix;
}
private static function generateMatrixWithZeros(array $labels): array
2016-07-06 22:29:58 +00:00
{
$count = count($labels);
$matrix = [];
for ($i = 0; $i < $count; ++$i) {
$matrix[$i] = array_fill(0, $count, 0);
}
return $matrix;
}
private static function getUniqueLabels(array $labels): array
2016-07-06 22:29:58 +00:00
{
$labels = array_values(array_unique($labels));
sort($labels);
$labels = array_flip($labels);
return $labels;
}
}