Как перевести нейронную сеть из C в Stack Overflow

Я пытаюсь перевести этот алгоритм с языка C на PHP (для изучения)
Это пример персептрона. Я скопировал пример, написанный на c, и пытаюсь перевести его на PHP. В настоящее время я написал этот код, что я не так? В качестве вывода я знаю только 101 итерацию с результатом всегда 1.

Это программа на C:

    #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define LEARNING_RATE    0.1
#define MAX_ITERATION    100

float randomFloat()
{
return (float)rand() / (float)RAND_MAX;
}

int calculateOutput(float weights[], float x, float y)
{
float sum = x * weights[0] + y * weights[1] + weights[2];
return (sum >= 0) ? 1 : -1;
}

int main(int argc, char *argv[])
{
srand(time(NULL));

float x[208], y[208], weights[3], localError, globalError;
int outputs[208], patternCount, i, p, iteration, output;

FILE *fp;
if ((fp = fopen("test1.txt", "r")) == NULL) {
printf("Cannot open file.\n");
exit(1);
}

i = 0;
while (fscanf(fp, "%f %f %d", &x[i], &y[i], &outputs[i]) != EOF) {
if (outputs[i] == 0) {
outputs[i] = -1;
}
i++;
}
patternCount = i;

weights[0] = randomFloat();
weights[1] = randomFloat();
weights[2] = randomFloat();

iteration = 0;
do {
iteration++;
globalError = 0;
for (p = 0; p < patternCount; p++) {
output = calculateOutput(weights, x[p], y[p]);

localError = outputs[p] - output;
weights[0] += LEARNING_RATE * localError * x[p];
weights[1] += LEARNING_RATE * localError * y[p];
weights[2] += LEARNING_RATE * localError;

globalError += (localError*localError);
}

/* Root Mean Squared Error */
printf("Iteration %d : RMSE = %.4f\n", iteration,
sqrt(globalError/patternCount));
} while (globalError != 0 && iteration<=MAX_ITERATION);

printf("\nDecision boundary (line) equation: %.2f*x + %.2f*y + %.2f = 0\n",
weights[0], weights[1], weights[2]);

return 0;
}

и это код, который я написал

   <?php
define("LEARNING_RATE", 0.1);
define("MAX_ITERATION", 100);
function randomFloat(){ return (float) mt_rand() / mt_getrandmax(); }
function calculateOutput($weights, $x, $y){
$sum = (float) $x * $weights[0] + $y * $weights[1] + $weights[2];
return ($sum >= 0) ? 1 : -1;
}
srand(time());
$i = 0;
$ars = explode("\n",file_get_contents('https://raw.githubusercontent.com/RichardKnop/ansi-c-perceptron/master/test1.txt'));
foreach($ars as $ar){
$temp = explode("\t", $ar);
$x[$i] = (float) $temp[0];
$y[$i] = (float) $temp[1];
$output[$i] = (int) $temp[2];
if($output[$i] == 0)
$output[$i] = -1;
$i++;
}
$patternCount = $i;
$weights[0] = randomFloat();
$weights[1] = randomFloat();
$weights[2] = randomFloat();
$iteration = 0;
do{
$iteration++;
$globalError = 0;
for ($p = 0; $p < $patternCount; $p++) {
$output = calculateOutput($weights, $x[$p], $y[$p]);
$localError = $outputs[$p] - $output;
$weights[0] += LEARNING_RATE * $localError * $x[$p];
$weights[1] += LEARNING_RATE * $localError * $y[$p];
$weights[2] += LEARNING_RATE * $localError;
$globalError += ($localError*$localError);
}
$r .= "Iteration $iteration : RMSE = " .
sqrt($globalError/$patternCount)."<br>";
}while($globalError != 0 && $iteration<=MAX_ITERATION);
echo $r;
echo "<br><hr><br>";
echo "Decision boundary (line) equation: ".$weights[0]."*x + ".$weights[1]."*y + ".$weights[2]." = 0<br>";

он практически идентичен, но почему не работает?

-3

Решение

    $ars = explode("\n",file_get_contents('…'));

Поскольку файл заканчивается \n, это приводит к пустой строке в качестве последнего значения массива, что разрушает foreach($ars as $ar) петля. Чтобы прочитать файл в массив, просто используйте:

    $ars = file('…');

в foreach($ars as $ar) цикл, вы использовали неправильное имя $output[$i] вместо $outputs[$i],


       $r .= "Iteration $iteration : RMSE = " .
sqrt($globalError/$patternCount)."<br>";
}while($globalError != 0 && $iteration<=MAX_ITERATION);
echo $r;

Вы не инициализировали $r, Вместо вышеперечисленного вы можете использовать:

       echo "Iteration $iteration : RMSE = " .
sqrt($globalError/$patternCount)."<br>";
} while ($globalError != 0 && $iteration<=MAX_ITERATION);
0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector