Passed
Push — master ( 3dff40...de5049 )
by Arkadiusz
03:58
created

LayeredNetwork   A

Complexity

Total Complexity 12

Size/Duplication

Total Lines 78
Duplicated Lines 0 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
wmc 12
lcom 1
cbo 4
dl 0
loc 78
rs 10
c 0
b 0
f 0

6 Methods

Rating   Name   Duplication   Size   Complexity  
A addLayer() 0 4 1
A getLayers() 0 4 1
A removeLayers() 0 4 1
A getOutputLayer() 0 4 1
A getOutput() 0 9 2
B setInput() 0 20 6
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 void
37
     */
38
    public function removeLayers()
39
    {
40
        unset($this->layers);
41
    }
42
43
    /**
44
     * @return Layer
45
     */
46
    public function getOutputLayer(): Layer
47
    {
48
        return $this->layers[count($this->layers) - 1];
49
    }
50
51
    /**
52
     * @return array
53
     */
54
    public function getOutput(): array
55
    {
56
        $result = [];
57
        foreach ($this->getOutputLayer()->getNodes() as $neuron) {
58
            $result[] = $neuron->getOutput();
59
        }
60
61
        return $result;
62
    }
63
64
    /**
65
     * @param mixed $input
66
     *
67
     * @return $this
68
     */
69
    public function setInput($input)
70
    {
71
        $firstLayer = $this->layers[0];
72
73
        foreach ($firstLayer->getNodes() as $key => $neuron) {
74
            if ($neuron instanceof Input) {
75
                $neuron->setInput($input[$key]);
76
            }
77
        }
78
79
        foreach ($this->getLayers() as $layer) {
80
            foreach ($layer->getNodes() as $node) {
81
                if ($node instanceof Neuron) {
82
                    $node->reset();
83
                }
84
            }
85
        }
86
87
        return $this;
88
    }
89
}
90