LayeredNetwork.php 1.5 KB
Newer Older
1
2
<?php

Arkadiusz Kondas's avatar
Arkadiusz Kondas committed
3
declare(strict_types=1);
4
5
6

namespace Phpml\NeuralNetwork\Network;

7
use Phpml\NeuralNetwork\Layer;
8
use Phpml\NeuralNetwork\Network;
9
10
use Phpml\NeuralNetwork\Node\Input;
use Phpml\NeuralNetwork\Node\Neuron;
11
12
13

abstract class LayeredNetwork implements Network
{
14
15
16
    /**
     * @var Layer[]
     */
17
    protected $layers = [];
18

Tomáš Votruba's avatar
Tomáš Votruba committed
19
    public function addLayer(Layer $layer): void
20
21
22
23
24
25
    {
        $this->layers[] = $layer;
    }

    /**
     * @return Layer[]
26
     */
27
    public function getLayers(): array
28
    {
29
30
        return $this->layers;
    }
31

Tomáš Votruba's avatar
Tomáš Votruba committed
32
    public function removeLayers(): void
33
34
35
36
    {
        unset($this->layers);
    }

37
38
39
    public function getOutputLayer(): Layer
    {
        return $this->layers[count($this->layers) - 1];
40
41
    }

42
    public function getOutput(): array
43
    {
44
45
46
47
        $result = [];
        foreach ($this->getOutputLayer()->getNodes() as $neuron) {
            $result[] = $neuron->getOutput();
        }
48

49
        return $result;
50
51
52
53
54
    }

    /**
     * @param mixed $input
     */
55
    public function setInput($input): Network
56
    {
57
        $firstLayer = $this->layers[0];
58

59
        foreach ($firstLayer->getNodes() as $key => $neuron) {
60
61
62
            if ($neuron instanceof Input) {
                $neuron->setInput($input[$key]);
            }
63
        }
64
65
66
67

        foreach ($this->getLayers() as $layer) {
            foreach ($layer->getNodes() as $node) {
                if ($node instanceof Neuron) {
68
                    $node->reset();
69
70
71
72
73
                }
            }
        }

        return $this;
74
75
    }
}