php-ml/src/Metric/ConfusionMatrix.php
Tomáš Votruba 46fa2c2cca Update to EasyCodingStandard 4 (#273)
* update ECS config to v4

* composer: require Symplify 4

* apply coding-standard: use constants over functions, protected setUp() in tests, array indentation

* ecs: add false positive case

* composer: update lock

* bump to ECS 4.4

* update composer.lock

* shorten ECS config name

* ecs: ignore assignments in while()

* fix cs
2018-06-15 07:57:45 +02:00

54 lines
1.3 KiB
PHP

<?php
declare(strict_types=1);
namespace Phpml\Metric;
class ConfusionMatrix
{
public static function compute(array $actualLabels, array $predictedLabels, array $labels = []): array
{
$labels = !empty($labels) ? array_flip($labels) : self::getUniqueLabels($actualLabels);
$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];
}
return $matrix;
}
private static function generateMatrixWithZeros(array $labels): array
{
$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
{
$labels = array_values(array_unique($labels));
sort($labels);
return array_flip($labels);
}
}