Пример #1
0
        private static void Main(string[] args)
        {
            var population = InitialPopulation();
            int iteration  = 0;

            Chromosome best = FindBest(population);

            while (iteration < MaxIteration && best.Cost > StopCondition)
            {
                iteration++;
                var newPopulation = new List <Chromosome>();
                newPopulation.AddRange(population.OrderBy(c => c.Cost).Take(Elitism));

                while (newPopulation.Count < PopulationSize)
                {
                    var(a, b) = Selection.Select(population);
                    Chromosome c = Crossover.Crossover(a, b);
                    Mutation.Mutate(c);
                    Evaluator.Evaluate(c);
                    newPopulation.Add(c);
                }
                population = newPopulation;

                best = FindBest(population);
                Console.WriteLine("Iteration: " + iteration + " - " + best.Cost);
            }

            Console.WriteLine(" ----- ");
            Console.WriteLine(best);
            Console.WriteLine(" ----- ");
            Console.WriteLine("Error: " + Evaluator.FinalError(best));
            Console.ReadKey();
        }
Пример #2
0
        static Population AdvanceGeneration(Population population, ISelection selection, ICrossover crossover, IMutation mutation)
        {
            var chromosomes = new List<Chromosome>();
            population = new Population(population.Take((int)(truncationRate * population.Count()))); // TRUNCATION
            chromosomes.AddRange(population.Take((int)(elitismRate * chromosomeCount)));  //ELITE (assuming that the chromosomes in the population are sorted by fitness (the fitter are at the top of the list)

            do
            {
                Chromosome chosen1 = selection.Select(population),
                           chosen2 = selection.Select(population);

                if (random.NextDouble() < crossoverRate)
                {
                    var children = crossover.Crossover(chosen1, chosen2); // CROSSOVER
                    chosen1 = children.Item1;
                    chosen2 = children.Item2;
                }

                if (random.NextDouble() < mutationRate)
                {
                    chosen1 = mutation.Mutate(chosen1); // MUTATION
                }

                if (random.NextDouble() < mutationRate)
                {
                    chosen2 = mutation.Mutate(chosen2); // MUTATION
                }

                chromosomes.Add(chosen1);
                chromosomes.Add(chosen2);
            } while (chromosomes.Count < chromosomeCount);

            return new Population(chromosomes);
        }
Пример #3
0
        private static void Main(string[] args)
        {
            var population = InitialPopulation();
            int iteration  = 0;

            Chromosome best = FindBest(population);

            while (iteration < MaxIteration && best.Cost > StopCondition)
            {
                iteration++;

                var(a, b) = Selection.Select(population, out var toKill);
                Chromosome c = Crossover.Crossover(a, b);
                Mutation.Mutate(c);

                for (int i = 0; i < ChromosomeSize; ++i)
                {
                    toKill[i] = c[i];
                }
                Evaluator.Evaluate(toKill);

                best = FindBest(population);
                if (iteration % 100 == 0)
                {
                    Console.WriteLine("Iteration: " + iteration + " - " + best.Cost);
                }
            }

            Console.WriteLine(" ----- ");
            Console.WriteLine(best);

            Console.ReadKey();
        }
Пример #4
0
        private void Evolve()
        {
            _currentSession.GenerationCount++;

            // Select parts of the population to preserve and not mutate
            var preservedPopulation = _preservationSelection.Select(_currentSession.CurrentPopulation);

            // Select parents which will create children
            var parents = _parentSelection.Select(_currentSession.CurrentPopulation);

            // Crossover (ie, create children from the selected parents)
            var children = _crossover.Crossover(parents);

            // Mutate the children (This sounds horribly, but this isn't real. It's just a genetic algorithm with bits and bytes...
            _mutation.Mutate(children);

            // Create a new population with the preserved population and all the new children
            var newPopulation = new List <Chromosome <TGeneSequence> >(preservedPopulation);

            newPopulation.AddRange(children);

            _currentSession.CurrentPopulation = newPopulation;

            // Calculate the fitness score for the current population
            CalculateFitness();
        }
Пример #5
0
 public void Procreate(List <int> child, ISelector selector, Random random)
 {
     crossover.Crossover(child, selector.Select(random).Chromosome, selector.Select(random).Chromosome, random);
     //child.AddRange(selector.Select(random).Chromosome);
     if (mutationRate == 1.0 || random.NextDouble() < mutationRate)
     {
         mutator.Mutate(child, random);
     }
 }
Пример #6
0
        public Genotype ProduceOffspring(ICrossover crossover)
        {
            // Truncate lower 20%
            var candidates = this.OrderByDescending(pt => pt.AdjustedFitness)
                             .Take(Mathf.CeilToInt(this.Count * 0.8f))
                             .ToList();

            // Tournament selection
            var parent1 = candidates[Random.Range(0, candidates.Count)];
            var parent2 = candidates.Sample(2)
                          .OrderByDescending(pt => pt.AdjustedFitness)
                          .First();

            return(crossover.Crossover(parent1, parent2));
        }
Пример #7
0
        public void Main()
        {
            // Main loop
            List <Seed> population = GeneratePopulation(size);

            selection = new RouletteSelection();
            crossover = new SinglePointCrossover(population.First().attributes.Count / 2, crossoverRate);
            Seed elite;

            for (int i = 0; i < population.Count; i++)
            {
                population[i].fitness = Fitness(population[i]);
            }

            for (int i = 0; i < k; i++)
            {
                population = population.OrderBy(x => x.fitness).ToList();                         // sort
                elite      = new Seed(population.First().attributes, population.First().fitness); // elitism
                population = selection.Selection(population);                                     // selection

                for (int j = 0; j < population.Count; j += 2)                                     // crossover
                {
                    Tuple <Seed, Seed> children = crossover.Crossover(population[j], population[j + 1]);
                    population[j]     = children.Item1;
                    population[j + 1] = children.Item2;
                }

                for (int j = 0; j < population.Count; j++) // mutate
                {
                    population[j] = Mutate(population[j]);
                }

                for (int j = 0; j < population.Count; j++) // recalculate fitness
                {
                    population[j].fitness = Fitness(population[j]);
                }

                population = population.OrderBy(x => x.fitness).ToList(); // sort again
                population[population.Count - 1] = elite;                 // replace the worst seed
                //Console.WriteLine("elite = " + elite.fitness + ", fitness = " + population.OrderBy(x => x.fitness).ToList().First().fitness);
            }

            if (topSeed == null || topSeed.fitness < population.OrderBy(x => x.fitness).ToList().First().fitness)
            {
                topSeed = new Seed(population.OrderBy(x => x.fitness).ToList().First().attributes, population.OrderBy(x => x.fitness).ToList().First().fitness);
            }
        }
Пример #8
0
        private void NextGeneration()
        {
            var newGeneration = new List <Tour>();

            for (var i = 0; i < populationSize; i += 2)
            {
                var selection1 = selection.Selection(populations, distances);
                var selection2 = selection.Selection(populations, distances);
                var aux        = crossover.Crossover(selection1, selection2);

                Mutation(aux);

                aux.GetDistance(distances);
                newGeneration.Add(aux);
            }

            SetBest(newGeneration);
        }
Пример #9
0
        private void InnerLoop(int n)
        {
            List <Seed> newGeneration = initialSeeds;

            for (int iterations = 0; iterations < n; iterations++)
            {
                List <Seed> selectedSeeds = selection.Select(newGeneration);
                //Console.WriteLine("The average SSE of generation: " + iterations);
                Console.WriteLine(selectedSeeds.Average(seed => seed.GetSSE()));
                for (int i = 0; i < selectedSeeds.Count - 1; i += 2)
                {
                    Tuple <Seed, Seed> children = crossover.Crossover(selectedSeeds[i], selectedSeeds[i + 1]);
                    currentSeeds.Add(children.Item1);
                    currentSeeds.Add(children.Item2);
                }

                for (int i = 0; i < currentSeeds.Count; i++)
                {
                    mutation.Mutate(currentSeeds[i]);
                }
                for (int i = 0; i < currentSeeds.Count; i++)
                {
                    List <double> predictions = fitnessEvaluator.GeneratePredictions(currentSeeds[i]);
                    currentSeeds[i].SetSSE(fitnessEvaluator.EvaluateFitness(predictions));
                }
                // Console.WriteLine("The lowest SSE of generation: " + iterations);
                //Console.WriteLine(currentSeeds.Min(seed => seed.GetSSE()));
                newGeneration = elitism.Preserve(currentSeeds);
                currentSeeds  = new List <Seed>();
            }
            List <double> list = new List <double>()
            {
                1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1
            };

            /*List<double> coefficients = new List<double>() { -0.1, -0.03, -0.03, -0.01, 0.22, -0.27, -0.24, 0.35, 0.29, 0.33, 0.19, 0.23, 0.15, 0.16, -0.16, 0.16, 0.19, -0.21, -0.24, 0.48 };
             * Prediction prediction = new Prediction(new Seed(coefficients), list);*/
            Prediction prediction = new Prediction(elitism.GetBestSeed(), list);

            prediction.Predict();
        }