From 7cacdb3b63802e4f45474583a1124b4e5e0bf730 Mon Sep 17 00:00:00 2001 From: xdrm-brackets Date: Wed, 26 Oct 2016 17:53:56 +0200 Subject: [PATCH] Corrections + Genome::mutation(threshold) --- build/neuralnetwork/core/Genome.php | 41 +++++++++++++++++++++++++++++ public/main.php | 7 +++-- 2 files changed, 44 insertions(+), 4 deletions(-) diff --git a/build/neuralnetwork/core/Genome.php b/build/neuralnetwork/core/Genome.php index 1acf4ea..d85cb27 100644 --- a/build/neuralnetwork/core/Genome.php +++ b/build/neuralnetwork/core/Genome.php @@ -145,6 +145,47 @@ return true; } + + /* APPLIES A MUTATION ON THE Genome WITH A SPECIFIC @threshold + * + * @threshold Mutation threshold + * + */ + public function mutation($threshold=0.5){ + /* (1) Checks @threshold argument */ + if( floatval($threshold) !== $threshold || $threshold < 0 || $threshold > 1 ) + throw new \Error('Invalid threshold for Genome mutation.'); + + /* (2) Calculates how many neurons/synapses to mutate */ + $neuronsMutations = round( (count($this->neurons) - 1) * $threshold ); + $synapsesMutations = round( (count($this->synapses) - 1) * $threshold ); + + /* (3) Choose random neurons' indexes */ + $iNeurons = []; + while( count($iNeurons) < $neuronsMutations ){ + $r = rand(0, count($this->neurons)-1); + + if( !in_array($r, $iNeurons) ) + $iNeurons[] = $r; + } + + /* (4) Choose random synapses' indexes */ + $iSynapses = []; + while( count($iSynapses) < $synapsesMutations ){ + $r = rand(0, count($this->synapses)-1); + + if( !in_array($r, $iSynapses) ) + $iSynapses[] = $r; + } + + /* (5) Update chosen neurons */ + for( $i = 0, $l = count($iNeurons) ; $i < $l ; $i++ ) + $this->neurons[$iNeurons[$i]] = rand(self::MIN, self::MAX) / self::MAX; + + /* (6) Update chosen synapses */ + for( $i = 0, $l = count($iSynapses) ; $i < $l ; $i++ ) + $this->synapses[$iSynapses[$i]] = rand(self::MIN, self::MAX) / self::MAX; + } } diff --git a/public/main.php b/public/main.php index adfe229..4e831f8 100644 --- a/public/main.php +++ b/public/main.php @@ -58,11 +58,10 @@ echo implode(' ; ', $b->synapses)."\n\n"; /* (3) Section Title */ - // $b->mutation(0.3); // @b has now mutated with a threshold of 30% - $b = new Genome(2, 3); // 2 layers of 3 neurons each -> randomly filled - echo "B neurons\n"; + $b->mutation(0.3); // @b has now mutated with a threshold of 30% + echo "mutated clone neurons\n"; echo implode(' ; ', $b->neurons)."\n"; - echo "B synapses\n"; + echo "mutated clone synapses\n"; echo implode(' ; ', $b->synapses)."\n\n"; /* (4) Cross-over (father+mother) */