public GeneticAlgorithmOld(int populationSize, int generation, GenomeOld[] population) { this.populationSize = populationSize; this.generation = generation; this.population = population; initialize(); }
public GeneticAlgorithmOld(int populationSize, int numInputs, int numOutputs, int numLayers, int numNeuronsPerLayer) { this.populationSize = populationSize; population = new GenomeOld[populationSize]; for (int currGenome = 0; currGenome < populationSize; ++currGenome) { population[currGenome] = new GenomeOld(NeuralNet.createRandomWeights(numInputs, numOutputs, numLayers, numNeuronsPerLayer)); } generation = 0; initialize(); }
//Create a new population selecting and crossing genomes of the previous population. private void createNewPopulation() { //Sort the population by fitness. Array.Sort(population); //Save the fittests genome mostFit = new GenomeOld(population[0]); //Create a new population. GenomeOld[] newPopulation = new GenomeOld[populationSize]; //Save the top genomes from the previous population. int keepBestNum = 5; elitism(newPopulation, keepBestNum); //Crossover until new population is full. for (int currGenome = keepBestNum; currGenome < populationSize; ++currGenome) { //Select two parents at random through a roulette wheel and cross them. GenomeOld[] children = GenomeOld.singlePointCrossover(rouletteWheelSelection(), rouletteWheelSelection(), crossoverRate); //Add first child to the population and mutate. newPopulation[currGenome] = children[0]; newPopulation[currGenome].mutate(mutationRate); ++currGenome; //If population is not full, add second child and mutate. if(currGenome < populationSize) { newPopulation[currGenome] = children[1]; newPopulation[currGenome].mutate(mutationRate); } } //Save over old population. population = newPopulation; }
//Save the top genomes from the previous population into the new population. private void elitism(GenomeOld[] newPopulation, int topBest) { string fittest = ""; for (int currBest = 0; currBest < topBest; ++currBest) { fittest += population[currBest].fitness +" "; newPopulation[currBest] = new GenomeOld(population[currBest]); } Debug.Log ("Saving these fitness values: "+fittest); }
//Create a population from a string. //Used in loading public static GeneticAlgorithmOld loadPopulationFromString(string contents) { char[] separators1 = new char[1]; separators1[0] = separator; string[] c = contents.Split(separators1); char[] separators2 = new char[1]; separators2[0] = '\n'; string[] init = c[0].Split(separators2); int populationSize = Convert.ToInt32(init[0]); int generationNumber = Convert.ToInt32(init[1]); GenomeOld[] population = new GenomeOld[populationSize]; for (int currGenome = 0; currGenome < populationSize; ++currGenome) { population[currGenome] = new GenomeOld(GenomeOld.createWeightsFromString(c[1+currGenome].Split(separators2))); } return new GeneticAlgorithmOld(populationSize, generationNumber, population); }