Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401]

   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  }