Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.

Differences Between: [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 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  }