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\Helper\Optimizer;
   6  
   7  use Closure;
   8  use Phpml\Exception\InvalidArgumentException;
   9  
  10  abstract class Optimizer
  11  {
  12      /**
  13       * Unknown variables to be found
  14       *
  15       * @var array
  16       */
  17      protected $theta = [];
  18  
  19      /**
  20       * Number of dimensions
  21       *
  22       * @var int
  23       */
  24      protected $dimensions;
  25  
  26      /**
  27       * Inits a new instance of Optimizer for the given number of dimensions
  28       */
  29      public function __construct(int $dimensions)
  30      {
  31          $this->dimensions = $dimensions;
  32  
  33          // Inits the weights randomly
  34          $this->theta = [];
  35          for ($i = 0; $i < $this->dimensions; ++$i) {
  36              $this->theta[] = (random_int(0, PHP_INT_MAX) / PHP_INT_MAX) + 0.1;
  37          }
  38      }
  39  
  40      public function setTheta(array $theta): self
  41      {
  42          if (count($theta) !== $this->dimensions) {
  43              throw new InvalidArgumentException(sprintf('Number of values in the weights array should be %s', $this->dimensions));
  44          }
  45  
  46          $this->theta = $theta;
  47  
  48          return $this;
  49      }
  50  
  51      /**
  52       * Executes the optimization with the given samples & targets
  53       * and returns the weights
  54       */
  55      abstract public function runOptimization(array $samples, array $targets, Closure $gradientCb): array;
  56  }