Layer.php 1.19 KB
Newer Older
1
2
<?php

Arkadiusz Kondas's avatar
Arkadiusz Kondas committed
3
declare(strict_types=1);
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

namespace Phpml\NeuralNetwork;

use Phpml\Exception\InvalidArgumentException;
use Phpml\NeuralNetwork\Node\Neuron;

class Layer
{
    /**
     * @var Node[]
     */
    private $nodes = [];

    /**
     * @throws InvalidArgumentException
     */
Tomáš Votruba's avatar
Tomáš Votruba committed
20
    public function __construct(int $nodesNumber = 0, string $nodeClass = Neuron::class, ?ActivationFunction $activationFunction = null)
21
    {
22
        if (!in_array(Node::class, class_implements($nodeClass), true)) {
23
            throw new InvalidArgumentException('Layer node class must implement Node interface');
24
25
26
        }

        for ($i = 0; $i < $nodesNumber; ++$i) {
27
            $this->nodes[] = $this->createNode($nodeClass, $activationFunction);
28
29
30
        }
    }

Tomáš Votruba's avatar
Tomáš Votruba committed
31
    public function addNode(Node $node): void
32
33
34
35
36
37
38
    {
        $this->nodes[] = $node;
    }

    /**
     * @return Node[]
     */
39
    public function getNodes(): array
40
41
42
    {
        return $this->nodes;
    }
43
44
45

    private function createNode(string $nodeClass, ?ActivationFunction $activationFunction = null): Node
    {
46
        if ($nodeClass === Neuron::class) {
47
48
49
50
51
            return new Neuron($activationFunction);
        }

        return new $nodeClass();
    }
52
}