Files
perceptron-viewer/app/Services/IterationEventBuffer/PerceptronIterationEventBuffer.php
T
Ninluc 08aa04fe56
linter / quality (push) Successful in 7m10s
tests / ci (8.4) (push) Successful in 4m43s
tests / ci (8.5) (push) Successful in 4m47s
Multilayer neuron network
2026-09-08 16:29:02 +02:00

62 lines
2.0 KiB
PHP

<?php
namespace App\Services\IterationEventBuffer;
class PerceptronIterationEventBuffer implements IPerceptronIterationEventBuffer
{
private $data;
private int $nextSizeIncreaseThreshold;
private int $underSizeIncreaseCount = 0;
public function __construct(
private string $sessionId,
private string $trainingId,
private int $sizeIncreaseStart = 10,
private int $sizeIncreaseFactor = 2,
) {
$this->data = [];
$this->nextSizeIncreaseThreshold = $sizeIncreaseStart;
}
public function flush(): void
{
event(new \App\Events\PerceptronTrainingIteration($this->data, $this->sessionId, $this->trainingId));
$this->data = [];
}
public function addIteration(int $epoch, int $exampleIndex, float $error, array $synaptic_weights): void
{
$iteration = [
'epoch' => $epoch,
'exampleIndex' => $exampleIndex,
'error' => $error,
'weights' => $synaptic_weights,
];
$payload = [
'iterations' => [...$this->data, $iteration],
'trainingId' => $this->trainingId,
];
if ($this->data !== [] && strlen(json_encode($payload, JSON_THROW_ON_ERROR)) > config('broadcasting.broadcast_max_payload_size')) {
$this->flush();
}
$this->data[] = $iteration;
if ($this->underSizeIncreaseCount <= $this->sizeIncreaseStart) { // We can still send a single date because we are under the increase start threshold
$this->underSizeIncreaseCount++;
$this->flush();
} elseif (count($this->data) >= $this->nextSizeIncreaseThreshold) {
$this->flush();
$this->nextSizeIncreaseThreshold *= $this->sizeIncreaseFactor;
if ($this->nextSizeIncreaseThreshold > config('perceptron.broadcast_iteration_size')) {
$this->nextSizeIncreaseThreshold = config('perceptron.broadcast_iteration_size'); // Cap the threshold to the maximum size
}
}
}
}