Completed
Push — develop ( e5d39e...c506a8 )
by Arkadiusz
03:32
created

LayeredNetwork::addLayer()   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
c 0
b 0
f 0
rs 10
cc 1
eloc 2
nc 1
nop 1
1
<?php
2
3
declare (strict_types = 1);
4
5
namespace Phpml\NeuralNetwork\Network;
6
7
use Phpml\NeuralNetwork\Layer;
8
use Phpml\NeuralNetwork\Network;
9
use Phpml\NeuralNetwork\Node\Input;
10
use Phpml\NeuralNetwork\Node\Neuron;
11
12
abstract class LayeredNetwork implements Network
13
{
14
    /**
15
     * @var Layer[]
16
     */
17
    protected $layers;
18
19
    /**
20
     * @param Layer $layer
21
     */
22
    public function addLayer(Layer $layer)
23
    {
24
        $this->layers[] = $layer;
25
    }
26
27
    /**
28
     * @return Layer[]
29
     */
30
    public function getLayers(): array
31
    {
32
        return $this->layers;
33
    }
34
35
    /**
36
     * @return Layer
37
     */
38
    public function getOutputLayer(): Layer
39
    {
40
        return $this->layers[count($this->layers) - 1];
41
    }
42
43
    /**
44
     * @return array
45
     */
46
    public function getOutput(): array
47
    {
48
        $result = [];
49
        foreach ($this->getOutputLayer()->getNodes() as $neuron) {
50
            $result[] = $neuron->getOutput();
51
        }
52
53
        return $result;
54
    }
55
56
    /**
57
     * @param mixed $input
58
     *
59
     * @return $this
60
     */
61
    public function setInput($input)
62
    {
63
        $firstLayer = $this->layers[0];
64
65
        foreach ($firstLayer->getNodes() as $key => $neuron) {
66
            if ($neuron instanceof Input) {
67
                $neuron->setInput($input[$key]);
68
            }
69
        }
70
71
        foreach ($this->getLayers() as $layer) {
72
            foreach ($layer->getNodes() as $node) {
73
                if ($node instanceof Neuron) {
74
                    $node->refresh();
75
                }
76
            }
77
        }
78
79
        return $this;
80
    }
81
}
82