php-ml/src/NeuralNetwork/Network/LayeredNetwork.php

76 lines
1.5 KiB
PHP
Raw Normal View History

2016-08-05 14:12:39 +00:00
<?php
2016-11-20 21:53:17 +00:00
declare(strict_types=1);
2016-08-05 14:12:39 +00:00
namespace Phpml\NeuralNetwork\Network;
2016-08-07 21:41:02 +00:00
use Phpml\NeuralNetwork\Layer;
2016-08-05 14:12:39 +00:00
use Phpml\NeuralNetwork\Network;
use Phpml\NeuralNetwork\Node\Input;
use Phpml\NeuralNetwork\Node\Neuron;
2016-08-05 14:12:39 +00:00
abstract class LayeredNetwork implements Network
{
2016-08-07 21:41:02 +00:00
/**
* @var Layer[]
*/
protected $layers = [];
2016-08-05 14:12:39 +00:00
public function addLayer(Layer $layer): void
2016-08-07 21:41:02 +00:00
{
$this->layers[] = $layer;
}
/**
* @return Layer[]
2016-08-05 14:12:39 +00:00
*/
public function getLayers(): array
2016-08-05 14:12:39 +00:00
{
2016-08-07 21:41:02 +00:00
return $this->layers;
}
2016-08-05 14:12:39 +00:00
public function removeLayers(): void
{
unset($this->layers);
}
2016-08-07 21:41:02 +00:00
public function getOutputLayer(): Layer
{
return $this->layers[count($this->layers) - 1];
2016-08-05 14:12:39 +00:00
}
public function getOutput(): array
2016-08-05 14:12:39 +00:00
{
2016-08-07 21:41:02 +00:00
$result = [];
foreach ($this->getOutputLayer()->getNodes() as $neuron) {
$result[] = $neuron->getOutput();
}
2016-08-05 14:12:39 +00:00
2016-08-07 21:41:02 +00:00
return $result;
2016-08-05 14:12:39 +00:00
}
/**
* @param mixed $input
*/
public function setInput($input): Network
2016-08-05 14:12:39 +00:00
{
2016-08-07 21:41:02 +00:00
$firstLayer = $this->layers[0];
2016-08-05 14:12:39 +00:00
2016-08-07 21:41:02 +00:00
foreach ($firstLayer->getNodes() as $key => $neuron) {
if ($neuron instanceof Input) {
$neuron->setInput($input[$key]);
}
2016-08-07 21:41:02 +00:00
}
foreach ($this->getLayers() as $layer) {
foreach ($layer->getNodes() as $node) {
if ($node instanceof Neuron) {
$node->reset();
}
}
}
return $this;
2016-08-05 14:12:39 +00:00
}
}