Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400]

   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace Phpml\FeatureSelection;
   6  
   7  use Phpml\Exception\InvalidArgumentException;
   8  use Phpml\Math\Matrix;
   9  use Phpml\Math\Statistic\Variance;
  10  use Phpml\Transformer;
  11  
  12  final class VarianceThreshold implements Transformer
  13  {
  14      /**
  15       * @var float
  16       */
  17      private $threshold;
  18  
  19      /**
  20       * @var array
  21       */
  22      private $variances = [];
  23  
  24      /**
  25       * @var array
  26       */
  27      private $keepColumns = [];
  28  
  29      public function __construct(float $threshold = 0.0)
  30      {
  31          if ($threshold < 0) {
  32              throw new InvalidArgumentException('Threshold can\'t be lower than zero');
  33          }
  34  
  35          $this->threshold = $threshold;
  36      }
  37  
  38      public function fit(array $samples, ?array $targets = null): void
  39      {
  40          $this->variances = array_map(static function (array $column): float {
  41              return Variance::population($column);
  42          }, Matrix::transposeArray($samples));
  43  
  44          foreach ($this->variances as $column => $variance) {
  45              if ($variance > $this->threshold) {
  46                  $this->keepColumns[$column] = true;
  47              }
  48          }
  49      }
  50  
  51      public function transform(array &$samples, ?array &$targets = null): void
  52      {
  53          foreach ($samples as &$sample) {
  54              $sample = array_values(array_intersect_key($sample, $this->keepColumns));
  55          }
  56      }
  57  }