コード例 #1
1
ファイル: Program.cs プロジェクト: RobMarini/csharpTSP
 static void Main(string[] args)
 {
     var cr = new CityReader();
     int numTours = 30;
     int numTrials = 10000;
     try
     {
         Tour tour = new Tour(cr.readCities(@"C:\Users\Rob\workspace\TravelingSalesman\files\30cities.txt"));
         GeneticAlgorithm mutate = new GeneticAlgorithm();
         GeneticAlgorithm crossover = new GeneticAlgorithm();
         mutate.setAllTours(tour.seed(numTours));
         for (int i = 0; i < numTrials; i++)
         {
             mutate.setAllTours(mutate.GenerateGeneration(true));
         }
         crossover.setAllTours(tour.seed(numTours));
         for (int i = 0; i < numTrials; i++)
         {
             crossover.setAllTours(crossover.GenerateGeneration(true));
         }
         Console.WriteLine("The results from Mutation Genetic Algorithm");
         Console.WriteLine("best distance: " + mutate.getAllTours()[0].getDistance());
         Console.WriteLine("Path: " + mutate.getAllTours()[0].ToString());
         Console.WriteLine("");
         Console.WriteLine("The results from Crossover Genetic Algorithm");
         Console.WriteLine("best distance: " + crossover.getAllTours()[0].getDistance());
         Console.WriteLine("Path: " + crossover.getAllTours()[0].ToString());
     }
     catch (Exception e)
     {
         Console.WriteLine(e.Message);
     }
 }
コード例 #2
0
        static void Main(string[] args)
        { 
            /*
            Func<StringInd> createIndividual;                                 ==> input is nothing, output is a new individual
            Func<StringInd,double> computeFitness;                            ==> input is one individual, output is its fitness
            Func<StringInd[],double[],Func<Tuple<StringInd,StringInd>>> selectTwoParents; ==> input is an array of individuals (population) and an array of corresponding fitnesses, output is a function which (without any input) returns a tuple with two individuals (parents)
            Func<Tuple<StringInd, StringInd>, Tuple<StringInd, StringInd>> crossover;           ==> input is a tuple with two individuals (parents), output is a tuple with two individuals (offspring/children)
            Func<StringInd, double, StringInd> mutation;                            ==> input is one individual and mutation rate, output is the mutated individual
            */

            loadMaxOnesProblem();
            GeneticAlgorithm<IInd> maxOnesProblem = new GeneticAlgorithm<IInd>(0.9, 0.01, true, 30, 10);
            var mOSolution = maxOnesProblem.Run(
                createIndividual,
                computeFitness,
                selectTwoParents,
                crossover,
                mutation);

            Console.WriteLine("Solution MaxOne Problem: ");
            Console.WriteLine(mOSolution);

            loadPregnancyProblem();
            IGeneticAlgorithm<IInd> PregnancyProblem = new PregnancyAlgorithm<IInd>(0.75, 0.05, true, 30, 200); 
            var pSolution = PregnancyProblem.Run(
                createIndividual,
                computeFitness,
                selectTwoParents,
                crossover,
                mutation);

            var tss = PregnancyUtilities.ComputeTSS();
            var sse = PregnancyUtilities.sse;
            var explSos = tss - sse;
            var rSquared = explSos / tss;

            PregnancyUtilities.AddPredictions();

            Console.WriteLine("Total Sum of Squares = " + tss);
            Console.WriteLine("Sum of Squared Error = " + sse);
            Console.WriteLine("Explained Sum of Squares = " + explSos);
            Console.WriteLine("R squared = " + rSquared);

            Console.WriteLine("Solution Pregnancy Problem: ");

            foreach (var x in pSolution.getDoubleArray())
            {
                Console.WriteLine(x);
            }
             
            Console.ReadLine();
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: chasingbob/CatBits
        static void Main(string[] args)
        {
            var fitness = new ShortestPathFitness();

            var ga = new GeneticAlgorithm.GeneticAlgorithm(0.8, 0.05, 100, 1000, 4);
            ga.FitnessFunction = fitness;

            ga.Go();

            double[] best = new double[4];
            var bestFitness = 0.0;
            ga.GetBest(out best, out bestFitness);

            Console.ReadKey();
        }
コード例 #4
0
        /// <summary>
        /// Run the genetic algorithm to train the neural network
        /// </summary>
        private void ExecuteTrainCommand()
        {
            this.ExecuteStopCommand();

            // The background worker allows the GA to be run in a different thread
            BackgroundWorker backgroundWorker = new BackgroundWorker();

            // Setup of the genetic algorithm
            LanderIndividualSettings landerIndividualSettings = new LanderIndividualSettings();
            LanderIndividualFactory landerFactory = new LanderIndividualFactory();
            GeneticAlgorithm.GeneticAlgorithm ga = new GeneticAlgorithm.GeneticAlgorithm(landerFactory);
            LanderIndividual best = null;
            int currentIteration = 0;

            // Set up the ga
            this.environment.Gravity = 2.0;
            this.environment.WindSpeed = 0.1;
            landerIndividualSettings.StartingFuel = 100;
            landerIndividualSettings.StartingHeight = 100;
            landerIndividualSettings.StartingHorizontal = 0;
            landerIndividualSettings.LanderEnvironment = this.environment;
            landerIndividualSettings.CrossoverAlgorithm = LanderIndividualSettings.CrossoverType.OnePoint;
            ga.SelectionType = GeneticAlgorithm.GeneticAlgorithm.SelectionTypes.Tournament;
            ga.TournamentSize = 4;
            ga.CrossoverProbability = 0;
            ga.MutationProbability = 1;
            ga.CalculationLimit = 60000;
            ga.ElitistCount = 4;
            ga.PopulationSize = 100;
            landerFactory.IndividualSettings = landerIndividualSettings;

            // This lambda function handles the iteration events from the ga.
            EventHandler<IterationEventArgs> handler = (sender, args) =>
            {
                backgroundWorker.ReportProgress(0, args);
            };

            // Set the work lambda function.
            backgroundWorker.DoWork += (sender, e) =>
            {

                // Add the iteration event handler to report progress back to the main thread
                ga.IterationEvent += handler;

                // Run the ga
                best = (LanderIndividual)ga.Run(landerIndividualSettings);

                ga.IterationEvent -= handler;

            };

            // Update the graph to show progress
            backgroundWorker.ProgressChanged += (sender, e) =>
            {
                this.MinFitnessValues.Add(new Tuple<int, double>(currentIteration, ((IterationEventArgs)e.UserState).MinFitness));
                this.MaxFitnessValues.Add(new Tuple<int, double>(currentIteration, ((IterationEventArgs)e.UserState).MaxFitness));
                this.AvgFitnessValues.Add(new Tuple<int, double>(currentIteration, ((IterationEventArgs)e.UserState).AverageFitness));
                currentIteration++;

                if (this.MinFitnessValues.Count > 600)
                {
                    this.MinFitnessValues.Clear();
                    this.MaxFitnessValues.Clear();
                    this.AvgFitnessValues.Clear();
                }
            };

            backgroundWorker.RunWorkerCompleted += (sender, e) =>
            {
                this.IsTraining = false;
                // Save the resulting neural network
                this.neuralNetwork = best.CurrentNeuralNetwork;
                Debug.WriteLine(this.neuralNetwork.ToString());
            };

            // Clear out previous chart data and run the background worker
            this.MinFitnessValues.Clear();
            this.MaxFitnessValues.Clear();
            this.AvgFitnessValues.Clear();
            backgroundWorker.WorkerReportsProgress = true;
            this.IsTraining = true;
            backgroundWorker.RunWorkerAsync();
        }
コード例 #5
0
ファイル: Program.cs プロジェクト: josharmstrong08/Lander
        private static double Train(bool showOutput)
        {
            LanderIndividualSettings landerIndividualSettings = new LanderIndividualSettings();
            LanderIndividualFactory landerFactory = new LanderIndividualFactory();
            GeneticAlgorithm ga = new GeneticAlgorithm(landerFactory);
            LanderIndividual best = null;
            int currentIteration = 0;
            double bestfitness = 0;

            // Set up the ga
            LanderSimulator.Model.Environment environment = new LanderSimulator.Model.Environment();
            environment.Gravity = 2.0;
            environment.WindSpeed = 0.1;
            landerIndividualSettings.StartingFuel = 100;
            landerIndividualSettings.StartingHeight = 100;
            landerIndividualSettings.StartingHorizontal = 0;
            landerIndividualSettings.LanderEnvironment = environment;
            landerIndividualSettings.CrossoverAlgorithm = LanderIndividualSettings.CrossoverType.Uniform;
            ga.SelectionType = GeneticAlgorithm.SelectionTypes.Tournament;
            ga.TournamentSize = 5;
            ga.CrossoverProbability = 0.98;
            ga.MutationProbability = 1;
            ga.CalculationLimit = 60000;
            ga.ElitistCount = 10;
            ga.PopulationSize = 500;
            landerFactory.IndividualSettings = landerIndividualSettings;

            // This lambda function handles the iteration events from the ga.
            EventHandler<IterationEventArgs> handler = (sender, args) =>
            {
                if (showOutput)
                {
                    Console.CursorLeft = 0;
                    Console.Write("{0,4:g}{1,12:f3}{2,12:f3}{3,12:f3}{4,12:f3}{5,12:f3}{6,12:f3}",
                        currentIteration,
                        args.MinFitness, args.AverageFitness, args.MaxFitness,
                        args.MinDifference, args.AverageDifference, args.MaxDifference);
                }

                currentIteration++;
                bestfitness = args.MinFitness;
            };

            ga.IterationEvent += handler;

            if (showOutput)
            {
                Console.WriteLine("{0,4}{1,12}{2,12}{3,12}{4,12}{5,12}{6,12}",
                "", "Min Fit", "Avg Fit", "Max Fit",
                "Min Dif", "Avg Dif", "Max Dif");
            }

            // Run the ga
            best = (LanderIndividual)ga.Run(landerIndividualSettings);
            Console.WriteLine();

            neuralNetwork.SetAllWeights(best.CurrentNeuralNetwork.GetAllWeights());

            ga.IterationEvent -= handler;

            return bestfitness;
        }
コード例 #6
0
 void Start()
 {
     Rng      = new System.Random();
     genetics = new GeneticAlgorithm <char>(populationSize, maxInputs, Rng, GetRandomCharacter, FitnessFunction, mutationRate);
 }
コード例 #7
0
        static void Main(string[] args)
        {
            const int    populationSize = 10;
            const int    maxIterations  = 100;
            const double crossoverRate  = 0.8;
            const double mutationRate   = 0.3;
            const bool   elitism        = true;

            /* FUNCTIONS TO DEFINE (for each problem):
             * Func<Ind> createIndividual;                                 ==> input is nothing, output is a new individual
             * Func<Ind,double> computeFitness;                            ==> input is one individual, output is its fitness
             * Func<Ind[],double[],Func<Tuple<Ind,Ind>>> selectTwoParents; ==> input is an array of individuals (population) and an array of corresponding fitnesses, output is a function which (without any input) returns a tuple with two individuals (parents)
             * Func<Tuple<Ind, Ind>, Tuple<Ind, Ind>> crossover;           ==> input is a tuple with two individuals (parents), output is a tuple with two individuals (offspring/children)
             * Func<Ind, double, Ind> mutation;                            ==> input is one individual and mutation rate, output is the mutated individual
             */

            Func <Binary> createIndividual = delegate() { return(new Binary(5, r.Next(0, 31))); };

            Func <Binary, double> computeFitness = delegate(Binary i) {
                int    value   = i.ToInt();
                double fitness = -Math.Pow(value, 2) + 7 * value;

                return(fitness);
            };

            Func <Binary[], double[], Func <Tuple <Binary, Binary> > > selectTwoParents = delegate(Binary[] individuals, double[] fitnesses) {
                var        indis        = individuals;
                var        fit          = fitnesses;
                List <int> indexes      = new List <int>();
                var        totalFitness = fitnesses.Sum();

                var index = 0;
                while (indexes.Count < 2)
                {
                    if (r.Next(0, 100) > (fitnesses[index] / totalFitness) * 100)
                    {
                        indexes.Add(index);
                    }
                    index++;
                    if (index >= fitnesses.Length - 1)
                    {
                        index = 0;
                    }
                }

                return(new Func <Tuple <Binary, Binary> > (() => new Tuple <Binary, Binary>(indis[indexes[0]], indis[indexes[1]])));
            };

            Func <Tuple <Binary, Binary>, Tuple <Binary, Binary> > crossover = delegate(Tuple <Binary, Binary> t) {
                var half    = t.Item1.Size / 2;
                var parnew1 = t.Item1.GetSubArray(0, half).Add(t.Item2.GetSubArray(half + 1, t.Item2.Size - 1));
                var parnew2 = t.Item2.GetSubArray(0, half).Add(t.Item1.GetSubArray(half + 1, t.Item1.Size - 1));


                return(new Tuple <Binary, Binary>(new Binary(parnew1), new Binary(parnew2)));
            };

            Func <Binary, double, Binary> mutation = delegate(Binary i, double d) {
                if (r.Next(0, 100) > (1 - d) * 100)
                {
                    i.Mutate(r.Next(0, i.Size - 1));
                }

                return(i);
            };

            GeneticAlgorithm <Binary> fakeProblemGA = new GeneticAlgorithm <Binary>(crossoverRate, mutationRate, elitism, populationSize, maxIterations); // CHANGE THE GENERIC TYPE (NOW IT'S INT AS AN EXAMPLE) AND THE PARAMETERS VALUES
            var solution = fakeProblemGA.Run(createIndividual, computeFitness, selectTwoParents, crossover, mutation);

            Console.WriteLine("Solution: ");
            Console.WriteLine(solution.ToString());
            Console.WriteLine(solution.ToInt());
            //    for(int i = 0; i < 100; i++) {
            //        Console.WriteLine(r.Next(0, 31));
            //    }

            // var ind1 = createIndividual();
            // var ind2 = createIndividual();
            // Ind[] ind = new Ind[5] {
            // new Ind(new int[5] {1, 0, 1, 1, 0}),
            // new Ind(new int[5] {1, 1, 1, 0, 0}),
            // new Ind(new int[5] {1, 0, 0, 1, 0}),
            // new Ind(new int[5] {1, 0, 0, 0, 0}),
            // new Ind(new int[5] {0, 0, 1, 0, 1}),
            // };
            // double[] fitnes = new double[5];

            // for(int i = 0; i < 5; i++) {
            //     fitnes[i] = computeFitness(ind[i]);
            // }
            // var parents = new Tuple<Ind, Ind>(ind1, ind2);
            // var TwoParents = selectTwoParents(ind, fitnes)();

            // Console.WriteLine("create test: " + ind1.ToString() + " ][ " + ind1.ToInt());
            // Console.WriteLine("--------------------------------");
            // Console.WriteLine("Fitness test: " + computeFitness(ind1));
            // Console.WriteLine("--------------------------------");
            // Console.WriteLine("Parent1: " + parents.Item1.ToString() + " _ Parent2: " + parents.Item2.ToString());
            // Console.WriteLine("crossover: new par1: " + crossover(parents).Item1.ToString() + " _ new par2: " + crossover(parents).Item2.ToString() );
            // Console.WriteLine("--------------------------------");
            // Console.WriteLine("Before mutation: " + ind1.ToString() + " After mutation: " + mutation(ind1, 1).ToString());
            // Console.WriteLine("--------------------------------");
            // Console.WriteLine("Select parents: " +  TwoParents.Item1.ToString() + " " + TwoParents.Item2.ToString());
            // Console.WriteLine("With values: " +  TwoParents.Item1.ToInt() + " " + TwoParents.Item2.ToInt());

            // for(int i = 0; i < 5; i++) {
            //     Console.WriteLine(computeFitness(ind[i]));
            // }
        }