Passed
Push — master ( e83f7b...d953ef )
by Arkadiusz
03:28
created

src/Phpml/NeuralNetwork/Node/Neuron.php (1 issue)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

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