Passed
Push — master ( 53c5a6...f2dd40 )
by Arkadiusz
02:17
created

ConfusionMatrix::compute()   A

Complexity

Conditions 5
Paths 8

Size

Total Lines 24

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 24
rs 9.2248
c 0
b 0
f 0
cc 5
nc 8
nop 3
1
<?php
2
3
declare(strict_types=1);
4
5
namespace Phpml\Metric;
6
7
class ConfusionMatrix
8
{
9
    public static function compute(array $actualLabels, array $predictedLabels, array $labels = []): array
10
    {
11
        $labels = count($labels) === 0 ? self::getUniqueLabels($actualLabels) : array_flip($labels);
12
        $matrix = self::generateMatrixWithZeros($labels);
13
14
        foreach ($actualLabels as $index => $actual) {
15
            $predicted = $predictedLabels[$index];
16
17
            if (!isset($labels[$actual], $labels[$predicted])) {
18
                continue;
19
            }
20
21
            if ($predicted === $actual) {
22
                $row = $column = $labels[$actual];
23
            } else {
24
                $row = $labels[$actual];
25
                $column = $labels[$predicted];
26
            }
27
28
            ++$matrix[$row][$column];
29
        }
30
31
        return $matrix;
32
    }
33
34
    private static function generateMatrixWithZeros(array $labels): array
35
    {
36
        $count = count($labels);
37
        $matrix = [];
38
39
        for ($i = 0; $i < $count; ++$i) {
40
            $matrix[$i] = array_fill(0, $count, 0);
41
        }
42
43
        return $matrix;
44
    }
45
46
    private static function getUniqueLabels(array $labels): array
47
    {
48
        $labels = array_values(array_unique($labels));
49
        sort($labels);
50
51
        return array_flip($labels);
52
    }
53
}
54