Files
Reseaux-de-neurones-artific…/app/Models/SimpleBinaryPerceptronTraining.php
Matthias Guillitte a70b7670e7
Some checks failed
linter / quality (push) Failing after 7s
tests / ci (8.4) (push) Failing after 4s
tests / ci (8.5) (push) Failing after 4s
Use correct naming for iteration and epoch
2026-03-21 09:46:35 +01:00

85 lines
3.1 KiB
PHP

<?php
namespace App\Models;
use App\Events\PerceptronTrainingEnded;
use App\Services\DataSetReader;
use App\Services\IPerceptronIterationEventBuffer;
use App\Services\ISynapticWeightsProvider;
class SimpleBinaryPerceptronTraining extends NetworkTraining
{
private Perceptron $perceptron;
private int $iterationErrorCounter = 0;
public ActivationsFunctions $activationFunction = ActivationsFunctions::STEP;
public const MIN_ERROR = 0;
public function __construct(
DataSetReader $datasetReader,
protected float $learningRate,
int $maxEpochs,
protected ISynapticWeightsProvider $synapticWeightsProvider,
IPerceptronIterationEventBuffer $iterationEventBuffer,
string $sessionId,
string $trainingId,
) {
parent::__construct($datasetReader, $maxEpochs, $iterationEventBuffer, $sessionId, $trainingId);
$this->perceptron = new SimpleBinaryPerceptron($synapticWeightsProvider->generate($datasetReader->getInputSize()));
}
public function start(): void
{
$this->epoch = 0;
$error = 0;
do {
$this->iterationErrorCounter = 0;
$this->epoch++;
while ($nextRow = $this->datasetReader->getNextLine()) {
$inputs = array_slice($nextRow, 0, -1);
$correctOutput = (float) end($nextRow);
$correctOutput = $correctOutput > 0 ? 1 : 0; // Modify labels for non binary datasets
$error = $this->iterationFunction($inputs, $correctOutput);
// Broadcast the training iteration event
$this->addIterationToBuffer($error, [[$this->perceptron->getSynapticWeights()]]);
}
$this->datasetReader->reset(); // Reset the dataset for the next iteration
} while ($this->epoch < $this->maxEpochs && !$this->stopCondition());
$this->iterationEventBuffer->flush(); // Ensure all iterations are sent to the frontend
$this->checkPassedMaxIterations(null);
}
protected function stopCondition(): bool
{
$condition = $this->iterationErrorCounter == 0;
if ($condition === true) {
event(new PerceptronTrainingEnded('Le perceptron ne commet plus d\'erreurs sur aucune des données', $this->sessionId, $this->trainingId));
}
return $this->iterationErrorCounter == 0;
}
private function iterationFunction(array $inputs, int $correctOutput)
{
$output = $this->perceptron->test($inputs);
$error = $correctOutput - $output;
if (abs($error) > $this::MIN_ERROR) {
$this->iterationErrorCounter++;
}
if ($error !== 0) { // Update synaptic weights if needed
$synaptic_weights = $this->perceptron->getSynapticWeights();
$inputs_with_bias = array_merge([1], $inputs); // Add bias input
$new_weights = array_map(fn($weight, $input) => $weight + $this->learningRate * $error * $input, $synaptic_weights, $inputs_with_bias);
$this->perceptron->setSynapticWeights($new_weights);
}
return $error;
}
}