Esempio n. 1
0
        /// <summary>
        /// Setup and solve the TSP.
        /// </summary>
        public void Execute(IExampleInterface app)
        {
            this.app = app;

            var builder = new StringBuilder();

            initCities();

            IPopulation pop = initPopulation();
		
		ICalculateScore score =  new TSPScore(cities);

		genetic = new TrainEA(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 < MAX_SAME_SOLUTION) {
			genetic.Iteration();

			double thisSolution = genetic.Error;

			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:");
		displaySolution();
		genetic.FinishTraining();
        }
        /// <summary>
        /// Create an EPL GA trainer.
        /// </summary>
        /// <param name="method">The method to use.</param>
        /// <param name="training">The training data to use.</param>
        /// <param name="argsStr">The arguments to use.</param>
        /// <returns>The newly created trainer.</returns>
        public IMLTrain Create(IMLMethod method,
                IMLDataSet training, String argsStr)
        {
            PrgPopulation pop = (PrgPopulation)method;

            ICalculateScore score = new TrainingSetScore(training);
            TrainEA train = new TrainEA(pop, score);
            train.Rules.AddRewriteRule(new RewriteConstants());
            train.Rules.AddRewriteRule(new RewriteAlgebraic());
            train.CODEC = new PrgCODEC();
            train.AddOperation(0.8, new SubtreeCrossover());
            train.AddOperation(0.1, new SubtreeMutation(pop.Context, 4));
            train.AddOperation(0.1, new ConstMutation(pop.Context, 0.5, 1.0));
            train.AddScoreAdjuster(new ComplexityAdjustedScore());
            train.Speciation = new PrgSpeciation();
            return train;
        }
        public void Eval(String start, String expect)
        {
            EncogProgramContext context = new EncogProgramContext();
            StandardExtensions.CreateNumericOperators(context);
            PrgPopulation pop = new PrgPopulation(context, 1);
            ICalculateScore score = new ZeroEvalScoreFunction();

            TrainEA genetic = new TrainEA(pop, score);
            genetic.ValidationMode = true;
            genetic.CODEC = new PrgCODEC();
            genetic.AddOperation(0.95, new SubtreeCrossover());
            genetic.AddOperation(0.05, new SubtreeMutation(context, 4));
            genetic.AddScoreAdjuster(new ComplexityAdjustedScore());
            genetic.Rules.AddRewriteRule(new RewriteConstants());
            genetic.Rules.AddRewriteRule(new RewriteAlgebraic());

            EncogProgram expression = new EncogProgram(context);
            expression.CompileExpression(start);
            RenderCommonExpression render = new RenderCommonExpression();
            genetic.Rules.Rewrite(expression);
            Assert.AreEqual(expect, render.Render(expression));
        }
        /// <summary>
        /// Program entry point.
        /// </summary>
        /// <param name="app">Holds arguments and other info.</param>
        public void Execute(IExampleInterface app)
        {
            IMLDataSet trainingData = GenerationUtil.GenerateSingleDataRange(
                (x) => (3 * Math.Pow(x, 2) + (12 * x) + 4)
                , 0, 100, 1);

            EncogProgramContext context = new EncogProgramContext();
            context.DefineVariable("x");

            StandardExtensions.CreateNumericOperators(context);

            PrgPopulation pop = new PrgPopulation(context, 1000);

            MultiObjectiveFitness score = new MultiObjectiveFitness();
            score.AddObjective(1.0, new TrainingSetScore(trainingData));

            TrainEA genetic = new TrainEA(pop, score);
            genetic.ValidationMode = true;
            genetic.CODEC = new PrgCODEC();
            genetic.AddOperation(0.5, new SubtreeCrossover());
            genetic.AddOperation(0.25, new ConstMutation(context, 0.5, 1.0));
            genetic.AddOperation(0.25, new SubtreeMutation(context, 4));
            genetic.AddScoreAdjuster(new ComplexityAdjustedScore(10, 20, 10, 20.0));
            genetic.Rules.AddRewriteRule(new RewriteConstants());
            genetic.Rules.AddRewriteRule(new RewriteAlgebraic());
            genetic.Speciation = new PrgSpeciation();

            (new RampedHalfAndHalf(context, 1, 6)).Generate(new EncogRandom(), pop);

            genetic.ShouldIgnoreExceptions = false;

            EncogProgram best = null;
            genetic.ThreadCount = 1;

            try
            {

                for (int i = 0; i < 1000; i++)
                {
                    genetic.Iteration();
                    best = (EncogProgram)genetic.BestGenome;
                    Console.Out.WriteLine(genetic.IterationNumber + ", Error: "
                            + best.Score + ",Best Genome Size:" + best.Size
                            + ",Species Count:" + pop.Species.Count + ",best: " + best.DumpAsCommonExpression());
                }

                //EncogUtility.evaluate(best, trainingData);

                Console.Out.WriteLine("Final score:" + best.Score
                        + ", effective score:" + best.AdjustedScore);
                Console.Out.WriteLine(best.DumpAsCommonExpression());
                //pop.dumpMembers(Integer.MAX_VALUE);
                //pop.dumpMembers(10);

            }
            catch (Exception t)
            {
                Console.Out.WriteLine(t.ToString());
            }
            finally
            {
                genetic.FinishTraining();
                EncogFramework.Instance.Shutdown();
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Construct a NEAT (or HyperNEAT trainer.
        /// </summary>
        /// <param name="population">The population.</param>
        /// <param name="calculateScore">The score function.</param>
        /// <returns>The NEAT EA trainer.</returns>
        public static TrainEA ConstructNEATTrainer(NEATPopulation population,
                ICalculateScore calculateScore)
        {
            var result = new TrainEA(population, calculateScore) {Speciation = new OriginalNEATSpeciation()};

            result.Selection = new TruncationSelection(result, 0.3);
            var weightMutation = new CompoundOperator();
            weightMutation.Components.Add(
                    0.1125,
                    new NEATMutateWeights(new SelectFixed(1),
                            new MutatePerturbLinkWeight(0.02)));
            weightMutation.Components.Add(
                    0.1125,
                    new NEATMutateWeights(new SelectFixed(2),
                            new MutatePerturbLinkWeight(0.02)));
            weightMutation.Components.Add(
                    0.1125,
                    new NEATMutateWeights(new SelectFixed(3),
                            new MutatePerturbLinkWeight(0.02)));
            weightMutation.Components.Add(
                    0.1125,
                    new NEATMutateWeights(new SelectProportion(0.02),
                            new MutatePerturbLinkWeight(0.02)));
            weightMutation.Components.Add(
                    0.1125,
                    new NEATMutateWeights(new SelectFixed(1),
                            new MutatePerturbLinkWeight(1)));
            weightMutation.Components.Add(
                    0.1125,
                    new NEATMutateWeights(new SelectFixed(2),
                            new MutatePerturbLinkWeight(1)));
            weightMutation.Components.Add(
                    0.1125,
                    new NEATMutateWeights(new SelectFixed(3),
                            new MutatePerturbLinkWeight(1)));
            weightMutation.Components.Add(
                    0.1125,
                    new NEATMutateWeights(new SelectProportion(0.02),
                            new MutatePerturbLinkWeight(1)));
            weightMutation.Components.Add(
                    0.03,
                    new NEATMutateWeights(new SelectFixed(1),
                            new MutateResetLinkWeight()));
            weightMutation.Components.Add(
                    0.03,
                    new NEATMutateWeights(new SelectFixed(2),
                            new MutateResetLinkWeight()));
            weightMutation.Components.Add(
                    0.03,
                    new NEATMutateWeights(new SelectFixed(3),
                            new MutateResetLinkWeight()));
            weightMutation.Components.Add(
                    0.01,
                    new NEATMutateWeights(new SelectProportion(0.02),
                            new MutateResetLinkWeight()));
            weightMutation.Components.FinalizeStructure();

            result.ChampMutation = weightMutation;
            result.AddOperation(0.5, new NEATCrossover());
            result.AddOperation(0.494, weightMutation);
            result.AddOperation(0.0005, new NEATMutateAddNode());
            result.AddOperation(0.005, new NEATMutateAddLink());
            result.AddOperation(0.0005, new NEATMutateRemoveLink());
            result.Operators.FinalizeStructure();

            if (population.IsHyperNEAT)
            {
                result.CODEC = new HyperNEATCODEC();
            }
            else
            {
                result.CODEC = new NEATCODEC();
            }

            return result;
        }