Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace Phpml\Preprocessing;
   6  
   7  final class LabelEncoder implements Preprocessor
   8  {
   9      /**
  10       * @var int[]
  11       */
  12      private $classes = [];
  13  
  14      public function fit(array $samples, ?array $targets = null): void
  15      {
  16          $this->classes = [];
  17  
  18          foreach ($samples as $sample) {
  19              if (!isset($this->classes[(string) $sample])) {
  20                  $this->classes[(string) $sample] = count($this->classes);
  21              }
  22          }
  23      }
  24  
  25      public function transform(array &$samples, ?array &$targets = null): void
  26      {
  27          foreach ($samples as &$sample) {
  28              $sample = $this->classes[(string) $sample];
  29          }
  30      }
  31  
  32      public function inverseTransform(array &$samples): void
  33      {
  34          $classes = array_flip($this->classes);
  35          foreach ($samples as &$sample) {
  36              $sample = $classes[$sample];
  37          }
  38      }
  39  
  40      /**
  41       * @return string[]
  42       */
  43      public function classes(): array
  44      {
  45          return array_keys($this->classes);
  46      }
  47  }