/// <summary> /// Construct a method genetic algorithm. /// </summary> /// <param name="phenotypeFactory">The phenotype factory.</param> /// <param name="calculateScore">The score calculation object.</param> /// <param name="populationSize">The population size.</param> public MLMethodGeneticAlgorithm(MLMethodGenomeFactory.CreateMethod phenotypeFactory, ICalculateScore calculateScore, int populationSize) : base(TrainingImplementationType.Iterative) { // create the population IPopulation population = new BasicPopulation(populationSize, null); population.GenomeFactory = new MLMethodGenomeFactory(phenotypeFactory, population); ISpecies defaultSpecies = population.CreateSpecies(); for (int i = 0; i < population.PopulationSize; i++) { IMLEncodable chromosomeNetwork = (IMLEncodable)phenotypeFactory(); MLMethodGenome genome = new MLMethodGenome(chromosomeNetwork); defaultSpecies.Add(genome); } defaultSpecies.Leader = defaultSpecies.Members[0]; // create the trainer this.genetic = new MLMethodGeneticAlgorithmHelper(population, calculateScore); this.genetic.CODEC = new MLEncodableCODEC(); IGenomeComparer comp = null; if (calculateScore.ShouldMinimize) { comp = new MinimizeScoreComp(); } else { comp = new MaximizeScoreComp(); } this.genetic.BestComparer = comp; this.genetic.SelectionComparer = comp; // create the operators int s = Math .Max(defaultSpecies.Members[0].Size / 5, 1); Genetic.Population = population; this.genetic.AddOperation(0.9, new Splice(s)); this.genetic.AddOperation(0.1, new MutatePerturb(1.0)); }
/// <summary> /// Construct an EA. /// </summary> /// <param name="thePopulation">The population.</param> /// <param name="theScoreFunction">The score function.</param> public BasicEA(IPopulation thePopulation, ICalculateScore theScoreFunction) { RandomNumberFactory = EncogFramework.Instance.RandomFactory.FactorFactory(); EliteRate = 0.3; MaxTries = 5; MaxOperationErrors = 500; CODEC = new GenomeAsPhenomeCODEC(); Population = thePopulation; ScoreFunction = theScoreFunction; Selection = new TournamentSelection(this, 4); Rules = new BasicRuleHolder(); // set the score compare method if (theScoreFunction.ShouldMinimize) { SelectionComparer = new MinimizeAdjustedScoreComp(); BestComparer = new MinimizeScoreComp(); } else { SelectionComparer = new MaximizeAdjustedScoreComp(); BestComparer = new MaximizeScoreComp(); } // set the iteration foreach (ISpecies species in thePopulation.Species) { foreach (IGenome genome in species.Members) { IterationNumber = Math.Max(IterationNumber, genome.BirthGeneration); } } // Set a best genome, just so it is not null. // We won't know the true best genome until the first iteration. if (Population.Species.Count > 0 && Population.Species[0].Members.Count > 0) { BestGenome = Population.Species[0].Members[0]; } }