These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more
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 | public function addLayer(Layer $layer): void |
||
20 | { |
||
21 | $this->layers[] = $layer; |
||
22 | } |
||
23 | |||
24 | /** |
||
25 | * @return Layer[] |
||
26 | */ |
||
27 | public function getLayers(): array |
||
28 | { |
||
29 | return $this->layers; |
||
30 | } |
||
31 | |||
32 | public function removeLayers(): void |
||
33 | { |
||
34 | unset($this->layers); |
||
35 | } |
||
36 | |||
37 | public function getOutputLayer(): Layer |
||
38 | { |
||
39 | return $this->layers[count($this->layers) - 1]; |
||
40 | } |
||
41 | |||
42 | public function getOutput(): array |
||
43 | { |
||
44 | $result = []; |
||
45 | foreach ($this->getOutputLayer()->getNodes() as $neuron) { |
||
46 | $result[] = $neuron->getOutput(); |
||
47 | } |
||
48 | |||
49 | return $result; |
||
50 | } |
||
51 | |||
52 | /** |
||
53 | * @param mixed $input |
||
54 | * |
||
55 | * @return $this |
||
56 | */ |
||
57 | public function setInput($input): Network |
||
58 | { |
||
59 | $firstLayer = $this->layers[0]; |
||
60 | |||
61 | foreach ($firstLayer->getNodes() as $key => $neuron) { |
||
62 | if ($neuron instanceof Input) { |
||
63 | $neuron->setInput($input[$key]); |
||
64 | } |
||
65 | } |
||
66 | |||
67 | foreach ($this->getLayers() as $layer) { |
||
68 | foreach ($layer->getNodes() as $node) { |
||
69 | if ($node instanceof Neuron) { |
||
70 | $node->reset(); |
||
71 | } |
||
72 | } |
||
73 | } |
||
74 | |||
75 | return $this; |
||
0 ignored issues
–
show
|
|||
76 | } |
||
77 | } |
||
78 |
If you return a value from a function or method, it should be a sub-type of the type that is given by the parent type f.e. an interface, or abstract method. This is more formally defined by the Lizkov substitution principle, and guarantees that classes that depend on the parent type can use any instance of a child type interchangably. This principle also belongs to the SOLID principles for object oriented design.
Let’s take a look at an example:
Our function
my_function
expects aPost
object, and outputs the author of the post. The base classPost
returns a simple string and outputting a simple string will work just fine. However, the child classBlogPost
which is a sub-type ofPost
instead decided to return anobject
, and is therefore violating the SOLID principles. If aBlogPost
were passed tomy_function
, PHP would not complain, but ultimately fail when executing thestrtoupper
call in its body.