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 310 and 401] [Versions 311 and 401] [Versions 39 and 401]

   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  }