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.

Differences Between: [Versions 401 and 403]

   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace Phpml;
   6  
   7  use Phpml\Exception\InvalidArgumentException;
   8  
   9  final class FeatureUnion implements Transformer
  10  {
  11      /**
  12       * @var Pipeline[]
  13       */
  14      private $pipelines = [];
  15  
  16      /**
  17       * @var Pipeline[]
  18       */
  19      public function __construct(array $pipelines)
  20      {
  21          if ($pipelines === []) {
  22              throw new InvalidArgumentException('At least one pipeline is required');
  23          }
  24  
  25          $this->pipelines = array_map(static function (Pipeline $pipeline): Pipeline {
  26              return $pipeline;
  27          }, $pipelines);
  28      }
  29  
  30      public function fit(array $samples, ?array $targets = null): void
  31      {
  32          $originSamples = $samples;
  33          foreach ($this->pipelines as $pipeline) {
  34              foreach ($pipeline->getTransformers() as $transformer) {
  35                  $transformer->fit($samples, $targets);
  36                  $transformer->transform($samples, $targets);
  37              }
  38              $samples = $originSamples;
  39          }
  40      }
  41  
  42      public function transform(array &$samples, ?array &$targets = null): void
  43      {
  44          $this->transformSamples($samples, $targets);
  45      }
  46  
  47      public function fitAndTransform(array &$samples, ?array &$targets = null): void
  48      {
  49          $this->transformSamples($samples, $targets, true);
  50      }
  51  
  52      private function transformSamples(array &$samples, ?array &$targets = null, bool $fit = false): void
  53      {
  54          $union = [];
  55          $originSamples = $samples;
  56          foreach ($this->pipelines as $pipeline) {
  57              foreach ($pipeline->getTransformers() as $transformer) {
  58                  if ($fit) {
  59                      $transformer->fit($samples, $targets);
  60                  }
  61                  $transformer->transform($samples, $targets);
  62              }
  63  
  64              foreach ($samples as $index => $sample) {
  65                  $union[$index] = array_merge($union[$index] ?? [], is_array($sample) ? $sample : [$sample]);
  66              }
  67              $samples = $originSamples;
  68          }
  69  
  70          $samples = $union;
  71      }
  72  }