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;
|
2016-08-10 20:43:47 +00:00
|
|
|
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
|
|
|
|
|
|
|
/**
|
2016-08-07 21:41:02 +00:00
|
|
|
* @param Layer $layer
|
|
|
|
*/
|
|
|
|
public function addLayer(Layer $layer)
|
|
|
|
{
|
|
|
|
$this->layers[] = $layer;
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @return Layer[]
|
2016-08-05 14:12:39 +00:00
|
|
|
*/
|
|
|
|
public function getLayers(): array
|
|
|
|
{
|
2016-08-07 21:41:02 +00:00
|
|
|
return $this->layers;
|
|
|
|
}
|
2016-08-05 14:12:39 +00:00
|
|
|
|
2017-05-23 07:03:05 +00:00
|
|
|
/**
|
|
|
|
* @return void
|
|
|
|
*/
|
|
|
|
public function removeLayers()
|
|
|
|
{
|
|
|
|
unset($this->layers);
|
|
|
|
}
|
|
|
|
|
2016-08-07 21:41:02 +00:00
|
|
|
/**
|
|
|
|
* @return Layer
|
|
|
|
*/
|
|
|
|
public function getOutputLayer(): Layer
|
|
|
|
{
|
|
|
|
return $this->layers[count($this->layers) - 1];
|
2016-08-05 14:12:39 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
2016-08-07 21:41:02 +00:00
|
|
|
* @return array
|
2016-08-05 14:12:39 +00:00
|
|
|
*/
|
2016-08-07 21:41:02 +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
|
2016-08-10 20:43:47 +00:00
|
|
|
*
|
|
|
|
* @return $this
|
2016-08-05 14:12:39 +00:00
|
|
|
*/
|
|
|
|
public function setInput($input)
|
|
|
|
{
|
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) {
|
2016-08-10 20:43:47 +00:00
|
|
|
if ($neuron instanceof Input) {
|
|
|
|
$neuron->setInput($input[$key]);
|
|
|
|
}
|
2016-08-07 21:41:02 +00:00
|
|
|
}
|
2016-08-10 20:43:47 +00:00
|
|
|
|
|
|
|
foreach ($this->getLayers() as $layer) {
|
|
|
|
foreach ($layer->getNodes() as $node) {
|
|
|
|
if ($node instanceof Neuron) {
|
2017-05-17 22:07:14 +00:00
|
|
|
$node->reset();
|
2016-08-10 20:43:47 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return $this;
|
2016-08-05 14:12:39 +00:00
|
|
|
}
|
|
|
|
}
|