1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Phpml\NeuralNetwork\Network; |
6
|
|
|
|
7
|
|
|
use Phpml\Exception\InvalidArgumentException; |
8
|
|
|
use Phpml\NeuralNetwork\Layer; |
9
|
|
|
use Phpml\NeuralNetwork\Network; |
10
|
|
|
use Phpml\NeuralNetwork\Node\Input; |
11
|
|
|
use Phpml\NeuralNetwork\Node\Neuron; |
12
|
|
|
|
13
|
|
|
abstract class LayeredNetwork implements Network |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* @var Layer[] |
17
|
|
|
*/ |
18
|
|
|
protected $layers = []; |
19
|
|
|
|
20
|
|
|
public function addLayer(Layer $layer): void |
21
|
|
|
{ |
22
|
|
|
$this->layers[] = $layer; |
23
|
|
|
} |
24
|
|
|
|
25
|
|
|
/** |
26
|
|
|
* @return Layer[] |
27
|
|
|
*/ |
28
|
|
|
public function getLayers(): array |
29
|
|
|
{ |
30
|
|
|
return $this->layers; |
31
|
|
|
} |
32
|
|
|
|
33
|
|
|
public function removeLayers(): void |
34
|
|
|
{ |
35
|
|
|
unset($this->layers); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function getOutputLayer(): Layer |
39
|
|
|
{ |
40
|
|
|
return $this->layers[count($this->layers) - 1]; |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
public function getOutput(): array |
44
|
|
|
{ |
45
|
|
|
$result = []; |
46
|
|
|
foreach ($this->getOutputLayer()->getNodes() as $neuron) { |
47
|
|
|
$result[] = $neuron->getOutput(); |
48
|
|
|
} |
49
|
|
|
|
50
|
|
|
return $result; |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
/** |
54
|
|
|
* @param mixed $input |
55
|
|
|
*/ |
56
|
|
|
public function setInput($input): Network |
57
|
|
|
{ |
58
|
|
|
$firstLayer = $this->layers[0]; |
59
|
|
|
|
60
|
|
|
foreach ($firstLayer->getNodes() as $key => $neuron) { |
61
|
|
|
if ($neuron instanceof Input) { |
62
|
|
|
$neuron->setInput($input[$key]); |
63
|
|
|
} |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
foreach ($this->getLayers() as $layer) { |
67
|
|
|
foreach ($layer->getNodes() as $node) { |
68
|
|
|
if ($node instanceof Neuron) { |
69
|
|
|
$node->reset(); |
70
|
|
|
} |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|
74
|
|
|
return $this; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
public function getTrainedCharacteristics(): array |
78
|
|
|
{ |
79
|
|
|
$result = []; |
80
|
|
|
foreach ($this->layers as $layer) { |
81
|
|
|
$result[] = $layer->getTrainedCharacteristics(); |
82
|
|
|
} |
83
|
|
|
|
84
|
|
|
return $result; |
85
|
|
|
} |
86
|
|
|
|
87
|
|
|
public function setTrainedCharacteristics(array $characteristics): void |
88
|
|
|
{ |
89
|
|
|
if (count($characteristics) != count($this->layers)) { |
90
|
|
|
throw new InvalidArgumentException('Loaded data does not match the network structure'); |
91
|
|
|
} |
92
|
|
|
|
93
|
|
|
for ($i = 0; $i < count($this->layers); $i++) { |
|
|
|
|
94
|
|
|
$this->layers[$i]->setTrainedCharacteristics($characteristics[$i]); |
95
|
|
|
} |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|
If the size of the collection does not change during the iteration, it is generally a good practice to compute it beforehand, and not on each iteration: