1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Phpml\NeuralNetwork\Node; |
6
|
|
|
|
7
|
|
|
use Phpml\Exception\InvalidArgumentException; |
8
|
|
|
use Phpml\NeuralNetwork\ActivationFunction; |
9
|
|
|
use Phpml\NeuralNetwork\ActivationFunction\Sigmoid; |
10
|
|
|
use Phpml\NeuralNetwork\Node; |
11
|
|
|
use Phpml\NeuralNetwork\Node\Neuron\Synapse; |
12
|
|
|
|
13
|
|
|
class Neuron implements Node |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var Synapse[] |
17
|
|
|
*/ |
18
|
|
|
protected $synapses = []; |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* @var ActivationFunction |
22
|
|
|
*/ |
23
|
|
|
protected $activationFunction; |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @var float |
27
|
|
|
*/ |
28
|
|
|
protected $output = 0.0; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var float |
32
|
|
|
*/ |
33
|
|
|
protected $z = 0.0; |
34
|
|
|
|
35
|
|
|
public function __construct(?ActivationFunction $activationFunction = null) |
36
|
|
|
{ |
37
|
|
|
$this->activationFunction = $activationFunction ?: new Sigmoid(); |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
public function addSynapse(Synapse $synapse): void |
41
|
|
|
{ |
42
|
|
|
$this->synapses[] = $synapse; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* @return Synapse[] |
47
|
|
|
*/ |
48
|
|
|
public function getSynapses(): array |
49
|
|
|
{ |
50
|
|
|
return $this->synapses; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
public function getOutput(): float |
54
|
|
|
{ |
55
|
|
|
if ($this->output === 0.0) { |
|
|
|
|
56
|
|
|
$this->z = 0; |
57
|
|
|
foreach ($this->synapses as $synapse) { |
58
|
|
|
$this->z += $synapse->getOutput(); |
59
|
|
|
} |
60
|
|
|
|
61
|
|
|
$this->output = $this->activationFunction->compute($this->z); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
return $this->output; |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
public function getDerivative(): float |
68
|
|
|
{ |
69
|
|
|
return $this->activationFunction->differentiate($this->z, $this->output); |
70
|
|
|
} |
71
|
|
|
|
72
|
|
|
public function reset(): void |
73
|
|
|
{ |
74
|
|
|
$this->output = 0.0; |
75
|
|
|
$this->z = 0.0; |
76
|
|
|
} |
77
|
|
|
|
78
|
|
|
public function getTrainedCharacteristics(): array |
79
|
|
|
{ |
80
|
|
|
$result = []; |
81
|
|
|
foreach ($this->synapses as $synapse) { |
82
|
|
|
$result[] = $synapse->getWeight(); |
83
|
|
|
} |
84
|
|
|
|
85
|
|
|
return $result; |
86
|
|
|
} |
87
|
|
|
|
88
|
|
|
public function setTrainedCharacteristics(array $characteristics): void |
89
|
|
|
{ |
90
|
|
|
// length of weights should equals number of synapses |
91
|
|
|
if (count($characteristics) != count($this->synapses)) { |
92
|
|
|
throw new InvalidArgumentException('Loaded weights should match the neuron structure'); |
93
|
|
|
} |
94
|
|
|
|
95
|
|
|
for ($i = 0; $i < count($characteristics); $i++) { |
|
|
|
|
96
|
|
|
$this->synapses[$i]->setWeight($characteristics[$i]); |
97
|
|
|
} |
98
|
|
|
} |
99
|
|
|
} |
100
|
|
|
|