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\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      public function theta(): array
  52      {
  53          return $this->theta;
  54      }
  55  
  56      /**
  57       * Executes the optimization with the given samples & targets
  58       * and returns the weights
  59       */
  60      abstract public function runOptimization(array $samples, array $targets, Closure $gradientCb): array;
  61  }