Last active
August 29, 2015 14:17
-
-
Save nitrix/05507b1a8fcc0af79623 to your computer and use it in GitHub Desktop.
Generic Neural Network
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| /******************* CONFIG *******************/ | |
| $config_nn_layout = [2, 3, 2, 1]; | |
| $config_nn_step = 7; | |
| /******************** MAIN ********************/ | |
| $neurons = nn_init_neurons($config_nn_layout); | |
| $weights = nn_init_weights($config_nn_layout); | |
| while (true) { | |
| $neurons = nn_init_neurons($config_nn_layout); | |
| $fp = fopen('php://stdin', 'r'); | |
| echo 'Input A: '; | |
| $neurons['0:0'] = trim(fgets($fp)); | |
| echo 'Input B: '; | |
| $neurons['0:1'] = trim(fgets($fp)); | |
| $output = nn_compute($neurons, $weights, $config_nn_layout); | |
| echo 'Output: '.$output[0]."\n"; | |
| echo 'Is the output correct? [y/n] '; | |
| $correct = trim(fgets($fp)) == 'y'; | |
| $weights = nn_adjust_weights($neurons, $weights, $config_nn_step, $config_nn_layout); | |
| echo '----------------'."\n"; | |
| } | |
| /****************** FUNCTIONS *****************/ | |
| function nn_adjust_weights($neurons, $weights, $step, Array $nbs) | |
| { | |
| //TODO | |
| } | |
| function nn_compute($neurons, $weights, Array $nbs) | |
| { | |
| $layer = 0; | |
| foreach ($nbs as $k => $nb) { | |
| if ($k) { | |
| echo 'Processing layer '.$layer.'...'."\n"; | |
| for ($i = 0; $i < $nb; $i++) { | |
| echo '-> '.$i."\n"; | |
| $sum = 0; | |
| for ($j = 0; $j < $nbs[$k-1]; $j++) { | |
| $w = $weights[($layer-1).':'.$j.';'.$layer.':'.$i]; | |
| $n = $neurons[($layer-1).':'.$j]; | |
| echo 'Layer '.($layer-1).' neuron '.$j.' has value '.$n.' and weight '.$w."\n"; | |
| if ($n) { | |
| $sum += $w; | |
| } | |
| } | |
| echo 'Calculated sum is: '.$sum."\n"; | |
| if ($sum >= 50) { | |
| $neurons[$layer.':'.$i] = 1; | |
| } | |
| } | |
| } | |
| $layer++; | |
| } | |
| $output = []; | |
| for ($i = 0; $i < $nb; $i++) { | |
| $output[] = $neurons[$k.':'.$i]; | |
| } | |
| return $output; | |
| } | |
| function nn_init_weights(Array $nbs) | |
| { | |
| $weights = []; | |
| $layer = 0; | |
| foreach ($nbs as $k => $nb) { | |
| for ($i = 0; $i < $nb; $i++) { | |
| if (isset($nbs[$k+1])) { | |
| for ($j = 0; $j < $nbs[$k+1]; $j++) { | |
| $weights[$layer.':'.$i.';'.($layer+1).':'.$j] = rand(0, 100); | |
| } | |
| } | |
| } | |
| $layer++; | |
| } | |
| return $weights; | |
| } | |
| function nn_init_neurons(Array $nbs) | |
| { | |
| $neurons = []; | |
| $layer = 0; | |
| foreach ($nbs as $nb) { | |
| for ($i = 0; $i < $nb; $i++) { | |
| $neurons[$layer.':'.$i] = 0; | |
| } | |
| $layer++; | |
| } | |
| return $neurons; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment