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\NeuralNetwork\Node;
   6  
   7  use Phpml\NeuralNetwork\ActivationFunction;
   8  use Phpml\NeuralNetwork\ActivationFunction\Sigmoid;
   9  use Phpml\NeuralNetwork\Node;
  10  use Phpml\NeuralNetwork\Node\Neuron\Synapse;
  11  
  12  class Neuron implements Node
  13  {
  14      /**
  15       * @var Synapse[]
  16       */
  17      protected $synapses = [];
  18  
  19      /**
  20       * @var ActivationFunction
  21       */
  22      protected $activationFunction;
  23  
  24      /**
  25       * @var float
  26       */
  27      protected $output = 0.0;
  28  
  29      /**
  30       * @var float
  31       */
  32      protected $z = 0.0;
  33  
  34      public function __construct(?ActivationFunction $activationFunction = null)
  35      {
  36          $this->activationFunction = $activationFunction ?: new Sigmoid();
  37      }
  38  
  39      public function addSynapse(Synapse $synapse): void
  40      {
  41          $this->synapses[] = $synapse;
  42      }
  43  
  44      /**
  45       * @return Synapse[]
  46       */
  47      public function getSynapses(): array
  48      {
  49          return $this->synapses;
  50      }
  51  
  52      public function getOutput(): float
  53      {
  54          if ($this->output === 0.0) {
  55              $this->z = 0;
  56              foreach ($this->synapses as $synapse) {
  57                  $this->z += $synapse->getOutput();
  58              }
  59  
  60              $this->output = $this->activationFunction->compute($this->z);
  61          }
  62  
  63          return $this->output;
  64      }
  65  
  66      public function getDerivative(): float
  67      {
  68          return $this->activationFunction->differentiate($this->z, $this->output);
  69      }
  70  
  71      public function reset(): void
  72      {
  73          $this->output = 0.0;
  74          $this->z = 0.0;
  75      }
  76  }