From c5e777463760b54496e1697dbc257e4c770037ce Mon Sep 17 00:00:00 2001 From: rsgrinko Date: Wed, 29 Mar 2023 22:41:18 +0300 Subject: [PATCH] Initial commit --- README.md | 3 +- bootstrap.php | 4 + lib/NeuroNetwork.class.php | 205 +++++++++++++++++++++++++++++++++++++ lib/Neuron.class.php | 36 +++++++ lib/Synaps.class.php | 94 +++++++++++++++++ storage/README.md | 1 + test.php | 17 +++ 7 files changed, 359 insertions(+), 1 deletion(-) create mode 100644 bootstrap.php create mode 100644 lib/NeuroNetwork.class.php create mode 100644 lib/Neuron.class.php create mode 100644 lib/Synaps.class.php create mode 100644 storage/README.md create mode 100644 test.php diff --git a/README.md b/README.md index 6b6d774..de2f3f9 100644 --- a/README.md +++ b/README.md @@ -1 +1,2 @@ -# php_ai \ No newline at end of file +# PHP AI - Нейросеть на PHP +Пример реализации простой нейросети на PHP diff --git a/bootstrap.php b/bootstrap.php new file mode 100644 index 0000000..9c2e3dd --- /dev/null +++ b/bootstrap.php @@ -0,0 +1,4 @@ +storageFile = $_SERVER['DOCUMENT_ROOT'] . '/neuroSynaps.json'; + } else { + $this->storageFile = $storageFile; + } + + // Слои нейросети + $this->layers = [ + [new Neuron(1), new Neuron(2)], + [new Neuron(3), new Neuron(4), new Neuron(5), new Neuron(6)], + [new Neuron(7)], + ]; + + + /** Строим связи нейронов */ + $this->generateSynapses(); + /*$this->synaps = [ + new Synaps($this->layers[0][0], $this->layers[1][0]), + new Synaps($this->layers[0][0], $this->layers[1][1]), + new Synaps($this->layers[0][0], $this->layers[1][2]), + new Synaps($this->layers[0][0], $this->layers[1][3]), + new Synaps($this->layers[0][1], $this->layers[1][0]), + new Synaps($this->layers[0][1], $this->layers[1][1]), + new Synaps($this->layers[0][1], $this->layers[1][2]), + new Synaps($this->layers[0][1], $this->layers[1][3]), + new Synaps($this->layers[1][0], $this->layers[2][0]), + new Synaps($this->layers[1][0], $this->layers[2][1]), + new Synaps($this->layers[1][1], $this->layers[2][0]), + new Synaps($this->layers[1][1], $this->layers[2][1]), + new Synaps($this->layers[1][2], $this->layers[2][0]), + new Synaps($this->layers[1][2], $this->layers[2][1]), + new Synaps($this->layers[1][3], $this->layers[2][0]), + new Synaps($this->layers[1][3], $this->layers[2][1]), + ];*/ + + // Получение сохраненных данных по весам + $this->getSynapsValue(); + } + + /** + * Генерируем связи между нейронами + */ + private function generateSynapses(): void + { + $synapsId = 1; + $layersCount = count($this->layers); + + // Бежим по слоям нейронов (последний нам не нужен) и строим связи + for ($i = 0; $i < $layersCount - 1; $i++) { + $neuronCount = count($this->layers[$i + 1]); + for ($j = 0; $j < $neuronCount; $j++) { + $neuronInCount = count($this->layers[$i]); + for ($k = 0; $k < $neuronInCount; $k++) { + $this->synapses[] = new Synaps( + $synapsId, $this->layers[$i][$k], $this->layers[$i + 1][$j], $this->arValues[$synapsId] ?? null + ); + $synapsId++; + } + } + } + } + + /** + * Сохранить значения весов синапсов в файл + * + * @param bool $forceUpdate Принудительно перезаписать + */ + private function saveSynapsValue(bool $forceUpdate= false): void + { + $data = []; + foreach ($this->synapses as $synapse) { + /** @var Synaps $synapse */ + $data[$synapse->getId()] = $synapse->getValue(); + } + + if ($forceUpdate || !file_exists($this->storageFile)) { + file_put_contents($this->storageFile, json_encode($data, JSON_UNESCAPED_UNICODE)); + } + } + + /** + * Получить значения весов синапсов из файла + * + * @return array Сохраненный раннее массив весов + */ + private function getSynapsValue(): array + { + if (!file_exists($this->storageFile)) { + return []; + } + + // Получаем массив весов + $synapsValues = json_decode(file_get_contents($this->storageFile), true); + + // Устанавливаем веса для синапсов + foreach ($this->synapses as $synapse) { + /** @var Synaps $synapse */ + $synapse->setValue($synapsValues[$synapse->getId()]); + } + + $this->arValues = $synapsValues; + + // Возвращаем веса + return $synapsValues; + } + + /** + * Мутация веса + * + * @param float|null $shift Величина сдвига для мутации + * + * @throws \Exception + */ + public function mutate(?float $shift = 0.1): self + { + foreach ($this->synapses as $synapse) { + /** @var Synaps $synapse */ + $tempValue = random_int((int)(($synapse->getValue() - $shift) * 100), (int)(($synapse->getValue() + $shift) * 100)) / 100; + + // Ограничиваемся диапазоном 0..1 + if ($tempValue < 0) { + $tempValue = 0; + } + if ($tempValue > 1) { + $tempValue = 1; + } + + $synapse->setValue($tempValue); + } + + $this->saveSynapsValue(true); + return $this; + } + + /** + * Запуск обработки + */ + public function run(array $arValue): array + { + foreach ($arValue as $key => $value) { + $this->layers[0][$key]->setValue($value); + } + foreach ($this->synapses as $synapse) { + $this->step($synapse); + } + + $result = []; + // Отдаем значения нейронов последнего слоя как результат + foreach ($this->layers[2] as $neuron) { + $result[] = $neuron->getValue(); + } + $this->saveSynapsValue(); + return $result; + //return [$this->layers[2][0]->getValue(), $this->layers[2][1]->getValue()]; + } + + + /** + * Шаг преобразования значений между нейронами + */ + public function step(Synaps $synaps): void + { + /* + // Умножение значения на коэфициент + $synaps->getOutNeuron()->setValue( + $synaps->getInNeuron()->getValue() * $synaps->getValue() + );*/ + + // Гиперболический тангенс + // https://otus.ru/journal/kak-sozdat-nejroset/ + // Функция активации + $synaps->getOutNeuron()->setValue( + tanh($synaps->getInNeuron()->getValue() * $synaps->getValue()) + ); + } + } \ No newline at end of file diff --git a/lib/Neuron.class.php b/lib/Neuron.class.php new file mode 100644 index 0000000..af9b27e --- /dev/null +++ b/lib/Neuron.class.php @@ -0,0 +1,36 @@ +id = $id; + } + + /** Получить текущее значение */ + public function getValue(): ?float + { + return $this->value; + } + + /** Задать текущее значение */ + public function setValue(float $value): self + { + $this->value = $value; + return $this; + } + } diff --git a/lib/Synaps.class.php b/lib/Synaps.class.php new file mode 100644 index 0000000..7134add --- /dev/null +++ b/lib/Synaps.class.php @@ -0,0 +1,94 @@ +inNeuron = $inNeuron; + $this->outNeuron = $outNeuron; + + // если мы хотим явно задать вес - задаем, иначе генерируем как-нибудь + if ($value !== null) { + $this->value = $value; + } else { + $this->value = random_int(0, 100) / 100; + } + $this->id = $id; + } + + /** Получить id синапса */ + public function getId(): int + { + return $this->id; + } + + /** + * Получение входящего нейрона + * + * @return Neuron + */ + public function getInNeuron(): Neuron + { + return $this->inNeuron; + } + + /** + * Получение выходящего нейрона + * + * @return Neuron + */ + public function getOutNeuron(): Neuron + { + return $this->outNeuron; + } + + + /** + * Получить вес + * + * @return float Вес + */ + public function getValue(): ?float + { + return $this->value; + } + + + /** + * Установить вес + * + * @param float $value Вес + * @return $this + */ + public function setValue(float $value): self + { + $this->value = $value; + return $this; + } + + } diff --git a/storage/README.md b/storage/README.md new file mode 100644 index 0000000..85f754e --- /dev/null +++ b/storage/README.md @@ -0,0 +1 @@ +Тут хранилище весов \ No newline at end of file diff --git a/test.php b/test.php new file mode 100644 index 0000000..1ad4e3d --- /dev/null +++ b/test.php @@ -0,0 +1,17 @@ +run([1, 1]); + print_r($res); + + $ob->mutate(); + $res = $ob->run([1, 1]); + print_r($res); + + +