diff --git a/README.md b/README.md index 837a008..6f65ebd 100644 --- a/README.md +++ b/README.md @@ -2,20 +2,69 @@ Пример реализации простой нейросети на PHP Для примера класс сети реализован следующим образом: -2 нейрона входного слоя, 4 нейрона на промежуточном слое и 1 выходной нейрон. +имеется входной слой, промежуточный и выходной. Количество нейронов каждого слоя можно задать в конструкторе. Можно попытаться изобразить логический оператор И, где принимаются 2 аргумента (0 или 1) и нейросеть выдает ответ. -## Запуск +## Запуск c обучением `` $ php test.php `` ## Результат ```` -[Preset 1] Input data [1, 1], result: 0.94613955122455 -[Mutate] Mutate weights... -[Preset 2] Input data [1, 1], result: 0.99165680551829 +=> Run training... +=> Training success +=> Save Weights... +=> Weights saved +=> Testing... +=> Input: [0, 0], result: [0.00050500874055015] +=> Input: [1, 0], result: [0.0023971208568645] +=> Input: [0, 1], result: [0.0034857253613739] +=> Input: [1, 1], result: [0.99544824644645] ```` +![training](training.png) + +Если закомментировать в файле примера блок обучения, то будет следеющий результат: +```` +=> Testing... +=> Input: [0, 0], result: [0.00050500874055015] +=> Input: [1, 0], result: [0.0023971208568645] +=> Input: [0, 1], result: [0.0034857253613739] +=> Input: [1, 1], result: [0.99544824644645] +```` +![training](run.png) ## Обучение -Процесс обучения будет описан позже... +Для обучения используются датасеты с заранее известным значением результата. В данной сети используется обучение путем обратного распространения ошибки. + +## Пример обучения для имитации логического оператора И +````php +// Создаем нейросеть +$nn = new NeuralNetwork(2, 3, 1, 'storage'); + +// Обучающий датасет +$trainingSet = [ + [[0, 0], [0]], + [[0, 1], [0]], + [[1, 0], [0]], + [[1, 1], [1]], +]; + +// Количество "эпох" +$epochs = 100000; + +// Скорость обучения +$learningRate = 0.5; + +for ($i = 0; $i < $epochs; $i++) { + // Выбираем случайный элемент из датасета + $trainingData = $trainingSet[array_rand($trainingSet)]; + $inputs = $trainingData[0]; + $targets = $trainingData[1]; + $nn->train($inputs, $targets, $learningRate); +} + +// Сохраняем натренированные веса +$nn->saveWeights(); +```` +Далее при уже обученной сети можно использовать значения сохраненных на этапе обучения весов (метод train() вызывать не требуется) \ No newline at end of file diff --git a/bootstrap.php b/bootstrap.php index d2d38bc..ba733ef 100644 --- a/bootstrap.php +++ b/bootstrap.php @@ -1,5 +1,24 @@ + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + require_once __DIR__ . '/lib/Console.class.php'; + require_once __DIR__ . '/lib/NeuralNetwork.class.php'; diff --git a/lib/Console.class.php b/lib/Console.class.php new file mode 100644 index 0000000..031125c --- /dev/null +++ b/lib/Console.class.php @@ -0,0 +1,68 @@ + + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + namespace rsgrinko; + + /** + * Класс системных функций + * + * @author Roman Grinko + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + namespace rsgrinko\ML; + + /** + * Класс нейронной сети + * + * "@author Roman Grinko numInputs = $numInputs; + $this->numHidden = $numHidden; + $this->numOutputs = $numOutputs; + + if ($storagePath !== null) { + // Задаем хранилище весов с учетом конфигурации сети + $this->storageFile = $storagePath . '/NeuralNetworkWeights_' . $numInputs . '_' . $numHidden . '_' . $numOutputs . '.json'; + } + + + // Пытаемся загрузить сохраненные значения весов + if (!$this->loadWeights()) { + // Если не удалось - генерируем случайно (первый запуск) + + // Инициализация случайных весов скрытого слоя + $this->hiddenWeights = []; + for ($i = 0; $i < $this->numInputs; $i++) { + for ($j = 0; $j < $this->numHidden; $j++) { + $this->hiddenWeights[$i][$j] = mt_rand(-100, 100) / 100; + } + } + + // Инициализация случайных весов выходного слоя + $this->outputWeights = []; + for ($i = 0; $i < $this->numHidden; $i++) { + for ($j = 0; $j < $this->numOutputs; $j++) { + $this->outputWeights[$i][$j] = mt_rand(-100, 100) / 100; + } + } + } + } + + /** + * Обработка + * + * @param array $inputs Входные данные + * + * @return array Результат + */ + public function feedForward(array $inputs): array + { + $hiddenOutputs = []; + for ($i = 0; $i < $this->numHidden; $i++) { + $sum = 0; + for ($j = 0; $j < $this->numInputs; $j++) { + $sum += $inputs[$j] * $this->hiddenWeights[$j][$i]; + } + $hiddenOutputs[$i] = 1 / (1 + exp(-$sum)); + } + + $outputs = []; + for ($i = 0; $i < $this->numOutputs; $i++) { + $sum = 0; + for ($j = 0; $j < $this->numHidden; $j++) { + $sum += $hiddenOutputs[$j] * $this->outputWeights[$j][$i]; + } + $outputs[$i] = 1 / (1 + exp(-$sum)); + } + + return $outputs; + } + + /** + * @param array $inputs Входные данные + * @param array $targets Эталонное значение + * @param float $learningRate Скорость обучения + * + * @return void + */ + public function train(array $inputs, array $targets, float $learningRate): void + { + // Обработка (часть кода дублируется из предыдущего метода для получения данных слоев + // и обработки методом обратного распространения ошибки + $hiddenOutputs = []; + for ($i = 0; $i < $this->numHidden; $i++) { + $sum = 0; + for ($j = 0; $j < $this->numInputs; $j++) { + $sum += $inputs[$j] * $this->hiddenWeights[$j][$i]; + } + $hiddenOutputs[$i] = 1 / (1 + exp(-$sum)); + } + + $outputs = []; + for ($i = 0; $i < $this->numOutputs; $i++) { + $sum = 0; + for ($j = 0; $j < $this->numHidden; $j++) { + $sum += $hiddenOutputs[$j] * $this->outputWeights[$j][$i]; + } + $outputs[$i] = 1 / (1 + exp(-$sum)); + } + + // Расчет ошибок + $outputErrors = []; + for ($i = 0; $i < $this->numOutputs; $i++) { + $error = $targets[$i] - $outputs[$i]; + $outputErrors[$i] = $outputs[$i] * (1 - $outputs[$i]) * $error; + } + + $hiddenErrors = []; + for ($i = 0; $i < $this->numHidden; $i++) { + $error = 0; + for ($j = 0; $j < $this->numOutputs; $j++) { + $error += $outputErrors[$j] * $this->outputWeights[$i][$j]; + } + $hiddenErrors[$i] = $hiddenOutputs[$i] * (1 - $hiddenOutputs[$i]) * $error; + } + + // Обновление весов + for ($i = 0; $i < $this->numHidden; $i++) { + for ($j = 0; $j < $this->numOutputs; $j++) { + $delta = $learningRate * $outputErrors[$j] * $hiddenOutputs[$i]; + $this->outputWeights[$i][$j] += $delta; + } + } + + for ($i = 0; $i < $this->numInputs; $i++) { + for ($j = 0; $j < $this->numHidden; $j++) { + $delta = $learningRate * $hiddenErrors[$j] * $inputs[$i]; + $this->hiddenWeights[$i][$j] += $delta; + } + } + } + + /** + * Загрузка сохраненных значений весов + * + * @return bool Флаг успешного выполнения + */ + private function loadWeights(): bool + { + // Если нет сохраненных весов - выходим + if (!file_exists($this->storageFile)) { + return false; + } + + $data = file_get_contents($this->storageFile); + + // Если данные отсутствуют - выходим + if (empty($data)) { + return false; + } + try { + $jsonData = json_decode($data, true, 512, JSON_THROW_ON_ERROR); + } catch (\Throwable $e) { + return false; + } + + // Если структура данных не совпадает с ожидаемой - выходим + if (empty($jsonData['type']) + || $jsonData['type'] !== 'NNW' + || empty($jsonData['data'])) { + return false; + } + + $this->hiddenWeights = $jsonData['data']['hidden']; + $this->outputWeights = $jsonData['data']['output']; + + return true; + } + + /** + * Сохранение значений весов + * + * @return bool Флаг успешного выполнения + */ + public function saveWeights(): bool + { + // Если не задан путь до файла-хранилища - выходим + if ($this->storageFile === null) { + return false; + } + $data = [ + 'type' => 'NNW', + 'version' => '1.0.0', + 'generated' => date('Y-m-d H:i:s'), + 'data' => [ + 'hidden' => $this->hiddenWeights, + 'output' => $this->outputWeights, + ], + ]; + $result = @file_put_contents($this->storageFile, json_encode($data, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT)); + + return !($result === false); + } + + } diff --git a/lib/NeuroNetwork.class.php b/lib/NeuroNetwork.class.php deleted file mode 100644 index dc6a8bf..0000000 --- a/lib/NeuroNetwork.class.php +++ /dev/null @@ -1,189 +0,0 @@ -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->getSynapsValue(); - } - - /** - * Генерируем связи между нейронами - */ - private function generateSynapses(): void - { - $synapseId = 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 Synapse( - $synapseId, $this->layers[$i][$k], $this->layers[$i + 1][$j], $this->arValues[$synapseId] ?? null - ); - $synapseId++; - } - } - } - } - - /** - * Сохранить значения весов синапсов в файл - * - * @param bool $forceUpdate Принудительно перезаписать - */ - private function saveSynapsValue(bool $forceUpdate= false): void - { - $data = []; - foreach ($this->synapses as $synapse) { - /** @var Synapse $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 Synapse $synapse */ - $synapse->setValue($synapsValues[$synapse->getId()]); - } - - $this->arValues = $synapsValues; - - // Возвращаем веса - return $synapsValues; - } - - /** - * Мутация веса - * - * @param bool $useFullRandom Использовать полностью случайный новый вес - * @param float|null $shift Величина сдвига для мутации - * - * @throws Exception - */ - public function mutate(bool $useFullRandom = false, ?float $shift = 0.1): self - { - foreach ($this->synapses as $synapse) { - /** @var Synapse $synapse */ - if ($useFullRandom) { - // Использовать полностью случайный новый вес - $tempValue = mt_rand() / mt_getrandmax(); - } else { - // Использовать случайный вес в диапазоне "$shift < текущий < $shift" - - // Вариант генерации 1 - //$tempValue = random_int((int)(($synapse->getValue() - $shift) * 100), (int)(($synapse->getValue() + $shift) * 100)) / 100; - - // Вариант генерации 2 - $tempValue = random_int( - (int)(($synapse->getValue() - $shift) * 100000000), - (int)(($synapse->getValue() + $shift) * 100000000) - ) / 100000000; - } - // Ограничиваемся диапазоном 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; - } - - - /** - * Шаг преобразования значений между нейронами - */ - public function step(Synapse $synapse): void - { - $synapse->getOutNeuron()->activate($synapse->getInNeuron()->getValue(), $synapse->getValue()); - } - } \ No newline at end of file diff --git a/lib/Neuron.class.php b/lib/Neuron.class.php deleted file mode 100644 index 2161a45..0000000 --- a/lib/Neuron.class.php +++ /dev/null @@ -1,56 +0,0 @@ -id = $id; - } - - /** Получить текущее значение */ - public function getValue(): ?float - { - return $this->value; - } - - /** Задать текущее значение */ - public function setValue(float $value): self - { - $this->value = $value; - return $this; - } - - /** - * Метод активации - * - * @param float $value Значение - * @param float $weight Коэффициент синапса - */ - public function activate(float $value, float $weight): self - { - - // Умножение значения на коэфициент - $this->value = $value * $weight; - - - // Гиперболический тангенс - // https://otus.ru/journal/kak-sozdat-nejroset/ - // Функция активации - //$this->value = tanh($value * $weight); - return $this; - } - } diff --git a/lib/Synapse.class.php b/lib/Synapse.class.php deleted file mode 100644 index 0f2da83..0000000 --- a/lib/Synapse.class.php +++ /dev/null @@ -1,98 +0,0 @@ -inNeuron = $inNeuron; - $this->outNeuron = $outNeuron; - - // если мы хотим явно задать вес - задаем, иначе генерируем как-нибудь - if ($value !== null) { - $this->value = $value; - } else { - //Вариант генерации 1 - //$this->value = random_int(0, 100000) / 100000; - - // Вариант генерации 2 - $this->value = mt_rand() / mt_getrandmax(); - } - $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/lib/SystemFunctions.class.php b/lib/SystemFunctions.class.php deleted file mode 100644 index 7edb18d..0000000 --- a/lib/SystemFunctions.class.php +++ /dev/null @@ -1,29 +0,0 @@ - + * Permission is hereby granted, free of charge, to any person obtaining + * a copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to + * permit persons to whom the Software is furnished to do so, subject to + * the following conditions: + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, + * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. + * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY + * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, + * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE + * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + + set_time_limit(0); require_once __DIR__ . '/bootstrap.php'; - function getStoragePath(int $id): string - { - return __DIR__ . '/storage/synapseWeightStorage_' . $id . '.json'; + + use rsgrinko\{ML\NeuralNetwork, Console}; + + // Создаем нейросеть + $nn = new NeuralNetwork(2, 3, 1, 'storage'); + + /** + * БЛОК ОБУЧЕНИЯ + * После обучения можно закомментировать его + * и проверить работу с сохраненными весами + */ + // Обучающий датасет + $trainingSet = [ + [[0, 0], [0]], + [[0, 1], [0]], + [[1, 0], [0]], + [[1, 1], [1]], + ]; + + // Количество "эпох" + $epochs = 100000; + + // Скорость обучения + $learningRate = 0.5; + + Console::log('=> Run training...', Console::CLI_COLOR_BLUE); + for ($i = 0; $i < $epochs; $i++) { + // Выбираем случайный элемент из датасета + $trainingData = $trainingSet[array_rand($trainingSet)]; + $inputs = $trainingData[0]; + $targets = $trainingData[1]; + $nn->train($inputs, $targets, $learningRate); + } + Console::log('=> Training success', Console::CLI_COLOR_GREEN); + // Сохраняем натренированные веса + Console::log('=> Save Weights...', Console::CLI_COLOR_BLUE); + $nn->saveWeights(); + Console::log('=> Weights saved', Console::CLI_COLOR_GREEN); + /** КОНЕЦ БЛОКА ОБУЧЕНИЯ */ + + + /** + * Тестирование нейросети + */ + $testSet = [ + [0, 0], + [1, 0], + [0, 1], + [1, 1], + ]; + + Console::log('=> Testing...', Console::CLI_COLOR_BLUE); + + foreach ($testSet as $testElement) { + $result = $nn->feedForward($testElement); + $resultString = '=> Input: ['; + $resultString .= implode(', ', $testElement); + $resultString .= '], result: ['; + $resultString .= implode(', ', $result); + $resultString .= ']'; + Console::log($resultString, Console::CLI_COLOR_GREEN); } - $ob = new NeuroNetwork(getStoragePath(1)); - $res = $ob->run([1, 1]); - echo '[Preset 1] Input data [1, 1], result: ' . $res[0] . PHP_EOL; - - echo '[Mutate] Mutate weights...' . PHP_EOL; - $ob->mutate(); - - $res = $ob->run([1, 1]); - echo '[Preset 2] Input data [1, 1], result: ' . $res[0] . PHP_EOL; - - - diff --git a/training.PNG b/training.PNG new file mode 100644 index 0000000..978e36b Binary files /dev/null and b/training.PNG differ