переосмысление

This commit is contained in:
rsgrinko committed 2023-04-01 00:52:19 +03:00
1 parent 8085cd0700
commit cccec5727f
11 files changed
+474 -397

No files matched your search

+55 -6
View File
@@ -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() вызывать не требуется)
+23 -4
View File
@@ -1,5 +1,24 @@
<?php
require_once __DIR__ . '/lib/SystemFunctions.class.php';
require_once __DIR__ . '/lib/Neuron.class.php';
require_once __DIR__ . '/lib/Synapse.class.php';
require_once __DIR__ . '/lib/NeuroNetwork.class.php';
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* 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';
+68
View File
@@ -0,0 +1,68 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* 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 <rsgrinko@gmail.com
*/
class Console
{
/** @var string CLI_COLOR_RED Красный */
public const CLI_COLOR_RED = "\033[1;31m";
/** @var string CLI_COLOR_GREEN Зеленый */
public const CLI_COLOR_GREEN = "\033[1;32m";
/** @var string CLI_COLOR_BLUE Синий */
public const CLI_COLOR_BLUE = "\033[1;34m";
/** @var string CLI_COLOR_DEFAULT Дефолтный */
public const CLI_COLOR_DEFAULT = "\033[0m";
/** @var string[] Разрешенные цвета */
public const ALLOWED_CLI_COLOR_LIST = [
self::CLI_COLOR_RED,
self::CLI_COLOR_GREEN,
self::CLI_COLOR_BLUE,
self::CLI_COLOR_DEFAULT,
];
/**
* Вывод данных в консоль
*
* @param string $text Текст
* @param string $color Цвет
*
* @return void
*/
public static function log(string $text, string $color = self::CLI_COLOR_DEFAULT): void
{
if (!in_array($color, self::ALLOWED_CLI_COLOR_LIST, true)) {
echo $text;
return;
}
echo $color . $text . self::CLI_COLOR_DEFAULT . PHP_EOL;
}
}
+245
View File
@@ -0,0 +1,245 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* 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 <rsgrinko@gmail.com
*/
class NeuralNetwork
{
/** @var int $numInputs Количество нейронов первого слоя (входы) */
private int $numInputs;
/** @var int $numHidden Количество нейронов скрытого слоя */
private int $numHidden;
/** @var int $numOutputs Количество нейронов последнего слоя (выходов) */
private int $numOutputs;
/** @var array $hiddenWeights Веса нейронов скрытого слоя */
private array $hiddenWeights;
/** @var array $outputWeights Веса нейронов выходного слоя */
private array $outputWeights;
/** @var string|null $storageFile Файл хранилища весов */
private ?string $storageFile = null;
/**
* Конструктор
*
* @param int $numInputs Количество нейронов входного слоя
* @param int $numHidden Количество нейронов скрытого слоя
* @param int $numOutputs Количество нейронов выходного слоя
* @param string|null $storagePath Папка хранилища весов (путь без слеша в конце)
*/
public function __construct(int $numInputs, int $numHidden, int $numOutputs, ?string $storagePath = null)
{
$this->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);
}
}
-189
View File
@@ -1,189 +0,0 @@
<?php
class NeuroNetwork
{
/** @var string $storageFile Файл-хранилище весов */
private $storageFile;
/** @var array $arValues Файл-хранилище весов */
private $arValues;
/**
* @var array $layers Массив массивов нейронов
* [
* [], // Входной слой
* [], // Скрытый слой
* [], // Выходной слой
* ];
*/
private array $layers;
/** @var array Массив синапсов */
private array $synapses;
/**
* Конструктор
*/
public function __construct(?string $storageFile = null)
{
// Хранилище весов
if ($storageFile === null) {
$this->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());
}
}
-56
View File
@@ -1,56 +0,0 @@
<?php
/**
* Класс нейрона
*/
class Neuron
{
/** @var int Идентификатор нейрона */
private int $id;
/** @var float|null Текущее значение */
private ?float $value;
/**
* Конструктор
*
* @param int $id Идентификатор нейрона
*/
public function __construct(int $id)
{
$this->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;
}
}
-98
View File
@@ -1,98 +0,0 @@
<?php
/**
* Класс синапса
* является связующим звеном между нейронами
*/
class Synapse
{
/** @var int Идентификатор синапса */
private $id;
/** @var float Вес */
private $value;
/** @var Neuron Входной нейрон */
private Neuron $inNeuron;
/** @var Neuron Выходной нейрон */
private Neuron $outNeuron;
/**
* Конструктор
*
* @param int $id Идентификатор синапса
* @param Neuron $inNeuron Входной нейрон
* @param Neuron $outNeuron Выходной нейрон
* @param float|null $value Значение веса синапса
*
* @throws \Exception
*/
public function __construct(int $id, Neuron $inNeuron, Neuron $outNeuron, float $value = null)
{
$this->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;
}
}
-29
View File
@@ -1,29 +0,0 @@
<?php
class SystemFunctions {
public const CLI_COLOR_RED = "\033[01;31m";
public const CLI_COLOR_GREEN = "\033[0;32m";
public const CLI_COLOR_BLUE = "\033[0;34m";
public const CLI_COLOR_RED_B = "\033[1;31m";
public const CLI_COLOR_GREEN_B = "\033[1;32m";
public const CLI_COLOR_BLUE_B = "\033[1;34m";
public const CLI_COLOR_DEFAULT = "\033[0m";
public const ALLOWED_CLI_COLOR_LIST = [
self::CLI_COLOR_RED,
self::CLI_COLOR_GREEN,
self::CLI_COLOR_BLUE,
self::CLI_COLOR_RED_B,
self::CLI_COLOR_GREEN_B,
self::CLI_COLOR_BLUE_B,
self::CLI_COLOR_DEFAULT,
];
public static function toConsole(string $text, string $color = self::CLI_COLOR_DEFAULT): void
{
if (!in_array($color, self::ALLOWED_CLI_COLOR_LIST, true)) {
echo $text;
return;
}
echo $color . $text . self::CLI_COLOR_DEFAULT . PHP_EOL;
}
}
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

+83 -15
View File
@@ -1,19 +1,87 @@
<?php
/**
* Copyright (c) 2022 Roman Grinko <rsgrinko@gmail.com>
* 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;
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB