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.
   1  <?php
   2  
   3  declare(strict_types=1);
   4  
   5  namespace Phpml\NeuralNetwork;
   6  
   7  use Phpml\Exception\InvalidArgumentException;
   8  use Phpml\NeuralNetwork\Node\Neuron;
   9  
  10  class Layer
  11  {
  12      /**
  13       * @var Node[]
  14       */
  15      private $nodes = [];
  16  
  17      /**
  18       * @throws InvalidArgumentException
  19       */
  20      public function __construct(int $nodesNumber = 0, string $nodeClass = Neuron::class, ?ActivationFunction $activationFunction = null)
  21      {
  22          if (!in_array(Node::class, class_implements($nodeClass), true)) {
  23              throw new InvalidArgumentException('Layer node class must implement Node interface');
  24          }
  25  
  26          for ($i = 0; $i < $nodesNumber; ++$i) {
  27              $this->nodes[] = $this->createNode($nodeClass, $activationFunction);
  28          }
  29      }
  30  
  31      public function addNode(Node $node): void
  32      {
  33          $this->nodes[] = $node;
  34      }
  35  
  36      /**
  37       * @return Node[]
  38       */
  39      public function getNodes(): array
  40      {
  41          return $this->nodes;
  42      }
  43  
  44      private function createNode(string $nodeClass, ?ActivationFunction $activationFunction = null): Node
  45      {
  46          if ($nodeClass === Neuron::class) {
  47              return new Neuron($activationFunction);
  48          }
  49  
  50          return new $nodeClass();
  51      }
  52  }