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
|
|
|
|
{
|
2018-02-16 06:25:24 +00:00
|
|
|
public static function compute(array $actualLabels, array $predictedLabels, array $labels = []): array
|
2016-07-06 22:29:58 +00:00
|
|
|
{
|
2018-02-16 06:25:24 +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;
|
|
|
|
}
|
|
|
|
|
2017-11-22 21:16:10 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
|
2017-11-22 21:16:10 +00:00
|
|
|
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;
|
|
|
|
}
|
|
|
|
}
|