Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.

Differences Between: [Versions 311 and 400] [Versions 311 and 401] [Versions 311 and 402] [Versions 311 and 403]

   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(function (array $column) {
  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): void
  52      {
  53          foreach ($samples as &$sample) {
  54              $sample = array_values(array_intersect_key($sample, $this->keepColumns));
  55          }
  56      }
  57  }