Completed
Push — develop ( 64859f...e5d39e )
by Arkadiusz
03:02
created

MultilayerPerceptron::addBiasNodes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 1
Metric Value
c 1
b 0
f 1
dl 0
loc 7
rs 9.4285
cc 2
eloc 4
nc 2
nop 0
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\Node\Bias;
10
use Phpml\NeuralNetwork\Node\Input;
11
use Phpml\NeuralNetwork\Node\Neuron;
12
use Phpml\NeuralNetwork\Node\Neuron\Synapse;
13
14
class MultilayerPerceptron extends LayeredNetwork
15
{
16
    /**
17
     * @param array $layers
18
     *
19
     * @throws InvalidArgumentException
20
     */
21
    public function __construct(array $layers)
22
    {
23
        if (count($layers) < 2) {
24
            throw InvalidArgumentException::invalidLayersNumber();
25
        }
26
27
        $this->addInputLayer(array_shift($layers));
28
        $this->addNeuronLayers($layers);
29
        $this->addBiasNodes();
30
        $this->generateSynapses();
31
    }
32
33
    /**
34
     * @param int $nodes
35
     */
36
    private function addInputLayer(int $nodes)
37
    {
38
        $this->addLayer(new Layer($nodes, Input::class));
39
    }
40
41
    /**
42
     * @param array $layers
43
     */
44
    private function addNeuronLayers(array $layers)
45
    {
46
        foreach ($layers as $neurons) {
47
            $this->addLayer(new Layer($neurons, Neuron::class));
48
        }
49
    }
50
51
    private function generateSynapses()
52
    {
53
        $layersNumber = count($this->layers) - 1;
54
        for ($i = 0; $i < $layersNumber; ++$i) {
55
            $currentLayer = $this->layers[$i];
56
            $nextLayer = $this->layers[$i + 1];
57
            $this->generateLayerSynapses($nextLayer, $currentLayer);
58
        }
59
    }
60
61
    private function addBiasNodes()
62
    {
63
        $biasLayers = count($this->layers) - 1;
64
        for ($i = 0;$i < $biasLayers;++$i) {
65
            $this->layers[$i]->addNode(new Bias());
66
        }
67
    }
68
69
    /**
70
     * @param Layer $nextLayer
71
     * @param Layer $currentLayer
72
     */
73
    private function generateLayerSynapses(Layer $nextLayer, Layer $currentLayer)
74
    {
75
        foreach ($nextLayer->getNodes() as $nextNeuron) {
76
            if ($nextNeuron instanceof Neuron) {
77
                $this->generateNeuronSynapses($currentLayer, $nextNeuron);
78
            }
79
        }
80
    }
81
82
    /**
83
     * @param Layer  $currentLayer
84
     * @param Neuron $nextNeuron
85
     */
86
    private function generateNeuronSynapses(Layer $currentLayer, Neuron $nextNeuron)
87
    {
88
        foreach ($currentLayer->getNodes() as $currentNeuron) {
89
            $nextNeuron->addSynapse(new Synapse($currentNeuron));
90
        }
91
    }
92
}
93