MonoLayer Perceptron
This commit is contained in:
76
app/Models/Perceptrons/NetworkPerceptron.php
Normal file
76
app/Models/Perceptrons/NetworkPerceptron.php
Normal file
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Models\Perceptrons;
|
||||
|
||||
class NetworkPerceptron extends Perceptron
|
||||
{
|
||||
public array $network = [];
|
||||
|
||||
public function __construct(
|
||||
private array $synaptic_weights,
|
||||
private int $inputLayerNeuronsCount,
|
||||
private string $hiddenLayerNeuronClass,
|
||||
private string $outputLayerNeuronClass,
|
||||
) {
|
||||
parent::__construct($synaptic_weights);
|
||||
$this->initializeNetwork($synaptic_weights);
|
||||
}
|
||||
|
||||
private function initializeNetwork(array $synaptic_weights): void
|
||||
{
|
||||
// Input Layer
|
||||
$this->network[0] = [];
|
||||
foreach (range(0, $this->inputLayerNeuronsCount - 1) as $i) {
|
||||
$this->network[0][] = new InputNeuron();
|
||||
}
|
||||
|
||||
// Hidden Layer
|
||||
for ($layerIndex = 0; $layerIndex < count($synaptic_weights) - 2; $layerIndex++) {
|
||||
$this->network[$layerIndex + 1] = [];
|
||||
|
||||
foreach ($synaptic_weights[$layerIndex] as $neuronWeights) {
|
||||
$this->network[$layerIndex + 1][] = new $this->hiddenLayerNeuronClass($neuronWeights);
|
||||
}
|
||||
}
|
||||
|
||||
// Output Layer
|
||||
$outputLayer = $synaptic_weights[count($synaptic_weights) - 1];
|
||||
$this->network[count($synaptic_weights)] = [];
|
||||
|
||||
foreach ($outputLayer as $neuronWeights) {
|
||||
$this->network[count($synaptic_weights)][] = new $this->outputLayerNeuronClass($neuronWeights);
|
||||
}
|
||||
}
|
||||
|
||||
public function test(array $inputs): array
|
||||
{
|
||||
// Set the inputs for the input layer
|
||||
foreach ($this->network[0] as $index => $inputNeuron) {
|
||||
$inputNeuron->setInput($inputs[$index]);
|
||||
}
|
||||
|
||||
// Pass through the hidden and output layers
|
||||
$output = [];
|
||||
for ($layerIndex = 0; $layerIndex < count($this->network); $layerIndex++) {
|
||||
$lastLayerOutput = $output;
|
||||
$output = [];
|
||||
foreach ($this->network[$layerIndex] as $neuron) {
|
||||
$output[] = $neuron->test($lastLayerOutput)[0];
|
||||
}
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
public function activationFunction(float $weighted_sum): float
|
||||
{
|
||||
return $weighted_sum;
|
||||
}
|
||||
|
||||
public function setSynapticWeights(array $synaptic_weights): void
|
||||
{
|
||||
parent::setSynapticWeights($synaptic_weights);
|
||||
$this->network = [];
|
||||
$this->initializeNetwork($synaptic_weights);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user