Issues (14)

src/Metric/ConfusionMatrix.php (2 issues)

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);
0 ignored issues
show
It seems like $labels can also be of type null; however, parameter $labels of Phpml\Metric\ConfusionMa...nerateMatrixWithZeros() does only seem to accept array, maybe add an additional type check? ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-type  annotation

12
        $matrix = self::generateMatrixWithZeros(/** @scrutinizer ignore-type */ $labels);
Loading history...
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);
0 ignored issues
show
Bug Best Practice introduced by Tomáš Votruba
The expression return array_flip($labels) could return the type null which is incompatible with the type-hinted return array. Consider adding an additional type-check to rule them out.
Loading history...
52
    }
53
}
54