test - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of test.php

  1. <?php
  2. // Тут мы берем два файла: файл с задачами и файл с ответами
  3. // и возвращаем массив, с таким кол-вом эл-тов, который указан в $count
  4. // В элементах содержится два ключа: 'data', указывающий на 784 пикселя(картинка 28х28)
  5. // и 'answer', указывающий на то какую цифру эти данные обозначают.
  6. // Файл offset.txt используется для запоминания того, на каком элементе остановились,
  7. // чтобы следующая выборка начиналась со следующего элемента.
  8. function get_data($file_data, $file_answers, $count) {
  9.     $data = [];
  10.     $offset = file_get_contents('offset.txt');
  11.     $offset_data = 16 + $offset * 784;
  12.     $offset_answers = 8 + $offset;
  13.     fseek( $file_data, $offset_data);
  14.     fseek( $file_answers, $offset_answers);
  15.     $byteString_data = fread($file_data, 784 * $count);
  16.     $arr_data = unpack( 'C*', $byteString_data);
  17.     $byteString_answer = fread($file_answers, 1 * $count);
  18.     $arr_answers = unpack( 'C*', $byteString_answer);
  19.     for ($i = 0; $i < $count; $i++) {
  20.         $arr['data'] = array_slice($arr_data, $i * 784, 784);
  21.         $arr_answer = array_slice($arr_answers, $i, 1);
  22.         $answer = $arr_answer[0];
  23.         $arr['answer'] = $answer;
  24.         if (strlen($answer)) {
  25.             $data[] = $arr;
  26.         }
  27.     }
  28.     $offset += $count;
  29.     $f = fopen('offset.txt','w');
  30.     fwrite($f, $offset);
  31.     fclose($f);
  32.     return $data;
  33. }
  34.  
  35. // тут мы создаем файл digits.data, который нужно 'скормить' нейросети
  36. function create_data_file($data) {
  37.     $f = fopen('digits.data', 'w');
  38.     $count_el = count($data);
  39.     $count_inputs = 784;
  40.     $count_outputs = 10;
  41.     fwrite($f, "$count_el $count_inputs $count_outputs\n");
  42.     foreach ($data as $el) {
  43.         $str_data = '';
  44.         $str_answers = '';
  45.         foreach ($el['data'] as $pixel) {
  46.             $str_pixel = $pixel;
  47.             $str_data .= $str_pixel." ";
  48.         }
  49.         $str_data .= "\n";
  50.         for ($i = 0; $i < 10; $i++) {
  51.             if ($i != $el['answer']) {
  52.                 $str_answers .= "0 ";
  53.             } else {
  54.                 $str_answers .= "1 ";
  55.             }
  56.         }
  57.         $str_data .= $str_answers."\n";
  58.         fwrite($f, $str_data);
  59.     }
  60.     fclose($f);
  61. }
  62.  
  63. // тренеровка искусственной нейросети. Тестовый вариант, я пока не разобрался в полной мере
  64. // и размышляю над правильной реализацией.
  65. function train_net() {
  66.     $start = microtime(true);
  67.     set_time_limit(0);
  68.     $desired_error = 0.001;
  69.     $max_epochs = 500000;
  70.     $epochs_between_reports = 1000;
  71.  
  72.     $fh = fopen('train-images.idx3-ubyte', 'rb');
  73.     $fl = fopen('train-labels.idx1-ubyte', 'rb');
  74.  
  75.     $filename = dirname(__FILE__) . "/digits.data";
  76.     $data = get_data($fh, $fl, 100);
  77.     shuffle ($data);
  78.     $data_chunk = array_chunk ($data, 10);
  79.     foreach ($data_chunk as $group) {
  80.         create_data_file($group);
  81.         $ann = fann_create_from_file((dirname(__FILE__) . '/neural_digits.net'));
  82.         if ($ann) {
  83.             fann_set_activation_function_hidden($ann, FANN_SIGMOID_SYMMETRIC);
  84.             fann_set_activation_function_output($ann, FANN_SIGMOID_SYMMETRIC);
  85.             if (fann_train_on_file($ann, $filename, $max_epochs, $epochs_between_reports, $desired_error)) {
  86.                 fann_save($ann, dirname(__FILE__) . "/neural_digits.net");
  87.             }
  88.             fann_destroy($ann);
  89.         }
  90.     }
  91.     fclose($fh);
  92.     fclose($fl);
  93.  
  94.     $finish = microtime(true);
  95.     $delta = $finish - $start;
  96.     echo $delta . ' сек.';
  97. }
  98. // Тестирование нейросети на новых изображениях.
  99. // Тут возвращается почти такой же массив как и в функции get_data(),
  100. // только появляется новый ключ у эл-тов - 'neural_answer', указывающий на ответ нейросети.
  101. function test_net() {
  102.     $fh = fopen('t10k-images.idx3-ubyte', 'rb');
  103.     $fl = fopen('t10k-labels.idx1-ubyte', 'rb');
  104.     $ann = fann_create_from_file((dirname(__FILE__) . '/neural_digits.net'));
  105.     if ($ann) {
  106.         $data = get_data($fh, $fl, 10);
  107.         foreach ($data as $key => $el) {
  108.             $calc_out = fann_run($ann, $el['data']);
  109.             $data[$key]['neural_answer'] = $calc_out;
  110.         }
  111.         fann_destroy($ann);
  112.         return $data;
  113.     }
  114. }
  115.  
  116. //Выводим на экран следующим образом: я использовал блоки <span> размером 10х10,
  117. //потому что картинка 28х28 очень мала, а 280х280 без проблем видно
  118. ?>    <style>
  119.         .img {
  120.             width: 289px;
  121.             font-size: 0;
  122.             margin-bottom: 5px;
  123.             display: inline-block;
  124.         }
  125.         span {
  126.             display: inline-block;
  127.             width: 10px;
  128.             height: 10px;
  129.         }
  130.         .digit, .neural_digit {
  131.             display: inline-block;
  132.             text-align: center;
  133.             width: 289px;
  134.             height: 289px;
  135.             box-sizing: border-box;
  136.             padding: 50px;
  137.             font-size: 40px;
  138.         }
  139.         pre.neural_digit {
  140.             font-size: 20px;
  141.         }
  142.     </style>
  143. <?php
  144. $data = test_net();
  145. foreach ($data as $el): ?>
  146.     <div class="img">
  147.         <?php foreach ($el[ 'data' ] as $pixel): ?>
  148.             <span style="background: rgb(<?php echo $pixel ?><?php echo $pixel ?>,<?php echo $pixel ?>)"></span>
  149.         <?php endforeach; ?>
  150.     </div>
  151.     <div class="digit"><?php echo $el[ 'answer' ]; ?></div>
  152.     <pre class="neural_digit"><?php print_r($el[ 'neural_answer' ]); ?></pre>
  153.     </div>
  154. <?php endforeach;
  155.  
File Description
  • test
  • PHP Code
  • 11 Feb-2021
  • 5.87 Kb
You can Share it: