Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab/3.3/Tests/GeneticAlgorithmSamplesTest.cs @ 6468

Last change on this file since 6468 was 6468, checked in by gkronber, 12 years ago

#1553: split GA unit tests into two sets, one set for creating the samples and one set to run the samples and check results.

File size: 23.6 KB
Line 
1using System;
2using System.Text;
3using System.Collections.Generic;
4using System.Linq;
5using Microsoft.VisualStudio.TestTools.UnitTesting;
6using HeuristicLab.Algorithms.GeneticAlgorithm;
7using HeuristicLab.Problems.ArtificialAnt;
8using HeuristicLab.Selection;
9using HeuristicLab.Data;
10using HeuristicLab.Encodings.SymbolicExpressionTreeEncoding;
11using HeuristicLab.Persistence.Default.Xml;
12using HeuristicLab.Optimization;
13using System.Threading;
14using HeuristicLab.ParallelEngine;
15using HeuristicLab.Problems.DataAnalysis.Symbolic.Regression;
16using HeuristicLab.Problems.DataAnalysis;
17using HeuristicLab.Problems.DataAnalysis.Symbolic;
18using System.IO;
19using HeuristicLab.Problems.DataAnalysis.Symbolic.Classification;
20using HeuristicLab.Problems.TravelingSalesman;
21using HeuristicLab.Encodings.PermutationEncoding;
22using HeuristicLab.Problems.VehicleRouting;
23using HeuristicLab.Problems.VehicleRouting.Encodings.Potvin;
24using HeuristicLab.Problems.VehicleRouting.Encodings;
25using HeuristicLab.Problems.VehicleRouting.Encodings.General;
26
27namespace HeuristicLab_33.Tests {
28  [TestClass]
29  public class GeneticAlgorithmSamplesTest {
30    #region TSP
31    [TestMethod]
32    public void CreateTSPSampleTest() {
33      var ga = CreateTSPSample();
34      XmlGenerator.Serialize(ga, "../../GA_TSP.hl");
35    }
36    [TestMethod]
37    public void RunTSPSampleTest() {
38      var ga = CreateTSPSample();
39      ga.SetSeedRandomly.Value = false;
40      RunAlgorithm(ga);
41      Assert.AreEqual(12332, GetDoubleResult(ga, "BestQuality"));
42      Assert.AreEqual(13123.2, GetDoubleResult(ga, "CurrentAverageQuality"));
43      Assert.AreEqual(14538, GetDoubleResult(ga, "CurrentWorstQuality"));
44      Assert.AreEqual(99100, GetIntResult(ga, "EvaluatedSolutions"));
45    }
46
47    private GeneticAlgorithm CreateTSPSample() {
48      GeneticAlgorithm ga = new GeneticAlgorithm();
49      #region problem configuration
50      TravelingSalesmanProblem tspProblem = new TravelingSalesmanProblem();
51      // import and configure TSP data
52      string ch130FileName = Path.GetTempFileName() + ".tsp";// for silly parser constraints
53      using (var writer = File.CreateText(ch130FileName)) {
54        writer.Write(HeuristicLab_33.Tests.Properties.Resources.ch130);
55      }
56      string ch130OptTourFileName = Path.GetTempFileName() + ".opt.tour"; // for silly parser constraints
57      using (var writer = File.CreateText(ch130OptTourFileName)) {
58        writer.Write(HeuristicLab_33.Tests.Properties.Resources.ch130_opt);
59      }
60
61      tspProblem.ImportFromTSPLIB(ch130FileName, ch130OptTourFileName, 6110);
62      tspProblem.Evaluator = new TSPRoundedEuclideanPathEvaluator();
63      tspProblem.SolutionCreator = new RandomPermutationCreator();
64      tspProblem.UseDistanceMatrix.Value = true;
65      tspProblem.Name = "ch130 TSP (imported from TSPLIB)";
66      tspProblem.Description = "130 city problem (Churritz)";
67      #endregion
68      #region algorithm configuration
69      ga.Name = "Genetic Algorithm - TSP";
70      ga.Description = "A genetic algorithm which solves the \"ch130\" traveling salesman problem (imported from TSPLIB)";
71      ga.Problem = tspProblem;
72      ConfigureGeneticAlgorithmParameters<ProportionalSelector, OrderCrossover2, InversionManipulator>(
73        ga, 100, 1, 1000, 0.05);
74
75      ga.Analyzer.Operators.SetItemCheckedState(ga.Analyzer.Operators
76        .OfType<TSPAlleleFrequencyAnalyzer>()
77        .Single(), false);
78      ga.Analyzer.Operators.SetItemCheckedState(ga.Analyzer.Operators
79        .OfType<TSPPopulationDiversityAnalyzer>()
80        .Single(), false);
81      #endregion
82      return ga;
83    }
84
85    #endregion
86    #region VRP
87    [TestMethod]
88    public void CreateVRPSampleTest() {
89      var ga = CreateVRPSample();
90      XmlGenerator.Serialize(ga, "../../GA_VRP.hl");
91    }
92
93    [TestMethod]
94    public void RunVRPSampleTest() {
95      var ga = CreateVRPSample();
96      ga.SetSeedRandomly.Value = false;
97      RunAlgorithm(ga);
98      Assert.AreEqual(1828.9368669428336, GetDoubleResult(ga, "BestQuality"));
99      Assert.AreEqual(1832.0882694567929, GetDoubleResult(ga, "CurrentAverageQuality"));
100      Assert.AreEqual(1948.386456294867, GetDoubleResult(ga, "CurrentWorstQuality"));
101      Assert.AreEqual(99100, GetIntResult(ga, "EvaluatedSolutions"));
102    }
103
104    private GeneticAlgorithm CreateVRPSample() {
105      GeneticAlgorithm ga = new GeneticAlgorithm();
106      #region problem configuration
107      VehicleRoutingProblem vrpProblem = new VehicleRoutingProblem();
108      // import and configure VRP data
109      string c101FileName = Path.GetTempFileName();
110      using (var writer = File.CreateText(c101FileName)) {
111        writer.Write(HeuristicLab_33.Tests.Properties.Resources.C101);
112      }
113      // import and configure VRP data
114      string c101BestSolutionFileName = Path.GetTempFileName();
115      using (var writer = File.CreateText(c101BestSolutionFileName)) {
116        writer.Write(HeuristicLab_33.Tests.Properties.Resources.C101_opt);
117      }
118
119      vrpProblem.ImportFromSolomon(c101FileName);
120      vrpProblem.ImportSolution(c101BestSolutionFileName);
121      vrpProblem.Name = "C101 VRP (imported from Solomon)";
122      vrpProblem.Description = "Represents a Vehicle Routing Problem.";
123      vrpProblem.DistanceFactorParameter.Value.Value = 1;
124      vrpProblem.FleetUsageFactorParameter.Value.Value = 100;
125      vrpProblem.OverloadPenaltyParameter.Value.Value = 100;
126      vrpProblem.TardinessPenaltyParameter.Value.Value = 100;
127      vrpProblem.TimeFactorParameter.Value.Value = 0;
128      vrpProblem.Evaluator = new VRPEvaluator();
129      vrpProblem.MaximizationParameter.Value.Value = false;
130      vrpProblem.SolutionCreator = new RandomCreator();
131      vrpProblem.UseDistanceMatrix.Value = true;
132      vrpProblem.Vehicles.Value = 25;
133      #endregion
134      #region algorithm configuration
135      ga.Name = "Genetic Algorithm - VRP";
136      ga.Description = "A genetic algorithm which solves the \"C101\" vehicle routing problem (imported from Solomon)";
137      ga.Problem = vrpProblem;
138      ConfigureGeneticAlgorithmParameters<TournamentSelector, MultiVRPSolutionCrossover, MultiVRPSolutionManipulator>(
139        ga, 100, 1, 1000, 0.05, 3);
140
141      var xOver = (MultiVRPSolutionCrossover)ga.Crossover;
142      foreach (var op in xOver.Operators) {
143        xOver.Operators.SetItemCheckedState(op, false);
144      }
145      xOver.Operators.SetItemCheckedState(xOver.Operators
146        .OfType<PotvinRouteBasedCrossover>()
147        .Single(), true);
148      xOver.Operators.SetItemCheckedState(xOver.Operators
149        .OfType<PotvinSequenceBasedCrossover>()
150        .Single(), true);
151
152      var manipulator = (MultiVRPSolutionManipulator)ga.Mutator;
153      foreach (var op in manipulator.Operators) {
154        manipulator.Operators.SetItemCheckedState(op, false);
155      }
156      manipulator.Operators.SetItemCheckedState(manipulator.Operators
157        .OfType<PotvinOneLevelExchangeMainpulator>()
158        .Single(), true);
159      manipulator.Operators.SetItemCheckedState(manipulator.Operators
160        .OfType<PotvinTwoLevelExchangeManipulator>()
161        .Single(), true);
162      #endregion
163      return ga;
164    }
165
166    #endregion
167    #region ArtificialAnt
168
169    [TestMethod]
170    public void CreateArtificialAntSampleTest() {
171      var ga = CreateArtificialAntSample();
172      XmlGenerator.Serialize(ga, "../../SGP_SantaFe.hl");
173    }
174
175    [TestMethod]
176    public void RunArtificialAntSampleTest() {
177      var ga = CreateArtificialAntSample();
178      ga.SetSeedRandomly.Value = false;
179      RunAlgorithm(ga);
180      Assert.AreEqual(89, GetDoubleResult(ga, "BestQuality"));
181      Assert.AreEqual(79.834, GetDoubleResult(ga, "CurrentAverageQuality"));
182      Assert.AreEqual(0, GetDoubleResult(ga, "CurrentWorstQuality"));
183      Assert.AreEqual(100900, GetIntResult(ga, "EvaluatedSolutions"));
184    }
185
186    public GeneticAlgorithm CreateArtificialAntSample() {
187      GeneticAlgorithm ga = new GeneticAlgorithm();
188      #region problem configuration
189      ArtificialAntProblem antProblem = new ArtificialAntProblem();
190      antProblem.BestKnownQuality.Value = 89;
191      antProblem.MaxExpressionDepth.Value = 10;
192      antProblem.MaxExpressionLength.Value = 100;
193      antProblem.MaxFunctionArguments.Value = 3;
194      antProblem.MaxFunctionDefinitions.Value = 3;
195      antProblem.MaxTimeSteps.Value = 600;
196      #endregion
197      #region algorithm configuration
198      ga.Name = "Genetic Programming - Artificial Ant";
199      ga.Description = "A standard genetic programming algorithm to solve the artificial ant problem (Santa-Fe trail)";
200      ga.Problem = antProblem;
201      ConfigureGeneticAlgorithmParameters<TournamentSelector, SubtreeCrossover, MultiSymbolicExpressionTreeArchitectureManipulator>(
202        ga, 1000, 1, 100, 0.15, 5);
203      var mutator = (MultiSymbolicExpressionTreeArchitectureManipulator)ga.Mutator;
204      mutator.Operators.SetItemCheckedState(mutator.Operators
205        .OfType<FullTreeShaker>()
206        .Single(), false);
207      mutator.Operators.SetItemCheckedState(mutator.Operators
208        .OfType<OnePointShaker>()
209        .Single(), false);
210      mutator.Operators.SetItemCheckedState(mutator.Operators
211        .OfType<ArgumentDeleter>()
212        .Single(), false);
213      mutator.Operators.SetItemCheckedState(mutator.Operators
214        .OfType<SubroutineDeleter>()
215        .Single(), false);
216      #endregion
217      return ga;
218    }
219
220    #endregion
221    #region symbolic regression
222    [TestMethod]
223    public void CreateSymbolicRegressionSampleTest() {
224      var ga = CreateSymbolicRegressionSample();
225      XmlGenerator.Serialize(ga, "../../SGP_SymbReg.hl");
226    }
227    [TestMethod]
228    public void RunSymbolicRegressionSampleTest() {
229      var ga = CreateSymbolicRegressionSample();
230      ga.SetSeedRandomly.Value = false;
231      RunAlgorithm(ga);
232      Assert.AreEqual(0.87577096276191879, GetDoubleResult(ga, "BestQuality"));
233      Assert.AreEqual(0.65140971696668726, GetDoubleResult(ga, "CurrentAverageQuality"));
234      Assert.AreEqual(0, GetDoubleResult(ga, "CurrentWorstQuality"));
235      Assert.AreEqual(100900, GetIntResult(ga, "EvaluatedSolutions"));
236    }
237
238    private GeneticAlgorithm CreateSymbolicRegressionSample() {
239      GeneticAlgorithm ga = new GeneticAlgorithm();
240      #region problem configuration
241      SymbolicRegressionSingleObjectiveProblem symbRegProblem = new SymbolicRegressionSingleObjectiveProblem();
242      symbRegProblem.Name = "Tower Symbolic Regression Problem";
243      symbRegProblem.Description = "Tower Dataset (downloaded from: http://vanillamodeling.com/realproblems.html)";
244      // import and configure problem data
245      string filename = Path.GetTempFileName();
246      using (var writer = File.CreateText(filename)) {
247        writer.Write(HeuristicLab_33.Tests.Properties.Resources.TowerData);
248      }
249      var towerProblemData = RegressionProblemData.ImportFromFile(filename);
250      towerProblemData.TargetVariableParameter.Value = towerProblemData.TargetVariableParameter.ValidValues
251        .First(v => v.Value == "towerResponse");
252      towerProblemData.InputVariables.SetItemCheckedState(
253        towerProblemData.InputVariables.Single(x => x.Value == "x1"), true);
254      towerProblemData.InputVariables.SetItemCheckedState(
255        towerProblemData.InputVariables.Single(x => x.Value == "x7"), false);
256      towerProblemData.InputVariables.SetItemCheckedState(
257        towerProblemData.InputVariables.Single(x => x.Value == "x11"), false);
258      towerProblemData.InputVariables.SetItemCheckedState(
259        towerProblemData.InputVariables.Single(x => x.Value == "x16"), false);
260      towerProblemData.InputVariables.SetItemCheckedState(
261        towerProblemData.InputVariables.Single(x => x.Value == "x21"), false);
262      towerProblemData.InputVariables.SetItemCheckedState(
263        towerProblemData.InputVariables.Single(x => x.Value == "x25"), false);
264      towerProblemData.InputVariables.SetItemCheckedState(
265        towerProblemData.InputVariables.Single(x => x.Value == "towerResponse"), false);
266      towerProblemData.TrainingPartition.Start = 0;
267      towerProblemData.TrainingPartition.End = 4000;
268      towerProblemData.TestPartition.Start = 4000;
269      towerProblemData.TestPartition.End = 4999;
270      towerProblemData.Name = "Data imported from towerData.txt";
271      towerProblemData.Description = "Chemical concentration at top of distillation tower, dataset downloaded from: http://vanillamodeling.com/realproblems.html, best R² achieved with nu-SVR = 0.97";
272      symbRegProblem.ProblemData = towerProblemData;
273
274      // configure grammar
275      var grammar = new TypeCoherentExpressionGrammar();
276      grammar.Symbols.OfType<Sine>().Single().InitialFrequency = 0.0;
277      grammar.Symbols.OfType<Cosine>().Single().InitialFrequency = 0.0;
278      grammar.Symbols.OfType<Tangent>().Single().InitialFrequency = 0.0;
279      grammar.Symbols.OfType<IfThenElse>().Single().InitialFrequency = 0.0;
280      grammar.Symbols.OfType<GreaterThan>().Single().InitialFrequency = 0.0;
281      grammar.Symbols.OfType<LessThan>().Single().InitialFrequency = 0.0;
282      grammar.Symbols.OfType<And>().Single().InitialFrequency = 0.0;
283      grammar.Symbols.OfType<Or>().Single().InitialFrequency = 0.0;
284      grammar.Symbols.OfType<Not>().Single().InitialFrequency = 0.0;
285      grammar.Symbols.OfType<TimeLag>().Single().InitialFrequency = 0.0;
286      grammar.Symbols.OfType<Integral>().Single().InitialFrequency = 0.0;
287      grammar.Symbols.OfType<Derivative>().Single().InitialFrequency = 0.0;
288      grammar.Symbols.OfType<LaggedVariable>().Single().InitialFrequency = 0.0;
289      grammar.Symbols.OfType<VariableCondition>().Single().InitialFrequency = 0.0;
290      var varSymbol = grammar.Symbols.OfType<Variable>().Where(x => !(x is LaggedVariable)).Single();
291      varSymbol.WeightMu = 1.0;
292      varSymbol.WeightSigma = 1.0;
293      varSymbol.WeightManipulatorMu = 0.0;
294      varSymbol.WeightManipulatorSigma = 0.05;
295      varSymbol.MultiplicativeWeightManipulatorSigma = 0.03;
296      var constSymbol = grammar.Symbols.OfType<Constant>().Single();
297      constSymbol.MaxValue = 20;
298      constSymbol.MinValue = -20;
299      constSymbol.ManipulatorMu = 0.0;
300      constSymbol.ManipulatorSigma = 1;
301      constSymbol.MultiplicativeManipulatorSigma = 0.03;
302      symbRegProblem.SymbolicExpressionTreeGrammar = grammar;
303
304      // configure remaining problem parameters
305      symbRegProblem.BestKnownQuality.Value = 0.97;
306      symbRegProblem.FitnessCalculationPartition.Start = 0;
307      symbRegProblem.FitnessCalculationPartition.End = 2800;
308      symbRegProblem.ValidationPartition.Start = 2800;
309      symbRegProblem.ValidationPartition.End = 4000;
310      symbRegProblem.RelativeNumberOfEvaluatedSamples.Value = 0.3;
311      symbRegProblem.MaximumSymbolicExpressionTreeLength.Value = 150;
312      symbRegProblem.MaximumSymbolicExpressionTreeDepth.Value = 12;
313      symbRegProblem.MaximumFunctionDefinitions.Value = 0;
314      symbRegProblem.MaximumFunctionArguments.Value = 0;
315
316      symbRegProblem.EvaluatorParameter.Value = new SymbolicRegressionSingleObjectivePearsonRSquaredEvaluator();
317      #endregion
318      #region algorithm configuration
319      ga.Problem = symbRegProblem;
320      ga.Name = "Genetic Programming - Symbolic Regression";
321      ga.Description = "A standard genetic programming algorithm to solve a symbolic regression problem (tower dataset)";
322      ConfigureGeneticAlgorithmParameters<TournamentSelector, SubtreeCrossover, MultiSymbolicExpressionTreeManipulator>(
323        ga, 1000, 1, 100, 0.15, 5);
324      var mutator = (MultiSymbolicExpressionTreeManipulator)ga.Mutator;
325      mutator.Operators.OfType<FullTreeShaker>().Single().ShakingFactor = 0.1;
326      mutator.Operators.OfType<OnePointShaker>().Single().ShakingFactor = 1.0;
327
328      ga.Analyzer.Operators.SetItemCheckedState(
329        ga.Analyzer.Operators
330        .OfType<SymbolicRegressionSingleObjectiveOverfittingAnalyzer>()
331        .Single(), false);
332      #endregion
333      return ga;
334    }
335    #endregion
336    #region symbolic classification
337
338    [TestMethod]
339    public void CreateSymbolicClassificationSampleTest() {
340      var ga = CreateSymbolicClassificationSample();
341      XmlGenerator.Serialize(ga, "../../SGP_SymbClass.hl");
342    }
343
344    [TestMethod]
345    public void RunSymbolicClassificationSampleTest() {
346      var ga = CreateSymbolicClassificationSample();
347      ga.SetSeedRandomly.Value = false;
348      RunAlgorithm(ga);
349      Assert.AreEqual(0.1385094551576456, GetDoubleResult(ga, "BestQuality"));
350      Assert.AreEqual(2.8817699057253576, GetDoubleResult(ga, "CurrentAverageQuality"));
351      Assert.AreEqual(100.62175156249987, GetDoubleResult(ga, "CurrentWorstQuality"));
352      Assert.AreEqual(100900, GetIntResult(ga, "EvaluatedSolutions"));
353    }
354
355    private GeneticAlgorithm CreateSymbolicClassificationSample() {
356      GeneticAlgorithm ga = new GeneticAlgorithm();
357      #region problem configuration
358      SymbolicClassificationSingleObjectiveProblem symbClassProblem = new SymbolicClassificationSingleObjectiveProblem();
359      symbClassProblem.Name = "Mammography Classification Problem";
360      symbClassProblem.Description = "Mammography dataset imported from the UCI machine learning repository (http://archive.ics.uci.edu/ml/datasets/Mammographic+Mass)";
361      // import and configure problem data
362      string filename = Path.GetTempFileName();
363      using (var writer = File.CreateText(filename)) {
364        writer.Write(HeuristicLab_33.Tests.Properties.Resources.MammographicMasses);
365      }
366      var mammoData = ClassificationProblemData.ImportFromFile(filename);
367      mammoData.TargetVariableParameter.Value = mammoData.TargetVariableParameter.ValidValues
368        .First(v => v.Value == "Severity");
369      mammoData.InputVariables.SetItemCheckedState(
370        mammoData.InputVariables.Single(x => x.Value == "BI-RADS"), false);
371      mammoData.InputVariables.SetItemCheckedState(
372        mammoData.InputVariables.Single(x => x.Value == "Age"), true);
373      mammoData.InputVariables.SetItemCheckedState(
374        mammoData.InputVariables.Single(x => x.Value == "Shape"), true);
375      mammoData.InputVariables.SetItemCheckedState(
376        mammoData.InputVariables.Single(x => x.Value == "Margin"), true);
377      mammoData.InputVariables.SetItemCheckedState(
378        mammoData.InputVariables.Single(x => x.Value == "Density"), true);
379      mammoData.InputVariables.SetItemCheckedState(
380        mammoData.InputVariables.Single(x => x.Value == "Severity"), false);
381      mammoData.TrainingPartition.Start = 0;
382      mammoData.TrainingPartition.End = 800;
383      mammoData.TestPartition.Start = 800;
384      mammoData.TestPartition.End = 961;
385      mammoData.Name = "Data imported from mammographic_masses.csv";
386      mammoData.Description = "Original dataset: http://archive.ics.uci.edu/ml/datasets/Mammographic+Mass, missing values have been replaced with median values.";
387      symbClassProblem.ProblemData = mammoData;
388
389      // configure grammar
390      var grammar = new TypeCoherentExpressionGrammar();
391      grammar.Symbols.OfType<Sine>().Single().InitialFrequency = 0.0;
392      grammar.Symbols.OfType<Cosine>().Single().InitialFrequency = 0.0;
393      grammar.Symbols.OfType<Tangent>().Single().InitialFrequency = 0.0;
394      grammar.Symbols.OfType<Power>().Single().InitialFrequency = 0.0;
395      grammar.Symbols.OfType<Root>().Single().InitialFrequency = 0.0;
396      grammar.Symbols.OfType<TimeLag>().Single().InitialFrequency = 0.0;
397      grammar.Symbols.OfType<Integral>().Single().InitialFrequency = 0.0;
398      grammar.Symbols.OfType<Derivative>().Single().InitialFrequency = 0.0;
399      grammar.Symbols.OfType<LaggedVariable>().Single().InitialFrequency = 0.0;
400      grammar.Symbols.OfType<VariableCondition>().Single().InitialFrequency = 0.0;
401      var varSymbol = grammar.Symbols.OfType<Variable>().Where(x => !(x is LaggedVariable)).Single();
402      varSymbol.WeightMu = 1.0;
403      varSymbol.WeightSigma = 1.0;
404      varSymbol.WeightManipulatorMu = 0.0;
405      varSymbol.WeightManipulatorSigma = 0.05;
406      varSymbol.MultiplicativeWeightManipulatorSigma = 0.03;
407      var constSymbol = grammar.Symbols.OfType<Constant>().Single();
408      constSymbol.MaxValue = 20;
409      constSymbol.MinValue = -20;
410      constSymbol.ManipulatorMu = 0.0;
411      constSymbol.ManipulatorSigma = 1;
412      constSymbol.MultiplicativeManipulatorSigma = 0.03;
413      symbClassProblem.SymbolicExpressionTreeGrammar = grammar;
414
415      // configure remaining problem parameters
416      symbClassProblem.BestKnownQuality.Value = 0.0;
417      symbClassProblem.FitnessCalculationPartition.Start = 0;
418      symbClassProblem.FitnessCalculationPartition.End = 400;
419      symbClassProblem.ValidationPartition.Start = 400;
420      symbClassProblem.ValidationPartition.End = 800;
421      symbClassProblem.RelativeNumberOfEvaluatedSamples.Value = 1;
422      symbClassProblem.MaximumSymbolicExpressionTreeLength.Value = 100;
423      symbClassProblem.MaximumSymbolicExpressionTreeDepth.Value = 10;
424      symbClassProblem.MaximumFunctionDefinitions.Value = 0;
425      symbClassProblem.MaximumFunctionArguments.Value = 0;
426      symbClassProblem.EvaluatorParameter.Value = new SymbolicClassificationSingleObjectiveMeanSquaredErrorEvaluator();
427      #endregion
428      #region algorithm configuration
429      ga.Problem = symbClassProblem;
430      ga.Name = "Genetic Programming - Symbolic Classification";
431      ga.Description = "A standard genetic programming algorithm to solve a classification problem (Mammographic+Mass dataset)";
432      ConfigureGeneticAlgorithmParameters<TournamentSelector, SubtreeCrossover, MultiSymbolicExpressionTreeManipulator>(
433        ga, 1000, 1, 100, 0.15, 5
434        );
435
436      var mutator = (MultiSymbolicExpressionTreeManipulator)ga.Mutator;
437      mutator.Operators.OfType<FullTreeShaker>().Single().ShakingFactor = 0.1;
438      mutator.Operators.OfType<OnePointShaker>().Single().ShakingFactor = 1.0;
439
440      ga.Analyzer.Operators.SetItemCheckedState(
441        ga.Analyzer.Operators
442        .OfType<SymbolicClassificationSingleObjectiveOverfittingAnalyzer>()
443        .Single(), false);
444      #endregion
445      return ga;
446    }
447    #endregion
448
449    private void ConfigureGeneticAlgorithmParameters<S, C, M>(GeneticAlgorithm ga, int popSize, int elites, int maxGens, double mutationRate, int tournGroupSize = 0)
450      where S : ISelector
451      where C : ICrossover
452      where M : IManipulator {
453      ga.Elites.Value = elites;
454      ga.MaximumGenerations.Value = maxGens;
455      ga.MutationProbability.Value = mutationRate;
456      ga.PopulationSize.Value = popSize;
457      ga.Seed.Value = 0;
458      ga.SetSeedRandomly.Value = true;
459      ga.Selector = ga.SelectorParameter.ValidValues
460        .OfType<S>()
461        .Single();
462
463      ga.Crossover = ga.CrossoverParameter.ValidValues
464        .OfType<C>()
465        .Single();
466
467      ga.Mutator = ga.MutatorParameter.ValidValues
468        .OfType<M>()
469        .Single();
470
471      var tSelector = ga.Selector as TournamentSelector;
472      if (tSelector != null) {
473        tSelector.GroupSizeParameter.Value.Value = 5;
474      }
475      ga.Engine = new ParallelEngine();
476    }
477
478
479    private void RunAlgorithm(IAlgorithm a) {
480      var trigger = new EventWaitHandle(false, EventResetMode.ManualReset);
481      Exception ex = null;
482      a.Stopped += (src, e) => { trigger.Set(); };
483      a.ExceptionOccurred += (src, e) => { ex = e.Value; };
484      a.Prepare();
485      a.Start();
486      trigger.WaitOne();
487
488      Assert.AreEqual(ex, null);
489    }
490
491    private double GetDoubleResult(GeneticAlgorithm ga, string resultName) {
492      return ((DoubleValue)ga.Results[resultName].Value).Value;
493    }
494    private int GetIntResult(GeneticAlgorithm ga, string resultName) {
495      return ((IntValue)ga.Results[resultName].Value).Value;
496    }
497  }
498}
Note: See TracBrowser for help on using the repository browser.