php-ml/src/NeuralNetwork/Node/Neuron.php

77 lines
1.5 KiB
PHP
Raw Normal View History

<?php
2016-11-20 21:53:17 +00:00
declare(strict_types=1);
namespace Phpml\NeuralNetwork\Node;
2016-08-02 18:30:20 +00:00
use Phpml\NeuralNetwork\ActivationFunction;
use Phpml\NeuralNetwork\ActivationFunction\Sigmoid;
2016-08-02 18:30:20 +00:00
use Phpml\NeuralNetwork\Node;
use Phpml\NeuralNetwork\Node\Neuron\Synapse;
2016-08-02 18:30:20 +00:00
class Neuron implements Node
{
2016-08-02 18:30:20 +00:00
/**
* @var Synapse[]
*/
protected $synapses = [];
2016-08-02 18:30:20 +00:00
/**
* @var ActivationFunction
*/
protected $activationFunction;
/**
* @var float
*/
protected $output = 0.0;
2016-08-02 18:30:20 +00:00
/**
* @var float
*/
protected $z = 0.0;
public function __construct(?ActivationFunction $activationFunction = null)
2016-08-02 18:30:20 +00:00
{
$this->activationFunction = $activationFunction ?? new Sigmoid();
2016-08-02 18:30:20 +00:00
}
public function addSynapse(Synapse $synapse): void
2016-08-02 18:30:20 +00:00
{
$this->synapses[] = $synapse;
}
/**
* @return Synapse[]
*/
public function getSynapses(): array
2016-08-02 18:30:20 +00:00
{
return $this->synapses;
}
public function getOutput(): float
2016-08-02 18:30:20 +00:00
{
if ($this->output === 0.0) {
$this->z = 0;
2016-08-02 18:30:20 +00:00
foreach ($this->synapses as $synapse) {
$this->z += $synapse->getOutput();
2016-08-02 18:30:20 +00:00
}
$this->output = $this->activationFunction->compute($this->z);
2016-08-02 18:30:20 +00:00
}
return $this->output;
}
public function getDerivative(): float
{
return $this->activationFunction->differentiate($this->z, $this->output);
}
public function reset(): void
2016-08-02 18:30:20 +00:00
{
$this->output = 0.0;
$this->z = 0.0;
2016-08-02 18:30:20 +00:00
}
}