Passed
Push — master ( 9938cf...e83f7b )
by Arkadiusz
05:59
created

Neuron::getDerivative()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 0
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()
48
    {
49
        return $this->synapses;
50
    }
51
52
    public function getOutput(): float
53
    {
54
        if ($this->output === 0.0) {
55
            $this->z = 0;
0 ignored issues
show
Documentation Bug introduced by David Monllao
The property $z was declared of type double, but 0 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
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
}
77