1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Phpml\NeuralNetwork; |
6
|
|
|
|
7
|
|
|
use Phpml\Exception\BadNeuralNetworkStructureException; |
8
|
|
|
use Phpml\Exception\InvalidArgumentException; |
9
|
|
|
use Phpml\NeuralNetwork\Node\Neuron; |
10
|
|
|
|
11
|
|
|
class Layer |
12
|
|
|
{ |
13
|
|
|
/** |
14
|
|
|
* @var Node[] |
15
|
|
|
*/ |
16
|
|
|
private $nodes = []; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @throws InvalidArgumentException |
20
|
|
|
*/ |
21
|
|
|
public function __construct(int $nodesNumber = 0, string $nodeClass = Neuron::class, ?ActivationFunction $activationFunction = null) |
22
|
|
|
{ |
23
|
|
|
if (!in_array(Node::class, class_implements($nodeClass), true)) { |
24
|
|
|
throw new InvalidArgumentException('Layer node class must implement Node interface'); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
for ($i = 0; $i < $nodesNumber; ++$i) { |
28
|
|
|
$this->nodes[] = $this->createNode($nodeClass, $activationFunction); |
29
|
|
|
} |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function addNode(Node $node): void |
33
|
|
|
{ |
34
|
|
|
$this->nodes[] = $node; |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* @return Node[] |
39
|
|
|
*/ |
40
|
|
|
public function getNodes(): array |
41
|
|
|
{ |
42
|
|
|
return $this->nodes; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
public function getTrainedCharacteristics(): array |
46
|
|
|
{ |
47
|
|
|
$result = []; |
48
|
|
|
foreach ($this->nodes as $node) { |
49
|
|
|
if ($node instanceof Neuron) { |
50
|
|
|
$result[] = $node->getTrainedCharacteristics(); |
51
|
|
|
} |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
return $result; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
public function setTrainedCharacteristics(array $characteristics): void |
58
|
|
|
{ |
59
|
|
|
// iterate over the node instances |
60
|
|
|
$iNode = -1; |
61
|
|
|
for ($i = 0; $i < count($this->nodes); $i++) { |
|
|
|
|
62
|
|
|
$node = $this->nodes[$i]; |
63
|
|
|
if ($node instanceof Neuron) { |
64
|
|
|
$iNode ++; |
65
|
|
|
|
66
|
|
|
if (count($characteristics) < $iNode + 1) { |
67
|
|
|
throw new BadNeuralNetworkStructureException(); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
$node->setTrainedCharacteristics($characteristics[$iNode]); |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
75
|
|
|
private function createNode(string $nodeClass, ?ActivationFunction $activationFunction = null): Node |
76
|
|
|
{ |
77
|
|
|
if ($nodeClass === Neuron::class) { |
78
|
|
|
return new Neuron($activationFunction); |
79
|
|
|
} |
80
|
|
|
|
81
|
|
|
return new $nodeClass(); |
82
|
|
|
} |
83
|
|
|
} |
84
|
|
|
|
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: