public GeneticAlgorithm(int selectedFitnessFunction, int populationSize, int iterationsNumber, int selectedMethod) { this.selectedMethod = selectedMethod; ISelectionMethod selectionMethot = GetSelectionMethod(); DoubleArrayChromosome chromosome = new DoubleArrayChromosome(new AForge.Math.Random.StandardGenerator(), new AForge.Math.Random.StandardGenerator(), new AForge.Math.Random.StandardGenerator(), 2); FitnessFunction fitnessfunction = new FitnessFunction(selectedFitnessFunction); Population population = new Population(populationSize, chromosome, fitnessfunction, selectionMethot); double[,] tmp = new double[iterationsNumber, 2]; this.result = new double[iterationsNumber, 2]; int i; for (i = 0; i < iterationsNumber; i++) { population.RunEpoch(); DoubleArrayChromosome bestChromosome = (DoubleArrayChromosome)population.BestChromosome; double x = (double)bestChromosome.Value.GetValue(0); double y = (double)bestChromosome.Value.GetValue(1); tmp[i, 0] = x; tmp[i, 1] = y; if (fitnessfunction.Evaluate(bestChromosome) == 100) { break; } } this.result = new double[i, 2]; for (int j = 0; j < i; j++) { result[j, 0] = tmp[j, 0]; result[j, 1] = tmp[j, 1]; } }
public void Mutate() { DoubleArrayChromosome c = ToDoubleArrarChromosome(); c.Mutate(); SetWithDoubleArrayChromosome(c); }
public Strategy Clone() { DoubleArrayChromosome daChromosome = ToDoubleArrarChromosome(); Strategy s = new Strategy(activationFunction, inputsCount, neuronsCount); s.SetWithDoubleArrayChromosome(daChromosome); return(s); }
/// <summary> /// Runs learning epoch. /// </summary> /// /// <param name="input">Array of input vectors.</param> /// <param name="output">Array of output vectors.</param> /// /// <returns>Returns summary squared learning error for the entire epoch.</returns> /// /// <remarks><para><note>While running the neural network's learning process, it is required to /// pass the same <paramref name="input"/> and <paramref name="output"/> values for each /// epoch. On the very first run of the method it will initialize evolutionary fitness /// function with the given input/output. So, changing input/output in middle of the learning /// process, will break it.</note></para></remarks> /// public double RunEpoch(double[][] input, double[][] output) { Debug.Assert(input.Length > 0); Debug.Assert(output.Length > 0); Debug.Assert(input.Length == output.Length); Debug.Assert(network.InputsCount == input.Length); // check if it is a first run and create population if so if (population == null) { // sample chromosome var chromosomeExample = new DoubleArrayChromosome( chromosomeGenerator, mutationMultiplierGenerator, mutationAdditionGenerator, numberOfNetworksWeights); // create population ... population = new Population(populationSize, chromosomeExample, new EvolutionaryFitness(network, input, output), selectionMethod) { // ... and configure it CrossoverRate = crossOverRate, MutationRate = mutationRate, RandomSelectionPortion = randomSelectionRate }; } // run genetic epoch population.RunEpoch(); // get best chromosome of the population var chromosome = (DoubleArrayChromosome)population.BestChromosome; var chromosomeGenes = chromosome.Value; // put best chromosome's value into neural network's weights var v = 0; for (var i = 0; i < network.Layers.Length; i++) { var layer = network.Layers[i]; for (var j = 0; j < layer.Neurons.Length; j++) { var neuron = layer.Neurons[j] as ActivationNeuron; for (var k = 0; k < neuron.Weights.Length; k++) { neuron.Weights[k] = chromosomeGenes[v++]; } neuron.Threshold = chromosomeGenes[v++]; } } Debug.Assert(v == numberOfNetworksWeights); return(1.0 / chromosome.Fitness); }
public void Crossover(Strategy strategy) { if (strategy != null) { DoubleArrayChromosome c1 = ToDoubleArrarChromosome(); DoubleArrayChromosome c2 = strategy.ToDoubleArrarChromosome(); c1.Crossover(c2); SetWithDoubleArrayChromosome(c1); } else { throw new NullReferenceException(); } }
/// <summary> /// Evaluates chromosome. /// </summary> /// /// <param name="chromosome">Chromosome to evaluate.</param> /// /// <returns>Returns chromosome's fitness value.</returns> /// /// <remarks>The method calculates fitness value of the specified /// chromosome.</remarks> /// public double Evaluate(IChromosome chromosome) { DoubleArrayChromosome daChromosome = (DoubleArrayChromosome)chromosome; double[] chromosomeGenes = daChromosome.Value; // total number of weight in neural network int totalNumberOfWeights = 0; // asign new weights and thresholds to network from the given chromosome for (int i = 0, layersCount = network.Layers.Length; i < layersCount; i++) { Layer layer = network.Layers[i]; for (int j = 0; j < layer.Neurons.Length; j++) { ActivationNeuron neuron = layer.Neurons[j] as ActivationNeuron; for (int k = 0; k < neuron.Weights.Length; k++) { neuron.Weights[k] = chromosomeGenes[totalNumberOfWeights++]; } neuron.Threshold = chromosomeGenes[totalNumberOfWeights++]; } } // post check if all values are processed and lenght of chromosome // is equal to network size Debug.Assert(totalNumberOfWeights == daChromosome.Length); double totalError = 0; for (int i = 0, inputVectorsAmount = input.Length; i < inputVectorsAmount; i++) { double[] computedOutput = network.Compute(input[i]); for (int j = 0, outputLength = output[0].Length; j < outputLength; j++) { double error = output[i][j] - computedOutput[j]; totalError += error * error; } } if (totalError > 0) { return(1.0 / totalError); } // zero error means the best fitness return(double.MaxValue); }
public static List <NeuroEvolveBot> GetBots(NetworkType networkType, IRandomNumberGenerator <double> rand) { var values = FileHandler.GetGenerations(networkType); List <NeuroEvolveBot> bots = new List <NeuroEvolveBot>(); for (int i = 0; i < values.Count; i++) { var chrome = new DoubleArrayChromosome(rand, rand, rand, values[i]); var net = GetNetHelper.GetNet(chrome, new int[] { 5, 4, 3 }); var bot = new NeuroEvolveBot(net, i, "NeuroEvolve" + " " + i); bots.Add(bot); } return(bots); }
public static void RunGene() { var rand = new ZigguratExponentialGenerator(); var chrom = new DoubleArrayChromosome(rand, rand, rand, 9); var pop = new Population(1000, chrom, new fitFunc(), new EliteSelection()); Console.WriteLine(pop.FitnessMax); for (int i = 0; i < 199; i++) { pop.RunEpoch(); Console.WriteLine(pop.FitnessMax); } var x = new fitFunc().Evaluate(pop.BestChromosome); Console.WriteLine(pop.FitnessMax); }
public void StartSimulation(Population population) { for (int i = 0; i < population.Size; i++) { DoubleArrayChromosome c = population[i] as DoubleArrayChromosome; if (c == null) { Debug.LogError("IChromosome with wrong type"); continue; } var animal = AnimalPrefab.PrefabInstantiate(c.Value, c, transform); animal.transform.localPosition = GetRandomPosition(); } for (int i = 0; i < FoodCount; i++) { var food = Instantiate(FoodPrefab, transform); food.transform.localPosition = GetRandomPosition(); } }
public void SetWithDoubleArrayChromosome(DoubleArrayChromosome daChromosome) { int count = 0; double[] chromosomeGenes = daChromosome.Value; // asign new weights and thresholds to network from the given chromosome for (int i = 0, layersCount = Layers.Length; i < layersCount; i++) { Layer layer = Layers[i]; for (int j = 0; j < layer.Neurons.Length; j++) { ActivationNeuron neuron = layer.Neurons[j] as ActivationNeuron; for (int k = 0; k < neuron.Weights.Length; k++) { neuron.Weights[k] = chromosomeGenes[count++]; } neuron.Threshold = chromosomeGenes[count++]; } } }
static void Main(string[] args) { DoubleArrayChromosome weightValues = new DoubleArrayChromosome(new WeightRandomGenerator(), new WeightRandomGenerator(), new WeightRandomGenerator(), 6); Population weightPop = new Population(40, weightValues, new AriesFF(), new EliteSelection()); int counter = 0; bool stopEvo = false; AriesFF fintessEval = new AriesFF(); double error = 0; while (!stopEvo) { weightPop.RunEpoch(); counter++; IChromosome best = weightPop.BestChromosome; error = fintessEval.Evaluate(best); stopEvo = counter > 1000 || error < 0.12; } Console.WriteLine("Stopped after " + counter.ToString()); DoubleArrayChromosome solution = (DoubleArrayChromosome)weightPop.BestChromosome; Console.WriteLine(solution.ToString()); Console.ReadKey(); }
public double Evaluate(IChromosome chromosome) { DoubleArrayChromosome actualChromosome = (DoubleArrayChromosome)chromosome; double x = (double)actualChromosome.Value.GetValue(0); double y = (double)actualChromosome.Value.GetValue(1); double functionResult; switch (selectedFitnessFunction) { case 0: functionResult = Math.Pow(x, 2) * y + 8 * x - x * Math.Pow(y, 2) + 5 * y; break; case 1: functionResult = Math.Pow(x, 2) * y + x * Math.Pow(y, 2) - 2 * x; break; case 2: functionResult = 4 * x + 2 * Math.Pow(y, 2) + x * y; break; case 3: functionResult = Math.Pow(y, 2) + 2 * x * Math.Pow(y, 2) + 3 * x; break; default: functionResult = 0; break; } functionResult = Math.Abs(functionResult); double result = 100 - functionResult; return(result); }
public double Evaluate(IChromosome chromosome) { DoubleArrayChromosome doubleChromosome = (DoubleArrayChromosome)chromosome; string[] s_genes = doubleChromosome.ToString().Split(); double[] d_genes = new double[s_genes.Length]; double sum = 0; for (int i = 0; i < d_genes.Length; i++) { d_genes[i] = Double.Parse(s_genes[i]); } double error = xorSim.getError(d_genes); if (error == 0) { return(0); } else { return(1 / xorSim.getError(d_genes)); } }
public GeneticArtistChromosome(DoubleArrayChromosome source) : base(source) { }
static void Main(string[] args) { NetworkType chromType = GenTypes.ReLU; var prevNeuralBots = new List <NeuroEvolveBot>(); var genValues = FileHandler.GetGenerations(GenTypes.ReLU); var rand = new ZigguratExponentialGenerator(); var Bots = GetBots(chromType, rand); prevNeuralBots.AddRange(Bots); /* * ; * * for (int i = 0; i < largestGen + 1; i++) * { * prevNeuralBots.Add(getBotGen(i, rand, chromType)); * }*/ var bots = new List <IBot> { new DrawBot() }; bots.AddRange(prevNeuralBots); var bestChromeValues = FileHandler.GetGenerations(chromType); DoubleArrayChromosome doubleChromosome = new DoubleArrayChromosome(rand, rand, rand, bestChromeValues[bestChromeValues.Count - 1]); //DoubleArrayChromosome doubleChromosome = (DoubleArrayChromosome)GetChromosomeGen(largestGen, rand, chromType); for (int i = 0; i < 10; i++) { var pop = new Population(200, doubleChromosome, new fitFuncForAdaptable(bots), new RouletteWheelSelection()); Console.WriteLine(pop.FitnessMax); for (int j = 0; j < 10; j++) { pop.RunEpoch(); Console.WriteLine(pop.FitnessMax); Console.WriteLine(pop.FitnessAvg); } var x = new fitFuncForAdaptable(bots).Evaluate(pop.BestChromosome); doubleChromosome = (DoubleArrayChromosome)pop.BestChromosome; var newNet = GetNetHelper.GetNet(doubleChromosome, new[] { 5, 4, 3 }); var newBot = new NeuroEvolveBot(newNet, 934 + i, "newBot" + i.ToString()); var gameRunner = new GameRunnerWithData(); GameData data; foreach (var bot in bots) { data = gameRunner.RunGame(newBot, bot); Console.WriteLine(data); } data = gameRunner.RunGame(newBot, new WaveBot()); Console.WriteLine(data); bots.Add(newBot); } double[] values = doubleChromosome.Value; FileHandler.WriteToLargestGen(chromType, values); RunWaveTest(); }