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

90 lines
1.7 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
/**
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
/**
* @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
*
* @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) {
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
}
}