php-ml/src/Metric/ConfusionMatrix.php

54 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
{
2018-10-28 06:44:52 +00:00
$labels = count($labels) === 0 ? self::getUniqueLabels($actualLabels) : array_flip($labels);
2016-07-06 22:29:58 +00:00
$matrix = self::generateMatrixWithZeros($labels);
foreach ($actualLabels as $index => $actual) {
$predicted = $predictedLabels[$index];
2018-10-28 06:44:52 +00:00
if (!isset($labels[$actual], $labels[$predicted])) {
2016-07-06 22:29:58 +00:00
continue;
}
if ($predicted === $actual) {
$row = $column = $labels[$actual];
} else {
$row = $labels[$actual];
$column = $labels[$predicted];
}
++$matrix[$row][$column];
2016-07-06 22:29:58 +00:00
}
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);
return array_flip($labels);
2016-07-06 22:29:58 +00:00
}
}