Neuron.php 1.5 KB
Newer Older
1
2
<?php

Arkadiusz Kondas's avatar
Arkadiusz Kondas committed
3
declare(strict_types=1);
4
5
6

namespace Phpml\NeuralNetwork\Node;

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
16
    /**
     * @var Synapse[]
     */
17
    protected $synapses = [];
18
19
20
21
22
23
24
25
26

    /**
     * @var ActivationFunction
     */
    protected $activationFunction;

    /**
     * @var float
     */
27
    protected $output = 0.0;
28

29
30
31
32
33
    /**
     * @var float
     */
    protected $z = 0.0;

Tomáš Votruba's avatar
Tomáš Votruba committed
34
    public function __construct(?ActivationFunction $activationFunction = null)
35
    {
36
        $this->activationFunction = $activationFunction ?: new Sigmoid();
37
38
    }

Tomáš Votruba's avatar
Tomáš Votruba committed
39
    public function addSynapse(Synapse $synapse): void
40
41
42
43
44
45
46
    {
        $this->synapses[] = $synapse;
    }

    /**
     * @return Synapse[]
     */
47
    public function getSynapses(): array
48
49
50
51
    {
        return $this->synapses;
    }

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
64
65
        }

        return $this->output;
    }

66
67
68
69
70
    public function getDerivative(): float
    {
        return $this->activationFunction->differentiate($this->z, $this->output);
    }

Tomáš Votruba's avatar
Tomáš Votruba committed
71
    public function reset(): void
72
    {
73
        $this->output = 0.0;
74
        $this->z = 0.0;
75
    }
76
}