Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
   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  }