php.de

Zurück   php.de > Webentwicklung > PHP Einsteiger > PHP Tipps 2005

 
 
LinkBack Themen-Optionen Thema bewerten
Alt 19.05.2005, 15:37  
Gast
 
Beiträge: n/a
Standard Training von neuronalen Netzen

Hallo

irgendwas ist faul mit meinem PHP-ANN (artifical neural network).

Beim Training gebe ich dem Ding immer weibliche Namen als Input, und als gewünschten Output eine 1. 1 steht für weiblich.

Bisher habe ich dem neuronalen Netz den Namen "Sabrina" in den Schädel gehämmert. Wenn ich jetzt aber die evaluation mache und dem Ding als Input "Sabrina" gebe, was es ja eigentlich kennen sollte, kommt so was hier als output:

0.10265486288699

weit von einer 1 entfernt, würde ich sagen. Jetzt könnte man ja noch meinen gut das Ding weis ja weniger als eine Eidechse, okay. Aber wieso zum Fuchs ist der Output auch bei einem Input wie "Bert", "Joe" oder "Sandra" immer genau gleich? nämlich: 0.10265486288699



falls mal jemand bock hat mit dem ANN rumzuspielen, hier die source:

nn.php


PHP-Code:
<?php
class Maths {

    function &
sigmoid($x) {
        return 
/ (exp(-$x) );
    }
    
    function &
random($min 0$max 10) {
        
mt_srand( (double) microtime() * 1234567890);
        return 
mt_rand($min$max);
    }
}


class 
Neuron {
    
    var 
$inputs;
    var 
$weights;
    var 
$output;
    var 
$delta;
    
    function 
Neuron() {
    }
    
    function 
setInputs($inputs) {
        
$inputs[] = 1// bias
        
        
$this->inputs $inputs;
        
        if (
count($this->weights) == 0) {
            
$this->initialiseWeights();
        }
    }
    
    function 
setOutput($output) {
        
$this->output $output;
    }
    
    function 
setDelta($delta) {
        
$this->delta $delta;
    }
    
    function 
getInputs() {
        return 
$this->inputs;
    }
    
    function 
getWeights() {
        return 
$this->weights;
    }

    function 
getOutput() {
        return 
$this->output;
    }
    
    function 
getDelta() {
        return 
$this->delta;
    }
    
    function 
initialiseWeights() {
        foreach (
array_keys($this->inputs) as $k) {
            
$this->weights[$k] = Maths::random(-10001000) / 1000;
        }
    }
    
    function 
activate() {
        
$sum 0;
        
        foreach (
array_keys($this->inputs) as $k) {
            
$sum += ($this->inputs[$k] * $this->weights[$k]);
        }
        
$this->setOutput(Maths::sigmoid($sum) );        
    }
    
    function 
adjustWeights($learningRate) {
        foreach (
array_keys($this->weights) as $k) {
            
$this->weights[$k] += ($learningRate $this->inputs[$k] * $this->getDelta() );
        }
    }
}


class 
Layer {
    
    var 
$neurons;
    var 
$outputs;
    
    function 
Layer($numberOfNeurons) {
        
$this->createNeurons($numberOfNeurons);
    }
    
    function 
setInputs($inputs) {
        foreach (
array_keys($this->neurons) as $k) {
            
$this->neurons[$k]->setInputs($inputs);
        }
    }
    
    function 
getNeurons() {
        return 
$this->neurons;
    }
    
    function 
getInputs() {
        return 
$this->inputs;
    }
    
    function 
getOutputs() {
        return 
$this->outputs;
    }
    
    function 
createNeurons($numberOfNeurons) {
        for (
$i 0$i $numberOfNeurons$i++) {
            
$this->neurons[] =& new Neuron();        
        }
    }
    
    function 
activate() {
        foreach (
array_keys($this->neurons) as $k) {
            
$this->neurons[$k]->activate();
            
$this->outputs[$k] = $this->neurons[$k]->getOutput();
        }
    }
    
    function 
calculateHiddenDeltas($nextLayer) {
        
$neurons $nextLayer->getNeurons();    
        
        foreach (
array_keys($this->neurons) as $k) {
            
$sum 0;
            foreach (
array_keys($neurons) as $l) {
                
$weights $neurons[$l]->getWeights();
                
$sum += ($weights[$k] * $neurons[$l]->getDelta() );
            }

            
$delta $this->neurons[$k]->getOutput() * ($this->neurons[$k]->getOutput() ) * $sum;
            
$this->neurons[$k]->setDelta($delta);
        }
    }
    
    function 
calculateOutputDeltas($desiredOutputs) {
        foreach (
array_keys($this->neurons) as $k) {
            
$delta $this->neurons[$k]->getOutput() * ($desiredOutputs[$k] - $this->neurons[$k]->getOutput() ) * 
                (
$this->neurons[$k]->getOutput() );
            
$this->neurons[$k]->setDelta($delta);
        }
    }
    
    function 
adjustWeights($learningRate) {
        foreach (
array_keys($this->neurons) as $k) {
            
$this->neurons[$k]->adjustWeights($learningRate);
        }
    }
}


class 
Network {

    var 
$outputLayer;
    var 
$hiddenLayers;
    
    function 
Network($numberOfHiddenLayers$numberOfNeuronsPerLayer$numberOfOutputs) {
        
$this->createHiddenLayers($numberOfHiddenLayers$numberOfNeuronsPerLayer);
        
$this->createOutputLayer($numberOfOutputs);
    }
    
    function 
setInputs($inputs) {
        foreach (
array_keys($this->hiddenLayers) as $k) {
            
$this->hiddenLayers[$k]->setInputs($inputs);
        }
    }
    
    function 
getOutputs() {
        return 
$this->outputLayer->getOutputs();    
    }
    
    function 
createHiddenLayers($numberOfHiddenLayers$numberOfNeuronsPerLayer) {
        for (
$i 0$i $numberOfHiddenLayers$i++) {
            
$this->hiddenLayers[] =& new Layer($numberOfNeuronsPerLayer);
        }
    }
    
    function 
createOutputLayer($numberOfOutputs) {
        
$this->outputLayer =& new Layer($numberOfOutputs);
    }
    
    function 
activate() {
        for (
$i 0$i count($this->hiddenLayers) - 1$i++) {
            
$this->hiddenLayers[$i]->activate();
            
            
$this->hiddenLayers[$i 1]->setInputs($this->hiddenLayers[$i]->getOutputs() );
        }
        
$this->hiddenLayers[$i]->activate();
        
        
$this->outputLayer->setInputs($this->hiddenLayers[$i]->getOutputs() );
        
$this->outputLayer->activate();
    }
    
    function 
train($learningRate$outputs) {
        
$this->activate();
        
        
$this->outputLayer->calculateOutputDeltas($outputs);
        
$this->hiddenLayers[count($this->hiddenLayers) - 1]->calculateHiddenDeltas($this->outputLayer);
        for (
$i count($this->hiddenLayers) - 1$i 1$i--) {
            
$this->hiddenLayers[$i 1]->calculateHiddenDeltas($this->hiddenLayers[$i]);
        }
        
        
$this->outputLayer->adjustWeights($learningRate);
        for (
$i count($this->hiddenLayers); $i 0$i--) {
            
$this->hiddenLayers[$i 1]->adjustWeights($learningRate);    
        }
    }
    
    function 
save($filename) {
        
$serialised serialize($this);
        
        
$f fopen($filename"w+");
        if (!
$f)  {
            echo 
"\nCould not open $filename!";
            return;
        }
        
        
$size fwrite($f$serialised);
        
fclose($f);
    }
    
    function &
load($filename) {
        if (
file_exists($filename) ) {
            
$f fopen($filename"r");
            
$serialised fread($ffilesize($filename) );
            
fclose($f);
            
            if (
$serialised 0) {
                return 
null;
            }
            return 
unserialize($serialised);
        }
        return 
null;
    }    
}
?>


Mein File zum trainieren:

PHP-Code:
<?php
// ini_set("max_execution_time", 800);

require_once("nn.php");

$filename "xor.dat";

$network Network::load($filename);

if (
$network == null) {
    echo 
"\nNetwork not found. Creating a new one...";
    
$network =& new Network(1101);
}


// training inputs
$inputs = array("Sabrina");

// desired outputs
$outputs = array("1");

                
// recurse the training until desired results are obtained
// $j = Maths::random(0, 1);
$j 1;
$network->setInputs($inputs[$j]);
$network->train(0.5$outputs[$j]);

echo 
$inputs[$j]."
"
;
echo 
$outputs[$j]."
"
;

$network->save($filename);
?>


und zu guter letzt die Datei zum evaluieren (abfragen des "Gehirns"):

PHP-Code:
<?php
// ini_set("max_execution_time", 300);

require_once("nn.php");

$filename "xor.dat";

$network Network::load($filename);

if (
$network == null) {
    echo 
"\nNetwork not found.";
}

// training inputs
$inputs = array(
    array(
"Sandra"),
    array(
"Sabrina"),
    array(
"Bert"),
    array(
"Joe")
);


for (
$i 0$i 4$i++) {
    
$network->setInputs($inputs[$i]);
    
$network->activate();
    
    echo 
"\n";
    
print_r($network->getOutputs() );
}
?>

den kram in einem Ordner ablegen und fertig ist der Brei. Dann die trainings-Datei laden und mehrmals aktualisieren. Bis eine Datei namens xor.dat angelegt wurde.

Je öfter ich den Namen "Sabrina" ins ANN einpflege desto kleiner scheint diese Zahl zu werden. Hab ich da irgendwas noch nicht gecheckt? Muss ich den Training-Input in einer Schleife so oft durchlaufen lassen bis mir das Ding eine glatte 1 ausspuckt? oh oh...
die Zahl wird aber nicht größer sondern kleiner, mit zunehmendem "Lernen". rofl

Und bitte ich will keine dummen Sprüche hören von wegen ich Noob habe mich gar nicht mit ANN's zu befassen. Lasst's stecken. Hoffe aber hier surfen die richtigen Leute, die mir bei dem Problemchen weiterhelfen können
 
Sponsor Mitteilung
PHP Code Flüsterer

Registriert seit: 21.08.2005
Beiträge: 4682
PHP-Kenntnisse:
Fortgeschritten

Alt 19.05.2005, 15:41  
Moderator
 
Benutzerbild von robo47
 
Registriert seit: 03.09.2004
Beiträge: 11.798
PHP-Kenntnisse:
Fortgeschritten
robo47 ist ein wunderbarer Anblickrobo47 ist ein wunderbarer Anblickrobo47 ist ein wunderbarer Anblickrobo47 ist ein wunderbarer Anblickrobo47 ist ein wunderbarer Anblickrobo47 ist ein wunderbarer Anblickrobo47 ist ein wunderbarer Anblickrobo47 ist ein wunderbarer Anblick
Standard

will ja nix sagen, aber so ne klasse die zu 0 % kommentiert ist, macht es wirklich keinen spass sich anzuschauen.
robo47 ist offline  
Alt 19.05.2005, 15:48  
Gast
 
Beiträge: n/a
Standard

naja, ich würd ned sagen "du n00b lass es"...
sondern eher "du N00b, das Projekt ist intressant, hol dir noch mehr leute dazu die mit dir das ganze über monate hinweg entwickeln"
ich glaube das passt besser...
wobei ich n00b nicht als schimpfwort sehe sondern eher von dir einfach übernommen hab....
denn ich denke das Projekt is für einen fast zu groß...eher ne Lebensaufgabe...
 
Alt 19.05.2005, 15:55  
Gast
 
Beiträge: n/a
Standard

Zitat:
denn ich denke das Projekt is für einen fast zu groß...eher ne Lebensaufgabe...
lol?

in amerika beschäftigen sich kleine schüler damit. alleine. von wegen eine lebensaufgabe, es klemmt nur beim richtigen training. hier waren doch mal ein par Leute die meinten die haben Ahnung davon. Ich bin geduldig...

Zitat:
will ja nix sagen, aber so ne klasse die zu 0 % kommentiert ist, macht es wirklich keinen spass sich anzuschauen.
vielleicht hilft das hier... wollte das Board nicht gleich vollstopfen:

Zitat:
Coding an artificial neural network (ANN) in PHP
Introduction
Operation Flashpoint, published by CodeMasters, is one of my favourite games. It is very immersive thanks to an assortment of authentic weapons, vehicles and realistic sound effects. But, perhaps, its most important ingredient is the artificial intelligence engine. No wonder, then, that countless hours of gameplay have rekindled my dormant interest in artificial intelligence and artificial neural networks (ANNs).
In this article, I will document how I implemented an ANN using the PHP scripting language. Theories, formulas and respective proofs will not be covered; for details, please visit the links in the next section.
The source can be found here.
Neural networks
What is an artificial neural network?
An artificial neural network is a model of the organic brain. It attempts to reproduce the interactions between the neurons in the brain during the learning and thinking process. It works by applying mathematical formulae obtained from medical studies of how the actual brain works. For a more detailed definition, please see here.
Types of ANNs
There are several different types of ANNs. This implementation will model the feed-forward, multi-layer neural network. See here.
Learning
An ANN learns in the same way as the natural brain, that is, by reinforcing the connections between neurons. Several learning (or training) algorithms have been devised. The one my implementation uses is backpropagation, also known as BACKPROP. See here.
Getting more information
The reference is, without doubt, the comp.ai.neural-nets FAQ.
PHP implementation
Choice of language
Several tutorials for developing ANNs are already available on the Internet. However, most of these cover the usual languages for such a task, that is, C, C++ and Java. Also, a procedural approach is very often adopted instead of an object-oriented one, even for the tutorials using Java.
I chose to develop in PHP to take advantage of its diversity of vector manipulation functions and a shorter coding-debugging lifecycle while in the process of learning the algorithms thanks to the interpreted nature of PHP scripts.
This implementation makes extensive use of OOP techniques. I recommend that the reader familiarises himself or herself with these concepts before proceeding.
Basics
If you have skipped the theory explained at the web sites listed above, hopefully, the following will get you up to speed.
A multi-layer ANN consists of at least three layers: one input layer, a hidden layer and one output layer. There can be any number of hidden layers, each with any number of neurons (hidden neurons).
In a feed-forward ANN, each input is fed into each neuron of the first hidden layer whose outputs are fed into the neurons of the next layer, and so on, until the output neurons receive the inputs and produce the final outputs.
Additionally, a bias input may be fed into each layer for better results. Please, see here for an explantion of the importance of the bias input.
Each input has a weight that is initially set to a random value -- usually between -1.0 and 1.0; during training, the weights are adjusted using an error-correction algorithm until the ANN gives the desired output. In essence, the final weights make up the "knowledge" acquired by the ANN. It should be noted, however, that each set of weights will only work with an ANN having the same architecture (same number of inputs, layers, hidden neurons and outputs) as the one from which it was obtained.
The simplest definition of the output of an artificial neuron is the result obtained when the sum of its weighted inputs is passed through a stepping function. In our case, the sigmoid function will be used. Its formula is
f(x) = 1 / (1 + exp(-x) )
where exp() is an exponential function.
Therefore, given three inputs x1, x2 and x3, with weights w1, w2, w3, respectively, to a neuron, the output can be obtained as follows:
Step 1 - Calculating the sum of weighted inputs
sum = (x1 * w1) + (x2 * w2) + (x3 * w3)
Step 2 - Calculating the output
output = 1 / (1 + exp(-1 * sum) )
Given an ANN with n output neurons, n outputs are expected. Each output is calculated using the formulae above to give the ANN's final output -- a vector of outputs, that is.
It should be noted that the above sigmoid function only outputs results between 0 and 1. Therefore, some kind scale should be applied to the results to give values outside this range.
An ANN, using the BACKPROP algorithm, is trained by recursively feeding a set of inputs into it and adjusting its weights according to the discrepancy between the actual outputs and desired outputs. The recursion lasts until an acceptable discrepancy is reached.
The adjustment (or weight change) for each input is proportional to its value. So,
weight change = learning rate * input * delta
The learning rate is an arbitrary value that dictates how fast the network should learn. The delta is the rate of change of the discrepancy with respect to the output for the neuron; it is determined by using the delta rule. For a general definition, see
http://uhaweb.hartford.edu/compsci/n...elta-rule.html
http://diwww.epfl.ch/mantra/tutorial...ml/theory.html
Calculation of the delta for an output neuron is easily obtained by using the following formula.
delta = actual output * (1 - actual output) * (desired output - actual output)
Calculation of the delta for a hidden neuron is more complex because it depends on the delta values of the neurons of the previous layer as the adjustment proceeds from the output layer to the input layer.
To calculate the delta for a neuron which feeds its output to n neurons in the next layer, the following steps are required.
Step 1 - Calculate the product of the weight [for the output] and the delta of each of the n neurons
sum += weight * deltan
for each delta of the n neurons, where deltan is the delta for the n-th neuron.
Step 2 - Calculate the delta for the hidden neuron
delta = actual output * (1 - actual output) * sum
The concepts and formulae above are sufficient for a successful implementation.
Components
The entire implementation consists of four classes.
Maths
This class provides two static methods, random() and sigmoid() respectively.
random() generates random numbers within the limits specified
sigmoid() implements the sigmoid function described earlier
Neuron
This class abstracts a neuron. It holds an array of inputs and weights; the output; and the calculated delta.
The output is calculated by calling the activate() method and read by calling the getOutput() accessor method. The method setDelta() sets the delta for the neuron, and adjustWeights() adjust the weights according to the delta and the learning rate.
Layer
This class abstracts a network layer. It contains a vector of neurons and outputs. It also provides functions to calculate the deltas of each neuron according to the type of the layer. In the case of an output layer, the function calculateOutputDeltas() is used; in the case of a hidden layer, the function calculateHiddenDeltas() is used. These two functions set the delta of each neuron of the layer. The method activate() activates each neuron in turn. The accessor method getOutputs() returns the outputs of all the neurons as a vector; these are then either fed into the next layer's neurons, or returned as the network output.
Network
This class abstracts the artificial neural network. The constructor takes arguments for the number of hidden layers, the number of neurons per hidden layer and the number of outputs.
The most important methods of this class are setInputs(), train(), activate() and getOutputs(). The network takes a vector of values as input and outputs a vector of values as output.
The methods save() and load() save the network architecture and weights and load a stored network, respectively.
Installation and usage
Contents of archive
The archive contains the following files.
nn.php - the ANN implementation classes
XOR_Training.php - the sample script for training a XOR
XOR_Run.php - the sample script to evaluate XOR operations
xor.dat - the saved XOR network architecture and weights
Creating a neural network
To create an ANN, you will need to include the file nn.php. Using the classes, you can structure your ANN as you wish. Once you have trained your network, you can save it to a file.
To use your network for evaluations, you need to restore the network from the saved file, feed it with inputs and get the output.
Training
Training is achieved by feeding a well prepared set of inputs and desired outputs to the network.
For example,
...

// training inputs
$inputs = array(
array(0, 0),
array(0, 1),
array(1, 0),
array(1, 1)
);

// desired outputs
$outputs = array(
array(0),
array(1),
array(1),
array(0)
);

// recurse the training until desired results are obtained
for ($i = 0; $i < 10000; $i++) {
$j = Maths::random(0, 3);
$network->setInputs($inputs[$j]);
$network->train(0.5, $outputs[$j]);
}

// save the network to a file
$network->save("xor.dat");
It is recommended that the network be saved at regular intervals to avoid re-starting the network each time.
Evaluating
To evaluate a set of inputs, the network needs to be loaded from the file and fed with the inputs; and the activate() method called. The output is obtained by calling the getOutputs() method.
For example,
$network = Network::load("xor.dat");

if ($network == null) {
echo "\nNetwork not found. Creating a new one...";
$network =& new Network(1, 10, 1);
}

$inputs = array(
array(0, 0),
array(0, 1),
array(1, 0),
array(1, 1)
);

for ($i = 0; $i < 4; $i++) {
$network->setInputs($inputs[$i]);
$network->activate();

echo "\n";
print_r($network->getOutputs() );
}
Leider wird das hier im Board nicht so sauber umgesetzt (logisch). Habs als Word Dokument. Wer es haben will, bitte eine PN.
 
Alt 19.05.2005, 18:13  
Gast
 
Beiträge: n/a
Standard

ich bin schon mal einen kleinen Schritt weiter gekommen... als Input werden scheinbar nur Zahlen zwischen 0 und 1 akzeptiert. Ich muss also meine Strings (Namen) in eine Zahl konvertieren, so bescheuert das auch klingt.

0 wäre dann eine Frau
1 wäre ein Mann.
 
Alt 28.09.2005, 15:12  
Erfahrener Benutzer
 
Benutzerbild von SvenLittkowski
 
Registriert seit: 05.09.2004
Beiträge: 578
SvenLittkowski zeigte ein beschämendes Verhalten in der Vergangenheit
Standard

Hallo New Bert,

ich finde Dein Projekt sehr sehr interessant. Auf welche Fähigkeiten (kurz genannt) wird dieses neuronale Netzwerk hinauslaufen? Welche Eigenschaften wird es irgendwann einmal haben?

Sven
SvenLittkowski ist offline  
 


Themen-Optionen
Thema bewerten
Thema bewerten:

Forumregeln
Es ist dir nicht erlaubt, neue Themen zu verfassen.
Es ist dir nicht erlaubt, auf Beiträge zu antworten.
Es ist dir nicht erlaubt, Anhänge hochzuladen.
Es ist dir nicht erlaubt, deine Beiträge zu bearbeiten.

BB-Code ist an.
Smileys sind an.
[IMG] Code ist an.
HTML-Code ist aus.
Trackbacks are an
Pingbacks are an
Refbacks are an
Gehe zu

Ähnliche Themen
Thema Autor Forum Antworten Letzter Beitrag
allgemeine Frage zu neuronalen Netzen auf PHP-Basis PHP Tipps 2005 6 20.05.2005 12:24

Besucher kamen über folgende Suchanfragen bei Google auf diese Seite
neuronale netze php, php neuronale netze, coding an artificial neural network (ann) in php, php sigmoid, php neuronales netz, metager daten bayes-filter, php sigmoid function, simple neural network tutorial, neuronale netzwerke php, c neuronal network sigmoid example, neuronales netz php, neuronal network count hidden layers, neuronales netzt mit php, staticmethods.class.php, count of hidden layers neurons, learnig rate neuronalen netz, php und neuronale netze, sigmoidal neurons calculation, training von neuronalen netzen, neuronale netze in php

Alle Zeitangaben in WEZ +1. Es ist jetzt 11:51 Uhr.




Powered by vBulletin® Version 3.7.2 (Deutsch)
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.2.0
Aprilia-Forum, Aquaristik-Forum, Liebeskummer-Forum, Zierfisch-Forum, Geizkragen-Forum

Creative Commons License
Dieser Inhalt ist unter einer Creative Commons-Lizenz lizenziert.