コード例 #1
0
        /// <inheritdoc />
        public int PerformSelection(Random rnd, ISpecies species)
        {
            int     bestIndex = rnd.Next(species.Members.Count);
            IGenome best      = species.Members[bestIndex];

            BasicEA.CalculateScoreAdjustment(best, Trainer.ScoreAdjusters);

            for (int i = 0; i < Rounds; i++)
            {
                int     competitorIndex = rnd.Next(species.Members.Count - 1);
                IGenome competitor      = species.Members[competitorIndex];

                // only evaluate valid genomes
                if (!Double.IsInfinity(competitor.AdjustedScore) &&
                    !Double.IsNaN(competitor.AdjustedScore))
                {
                    BasicEA.CalculateScoreAdjustment(competitor,
                                                     Trainer.ScoreAdjusters);
                    if (Trainer.SelectionComparer.IsBetterThan(
                            competitor, best))
                    {
                        best      = competitor;
                        bestIndex = competitorIndex;
                    }
                }
            }
            return(bestIndex);
        }
コード例 #2
0
        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {
            pop          = InitPopulation();
            score        = new PlantScore();
            this.genetic = new BasicEA(pop, score);

            //this.genetic.Speciation = new ArraySpeciation<DoubleArrayGenome>();

            genetic.AddOperation(0.9, new Splice(PlantUniverse.GenomeSize / 3));
            genetic.AddOperation(0.1, new MutatePerturb(0.1));

            // Display

            this.universe = new PlantUniverse();
            this.universe.Reset();


            DoubleArrayGenome bestGenome = (DoubleArrayGenome)genetic.BestGenome;
            PlantPhysics      physics    = new PlantPhysics();
            PlantGrowth       growth     = new PlantGrowth();

            for (int i = 0; i < 100; i++)
            {
                physics.RunPhysics(universe);
                growth.RunGrowth(universe, bestGenome.Data);
            }

            this.display          = new DisplayPlant(CanvasOutput);
            this.display.Universe = this.universe;
            Thread t = new Thread(DoWork);

            t.Start();
        }
コード例 #3
0
        /// <inheritdoc />
        public int PerformAntiSelection(Random rnd, ISpecies species)
        {
            int     worstIndex = rnd.Next(species.Members.Count);
            IGenome worst      = species.Members[worstIndex];

            BasicEA.CalculateScoreAdjustment(worst,
                                             Trainer.ScoreAdjusters);

            for (int i = 0; i < Rounds; i++)
            {
                int     competitorIndex = rnd.Next(species.Members.Count - 1);
                IGenome competitor      = species.Members[competitorIndex];

                // force an invalid genome to lose
                if (Double.IsInfinity(competitor.AdjustedScore) ||
                    Double.IsNaN(competitor.AdjustedScore))
                {
                    return(competitorIndex);
                }

                BasicEA.CalculateScoreAdjustment(competitor,
                                                 Trainer.ScoreAdjusters);
                if (!Trainer.SelectionComparer.IsBetterThan(competitor,
                                                            worst))
                {
                    worst      = competitor;
                    worstIndex = competitorIndex;
                }
            }
            return(worstIndex);
        }
コード例 #4
0
        /// <summary>
        ///     Run the example.
        /// </summary>
        public void Process()
        {
            // read the iris data from the resources
            Assembly assembly = Assembly.GetExecutingAssembly();
            Stream   res      = assembly.GetManifestResourceStream("AIFH_Vol2.Resources.iris.csv");

            // did we fail to read the resouce
            if (res == null)
            {
                Console.WriteLine("Can't read iris data from embedded resources.");
                return;
            }

            // load the data
            var     istream = new StreamReader(res);
            DataSet ds      = DataSet.Load(istream);

            istream.Close();

            IGenerateRandom rnd = new MersenneTwisterGenerateRandom();


            // The following ranges are setup for the Iris data set.  If you wish to normalize other files you will
            // need to modify the below function calls other files.
            ds.NormalizeRange(0, -1, 1);
            ds.NormalizeRange(1, -1, 1);
            ds.NormalizeRange(2, -1, 1);
            ds.NormalizeRange(3, -1, 1);
            IDictionary <string, int> species = ds.EncodeOneOfN(4);

            istream.Close();

            var codec = new RBFNetworkGenomeCODEC(4, RbfCount, 3);

            IList <BasicData> trainingData = ds.ExtractSupervised(0,
                                                                  codec.InputCount, 4, codec.OutputCount);

            IPopulation pop = InitPopulation(rnd, codec);

            IScoreFunction score = new ScoreRegressionData(trainingData);

            var genetic = new BasicEA(pop, score)
            {
                CODEC = codec
            };

            genetic.AddOperation(0.7, new Splice(codec.Size / 3));
            genetic.AddOperation(0.3, new MutatePerturb(0.1));


            PerformIterations(genetic, 100000, 0.05, true);

            var winner = (RBFNetwork)codec.Decode(genetic.BestGenome);

            QueryOneOfN(winner, trainingData, species);
        }
コード例 #5
0
        /// <summary>
        ///     Setup and solve the TSP.
        /// </summary>
        public void Solve()
        {
            IGenerateRandom rnd     = new MersenneTwisterGenerateRandom();
            var             builder = new StringBuilder();

            InitCities(rnd);

            IPopulation pop = InitPopulation(rnd);

            IScoreFunction score = new TSPScore(_cities);

            _genetic = new BasicEA(pop, score);

            _genetic.AddOperation(0.9, new SpliceNoRepeat(Cities / 3));
            _genetic.AddOperation(0.1, new MutateShuffle());

            int    sameSolutionCount = 0;
            int    iteration         = 1;
            double lastSolution      = double.MaxValue;

            while (sameSolutionCount < MaxSameSolution)
            {
                _genetic.Iteration();

                double thisSolution = _genetic.LastError;

                builder.Length = 0;
                builder.Append("Iteration: ");
                builder.Append(iteration++);
                builder.Append(", Best Path Length = ");
                builder.Append(thisSolution);

                Console.WriteLine(builder.ToString());

                if (Math.Abs(lastSolution - thisSolution) < 1.0)
                {
                    sameSolutionCount++;
                }
                else
                {
                    sameSolutionCount = 0;
                }

                lastSolution = thisSolution;
            }

            Console.WriteLine("Good solution found:");
            var best = (IntegerArrayGenome)_genetic.BestGenome;

            DisplaySolution(best);
            _genetic.FinishTraining();
        }
コード例 #6
0
        /// <summary>
        ///     Demonstrate the crossover splice operator.  Two offspring will be created by swapping three
        ///     segments of the parents (two cut points). Some genes may repeat.
        /// </summary>
        public static void Splice()
        {
            Console.WriteLine("Crossover Splice");

            // Create a random number generator
            IGenerateRandom rnd = new MersenneTwisterGenerateRandom();

            // Create a new population.
            IPopulation pop = new BasicPopulation();

            pop.GenomeFactory = new IntegerArrayGenomeFactory(10);

            // Create a trainer with a very simple score function.  We do not care
            // about the calculation of the score, as they will never be calculated.
            IEvolutionaryAlgorithm train = new BasicEA(pop, new NullScore());

            // Create a splice operator, length = 5.  Use it 1.0 (100%) of the time.
            var opp = new Splice(5);

            train.AddOperation(1.0, opp);

            // Create two parents, the genes are set to 1,2,3,4,5,7,8,9,10
            // and 10,9,8,7,6,5,4,3,2,1.
            var parents = new IntegerArrayGenome[2];

            parents[0] = (IntegerArrayGenome)pop.GenomeFactory.Factor();
            parents[1] = (IntegerArrayGenome)pop.GenomeFactory.Factor();
            for (int i = 1; i <= 10; i++)
            {
                parents[0].Data[i - 1] = i;
                parents[1].Data[i - 1] = 11 - i;
            }

            // Create an array to hold the offspring.
            var offspring = new IntegerArrayGenome[2];

            // Perform the operation
            opp.PerformOperation(rnd, parents, 0, offspring, 0);

            // Display the results
            Console.WriteLine("Parent 1: " + string.Join(",", parents[0].Data));
            Console.WriteLine("Parent 2: " + string.Join(",", parents[1].Data));
            Console.WriteLine("Offspring 1: " + string.Join(",", offspring[0].Data));
            Console.WriteLine("Offspring 2: " + string.Join(",",
                                                            offspring[1].Data));
        }
コード例 #7
0
        /// <summary>
        ///  Demonstrate the mutate peterb operator.  An offspring will be created by randomly changing each
        /// gene.
        /// </summary>
        public static void MutatePeterb()
        {
            Console.WriteLine("Mutate Perturb");

            IGenerateRandom rnd = new MersenneTwisterGenerateRandom();

            // Create a new population.
            IPopulation pop = new BasicPopulation();

            pop.GenomeFactory = new DoubleArrayGenomeFactory(5);

            // Create a trainer with a very simple score function.  We do not care
            // about the calculation of the score, as they will never be calculated.
            IEvolutionaryAlgorithm train = new BasicEA(pop, new NullScore());


            var opp = new MutatePerturb(0.1);

            train.AddOperation(1.0, opp);


            // Create a peterb operator.  Use it 1.0 (100%) of the time.
            var parents = new DoubleArrayGenome[1];

            parents[0]            = (DoubleArrayGenome)pop.GenomeFactory.Factor();
            parents[0].Population = pop;

            for (int i = 1; i <= 5; i++)
            {
                parents[0].Data[i - 1] = i;
            }

            // Create an array to hold the offspring.
            var offspring = new DoubleArrayGenome[1];

            offspring[0] = new DoubleArrayGenome(5);

            // Perform the operation
            opp.PerformOperation(rnd, parents, 0, offspring, 0);

            // Display the results
            Console.WriteLine("Parent: " + string.Join(",", parents[0].Data));
            Console.WriteLine("Offspring: " + string.Join(",", offspring[0].Data));
        }
コード例 #8
0
        /// <summary>
        ///     Perform the task.
        /// </summary>
        public void PerformTask()
        {
            IMLMethod phenotype = owner.CODEC.Decode(genome);

            if (phenotype != null)
            {
                double score;
                try
                {
                    score = scoreFunction.CalculateScore(phenotype);
                }
                catch (EARuntimeError e)
                {
                    score = Double.NaN;
                }
                genome.Score         = score;
                genome.AdjustedScore = score;
                BasicEA.CalculateScoreAdjustment(genome, adjusters);
            }
        }
コード例 #9
0
        /// <summary>
        ///     The entry point for this example.  If you would like to make this example
        ///     stand alone, then add to its own project and rename to Main.
        /// </summary>
        /// <param name="args">Not used.</param>
        public static void ExampleMain(string[] args)
        {
            // Create a new population.
            IPopulation pop     = new BasicPopulation();
            ISpecies    species = pop.CreateSpecies();

            // Create 1000 genomes, assign the score to be the index number.
            for (int i = 0; i < 1000; i++)
            {
                IGenome genome = new IntegerArrayGenome(1);
                genome.Score         = i;
                genome.AdjustedScore = i;
                pop.Species[0].Add(genome);
            }

            IGenerateRandom rnd = new MersenneTwisterGenerateRandom();

            // Create a trainer with a very simple score function.  We do not care
            // about the calculation of the score, as they will never be calculated.
            // We only care that we are maximizing.
            IEvolutionaryAlgorithm train = new BasicEA(pop, new NullScore());

            // Perform the test for round counts between 1 and 10.
            for (int roundCount = 1; roundCount <= 10; roundCount++)
            {
                var selection = new TournamentSelection(train, roundCount);
                int sum       = 0;
                int count     = 0;
                for (int i = 0; i < 100000; i++)
                {
                    int     genomeID = selection.PerformSelection(rnd, species);
                    IGenome genome   = species.Members[genomeID];
                    sum += (int)genome.AdjustedScore;
                    count++;
                }
                sum /= count;
                Console.WriteLine("Rounds: " + roundCount + ", Avg Score: " + sum);
            }
        }
コード例 #10
0
        /// <summary>
        ///     Process the specified file.
        /// </summary>
        /// <param name="filename">The filename to process.</param>
        public void Process(String filename)
        {
            // read the data from the resources
            Assembly assembly = Assembly.GetExecutingAssembly();
            Stream   res      = assembly.GetManifestResourceStream("AIFH_Vol2.Resources.simple-poly.csv");

            // did we fail to read the resouce
            if (res == null)
            {
                Console.WriteLine("Can't read iris data from embedded resources.");
                return;
            }

            // load the data
            var     istream = new StreamReader(res);
            DataSet ds      = DataSet.Load(istream);

            istream.Close();


            // Extract supervised training.
            IList <BasicData> training = ds.ExtractSupervised(0, 1, 1, 1);


            IGenerateRandom rnd   = new MersenneTwisterGenerateRandom();
            var             eval  = new EvaluateExpression(rnd);
            IPopulation     pop   = InitPopulation(rnd, eval);
            IScoreFunction  score = new ScoreSmallExpression(training, 30);

            IEvolutionaryAlgorithm genetic = new BasicEA(pop, score);

            genetic.AddOperation(0.3, new MutateTree(3));
            genetic.AddOperation(0.7, new CrossoverTree());
            genetic.ShouldIgnoreExceptions = false;


            int    sameSolutionCount = 0;
            int    iteration         = 1;
            double lastSolution      = double.MaxValue;
            var    builder           = new StringBuilder();

            while (sameSolutionCount < MaxSameSolution && iteration < 1000)
            {
                genetic.Iteration();

                double thisSolution = genetic.LastError;

                builder.Length = 0;
                builder.Append("Iteration: ");
                builder.Append(iteration++);
                builder.Append(", Current error = ");
                builder.Append(thisSolution);
                builder.Append(", Best Solution Length = ");
                builder.Append(genetic.BestGenome.Count);

                Console.WriteLine(builder.ToString());

                if (Math.Abs(lastSolution - thisSolution) < 1.0)
                {
                    sameSolutionCount++;
                }
                else
                {
                    sameSolutionCount = 0;
                }

                lastSolution = thisSolution;
            }

            Console.WriteLine("Good solution found:");
            var best = (TreeGenome)genetic.BestGenome;

            Console.WriteLine(eval.DisplayExpressionNormal(best.Root));
            genetic.FinishTraining();
        }