Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/Main/Program.cs @ 11801

Last change on this file since 11801 was 11801, checked in by gkronber, 9 years ago

#2283 comment and new test runs

File size: 14.6 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Data;
4using System.Diagnostics;
5using System.Globalization;
6using System.Linq;
7using System.Text;
8using System.Threading.Tasks;
9using HeuristicLab.Algorithms.Bandits;
10using HeuristicLab.Algorithms.Bandits.BanditPolicies;
11using HeuristicLab.Algorithms.Bandits.GrammarPolicies;
12using HeuristicLab.Algorithms.Bandits.Models;
13using HeuristicLab.Algorithms.GrammaticalOptimization;
14using HeuristicLab.Problems.GrammaticalOptimization;
15using HeuristicLab.Problems.GrammaticalOptimization.SymbReg;
16using BoltzmannExplorationPolicy = HeuristicLab.Algorithms.Bandits.BanditPolicies.BoltzmannExplorationPolicy;
17using EpsGreedyPolicy = HeuristicLab.Algorithms.Bandits.BanditPolicies.EpsGreedyPolicy;
18using RandomPolicy = HeuristicLab.Algorithms.Bandits.BanditPolicies.RandomPolicy;
19using UCTPolicy = HeuristicLab.Algorithms.Bandits.BanditPolicies.UCTPolicy;
20
21namespace Main {
22  class Program {
23    static void Main(string[] args) {
24      CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture;
25
26      //RunDemo();
27      RunGridTest();
28    }
29
30    private static void RunGridTest() {
31      int maxIterations = 50000; // for poly-10 with 50000 evaluations no successful try with hl yet
32      //var globalRandom = new Random(31415);
33      var localRandSeed = 31415;
34      var reps = 10;
35
36      var policyFactories = new Func<IBanditPolicy>[]
37        {
38         () => new RandomPolicy(),
39          () => new ActiveLearningPolicy(), 
40         () => new EpsGreedyPolicy(0.01, (aInfo)=> aInfo.MaxReward, "max"),
41         () => new EpsGreedyPolicy(0.05, (aInfo)=> aInfo.MaxReward, "max"),
42         () => new EpsGreedyPolicy(0.1, (aInfo)=> aInfo.MaxReward, "max"),
43         () => new EpsGreedyPolicy(0.2, (aInfo)=> aInfo.MaxReward, "max"),
44         //() => new GaussianThompsonSamplingPolicy(),
45         () => new GaussianThompsonSamplingPolicy(true),
46         () => new GenericThompsonSamplingPolicy(new GaussianModel(0.5, 10, 1)),
47         () => new GenericThompsonSamplingPolicy(new GaussianModel(0.5, 10, 1, 1)),
48         //() => new BernoulliThompsonSamplingPolicy(),
49         () => new GenericThompsonSamplingPolicy(new BernoulliModel(1, 1)),
50         () => new EpsGreedyPolicy(0.01),
51         () => new EpsGreedyPolicy(0.05),
52         () => new EpsGreedyPolicy(0.1),
53         () => new EpsGreedyPolicy(0.2),
54         () => new EpsGreedyPolicy(0.5),
55         () => new UCTPolicy(0.01),
56         () => new UCTPolicy(0.05),
57         () => new UCTPolicy(0.1),
58         () => new UCTPolicy(0.5),
59         () => new UCTPolicy(1),
60         () => new UCTPolicy(2),
61         () => new UCTPolicy( 5),
62         () => new UCTPolicy( 10),
63         () => new UCB1Policy(),
64         () => new UCB1TunedPolicy(),
65         () => new UCBNormalPolicy(),
66         () => new BoltzmannExplorationPolicy(1),
67         () => new BoltzmannExplorationPolicy(10),
68         () => new BoltzmannExplorationPolicy(20),
69         () => new BoltzmannExplorationPolicy(100),
70         () => new BoltzmannExplorationPolicy(200),
71         () => new BoltzmannExplorationPolicy(500),
72         () => new ChernoffIntervalEstimationPolicy( 0.01),
73         () => new ChernoffIntervalEstimationPolicy( 0.05),
74         () => new ChernoffIntervalEstimationPolicy( 0.1),
75         () => new ChernoffIntervalEstimationPolicy( 0.2),
76         () => new ThresholdAscentPolicy(5, 0.01),
77         () => new ThresholdAscentPolicy(5, 0.05),
78         () => new ThresholdAscentPolicy(5, 0.1),
79         () => new ThresholdAscentPolicy(5, 0.2),
80         () => new ThresholdAscentPolicy(10, 0.01),
81         () => new ThresholdAscentPolicy(10, 0.05),
82         () => new ThresholdAscentPolicy(10, 0.1),
83         () => new ThresholdAscentPolicy(10, 0.2),
84         () => new ThresholdAscentPolicy(50, 0.01),
85         () => new ThresholdAscentPolicy(50, 0.05),
86         () => new ThresholdAscentPolicy(50, 0.1),
87         () => new ThresholdAscentPolicy(50, 0.2),
88         () => new ThresholdAscentPolicy(100, 0.01),
89         () => new ThresholdAscentPolicy(100, 0.05),
90         () => new ThresholdAscentPolicy(100, 0.1),
91         () => new ThresholdAscentPolicy(100, 0.2),
92         () => new ThresholdAscentPolicy(500, 0.01),
93         () => new ThresholdAscentPolicy(500, 0.05),
94         () => new ThresholdAscentPolicy(500, 0.1),
95         () => new ThresholdAscentPolicy(500, 0.2),
96         //() => new ThresholdAscentPolicy(5000, 0.01),
97         //() => new ThresholdAscentPolicy(10000, 0.01),
98        };
99
100      var instanceFactories = new Func<Random, Tuple<IProblem, int>>[]
101      {
102        //(rand) => Tuple.Create((IProblem)new SantaFeAntProblem(), 17),
103        (rand) => Tuple.Create((IProblem)new FindPhrasesProblem(rand, 10, numPhrases:5, phraseLen:3, numOptimalPhrases:5, numDecoyPhrases:0, correctReward:1, decoyReward:0, phrasesAsSets:false ), 15),
104        (rand) => Tuple.Create((IProblem)new FindPhrasesProblem(rand, 10, numPhrases:5, phraseLen:3, numOptimalPhrases:5, numDecoyPhrases:0, correctReward:1, decoyReward:0, phrasesAsSets:true ), 15),
105        (rand) => Tuple.Create((IProblem)new FindPhrasesProblem(rand, 10, numPhrases:5, phraseLen:3, numOptimalPhrases:5, numDecoyPhrases:200, correctReward:1, decoyReward:0.5, phrasesAsSets:false), 15),
106        (rand) => Tuple.Create((IProblem)new FindPhrasesProblem(rand, 10, numPhrases:5, phraseLen:3, numOptimalPhrases:5, numDecoyPhrases:200, correctReward:1, decoyReward:0.5, phrasesAsSets:true), 15),
107        //(rand) => Tuple.Create((IProblem)new SymbolicRegressionPoly10Problem(), 23)
108      };
109
110      foreach (var instanceFactory in instanceFactories) {
111        foreach (var useCanonical in new bool[] { true /*, false */ }) {
112          foreach (var randomTries in new int[] { 0, /* 1, 10, /* 5, 100 /*, 500, 1000 */}) {
113            foreach (var policyFactory in policyFactories) {
114              var myRandomTries = randomTries;
115              var localRand = new Random(localRandSeed);
116              var options = new ParallelOptions();
117              options.MaxDegreeOfParallelism = 4;
118              Parallel.For(0, reps, options, (i) => {
119                Random myLocalRand;
120                lock (localRand)
121                  myLocalRand = new Random(localRand.Next());
122
123                int iterations = 0;
124                var globalStatistics = new SentenceSetStatistics();
125
126                // var problem = new SymbolicRegressionPoly10Problem();
127                // var problem = new SantaFeAntProblem();
128                //var problem = new PalindromeProblem();
129                //var problem = new HardPalindromeProblem();
130                //var problem = new RoyalPairProblem();
131                //var problem = new EvenParityProblem();
132                // var alg = new MctsSampler(problem.Item1, problem.Item2, myLocalRand, myRandomTries, policy());
133                var instance = instanceFactory(myLocalRand);
134                var problem = instance.Item1;
135                var maxLen = instance.Item2;
136                var alg = new SequentialSearch(problem, maxLen, myLocalRand, myRandomTries,
137                  new GenericGrammarPolicy(problem, policyFactory(), useCanonical));
138                //var alg = new ExhaustiveBreadthFirstSearch(problem, 25);
139                //var alg = new AlternativesContextSampler(problem, 25);
140
141                alg.SolutionEvaluated += (sentence, quality) => {
142                  iterations++;
143                  globalStatistics.AddSentence(sentence, quality);
144                  if (iterations % 10000 == 0) {
145                    Console.WriteLine("{0,3} {1,5} \"{2,25}\" {3} {4}", i, myRandomTries, policyFactory(), useCanonical, globalStatistics);
146                  }
147                };
148                alg.FoundNewBestSolution += (sentence, quality) => {
149                  //Console.WriteLine("{0,5} {1,25} {2} {3}",
150                  //  myRandomTries, policyFactory(), useCanonical,
151                  //  globalStatistics);
152                };
153
154                alg.Run(maxIterations);
155              });
156            }
157          }
158        }
159      }
160    }
161
162    private static void RunDemo() {
163      // TODO: move problem instances into a separate folder
164      // TODO: implement bridge to HL-GP
165      // TODO: unify MCTS, TD and ContextMCTS Solvers (stateInfos)
166      // TODO: test with eps-greedy using max instead of average as value (seems to work well for symb-reg! explore further!)
167      // TODO: separate value function from policy
168      // TODO: in contextual MCTS store a bandit info for each node in the _graph_ and also update all bandit infos of all parents
169      // TODO: exhaustive search with priority list
170      // TODO: warum funktioniert die alte Implementierung von GaussianThompson besser fÃŒr SantaFe als neue? Siehe Vergleich: alte vs. neue implementierung GaussianThompsonSampling
171      // TODO: why does GaussianThompsonSampling work so well with MCTS for the artificial ant problem?
172      // TODO: wie kann ich sampler noch vergleichen bzw. was kann man messen um die qualitÀt des samplers abzuschÀtzen (bis auf qualitÀt und iterationen bis zur besten lösung) => ziel schnellere iterationen zu gutem ergebnis
173      // TODO: research thompson sampling for max bandit?
174      // TODO: ausfÃŒhrlicher test von strategien fÃŒr numCorrectPhrases-armed max bandit
175      // TODO: verify TA implementation using example from the original paper     
176      // TODO: separate policy from MCTS tree data structure to allow sharing of information over disconnected parts of the tree (semantic equivalence)
177      // TODO: implement thompson sampling for gaussian mixture models
178      // TODO: implement inspection for MCTS (eventuell interactive command line fÃŒr statistiken aus dem baum anzeigen)
179      // TODO: implement ACO-style bandit policy
180      // TODO: gleichzeitige modellierung von transformierter zielvariable (y, 1/y, log(y), exp(y), sqrt(y), ...)
181      // TODO: vergleich bei complete-randomly möglichst kurze sÀtze generieren vs. einfach zufÀllig alternativen wÀhlen
182      // TODO: reward discounting (fÃŒr verÀnderliche reward distributions ÃŒber zeit). speziellen unit-test dafÃŒr erstellen
183      // TODO: constant optimization
184
185
186      int maxIterations = 100000;
187      int iterations = 0;
188      var sw = new Stopwatch();
189
190      var globalStatistics = new SentenceSetStatistics();
191      var random = new Random();
192
193
194      var problem = new RoyalSequenceProblem(random, 10, 30, 2, 1, 0);
195      //var phraseLen = 3;
196      //var numPhrases = 5;
197      //var problem = new RoyalPhraseSequenceProblem(random, 15, numPhrases, phraseLen: phraseLen, numCorrectPhrases: 1, correctReward: 1, incorrectReward: 0.0, phrasesAsSets: true);
198
199      // var phraseLen = 3;
200      // var numPhrases = 5;
201      // var problem = new FindPhrasesProblem(random, 10, numPhrases, phraseLen, numOptimalPhrases: numPhrases, numDecoyPhrases: 200, correctReward: 1.0, decoyReward: 0.5, phrasesAsSets: true);
202
203      // good results for symb-reg
204      // prev results: e.g. 10 randomtries and EpsGreedyPolicy(0.2, (aInfo)=>aInfo.MaxReward)
205      // 2015 01 19: grid test with canonical states:
206      // - EpsGreedyPolicy(0.20,max)
207      // - GenericThompsonSamplingPolicy("")
208      // - UCTPolicy(0.10) (5 of 5 runs, 35000 iters avg.), 10 successful runs of 10 with rand-tries 0, bei 40000 iters 9 / 10, bei 30000 1 / 10
209
210      // good results for artificial ant:
211      // prev results:
212      // - var alg = new MctsSampler(problem, 17, random, 1, (rand, numActions) => new ThresholdAscentPolicy(numActions, 500, 0.01));
213      // - GaussianModelWithUnknownVariance (and Q= 0.99-quantil) also works well for Ant
214      // 2015 01 19: grid test with canonical states (non-canonical slightly worse)
215      // - Threshold Ascent (best 100, 0.01; all variants relatively good)
216      // - Policies where the variance has a large weight compared to the mean? (Gaussian(compatible), Gaussian with fixed variance, UCT with large c, alle TA)
217
218      //var problem = new SymbolicRegressionPoly10Problem();
219
220      //var problem = new SantaFeAntProblem();
221      //var problem = new SymbolicRegressionProblem("Tower");
222      //var problem = new PalindromeProblem();
223      //var problem = new HardPalindromeProblem();
224      //var problem = new RoyalPairProblem();
225      //var problem = new EvenParityProblem();
226      // symbreg length = 11 q = 0.824522210419616
227      //var alg = new MctsSampler(problem, 23, random, 0, new BoltzmannExplorationPolicy(100));
228      //var alg = new MctsSampler(problem, 23, random, 0, new EpsGreedyPolicy(0.1));
229      var alg = new SequentialSearch(problem, 30, random, 0,
230        new HeuristicLab.Algorithms.Bandits.GrammarPolicies.GenericGrammarPolicy(problem, new EpsGreedyPolicy(0.1), true));
231      //var alg = new MctsQLearningSampler(problem, sentenceLen, random, 0, null);
232      //var alg = new MctsQLearningSampler(problem, 30, random, 0, new EpsGreedyPolicy(0.2));
233      //var alg = new MctsContextualSampler(problem, 23, random, 0); // must visit each canonical solution only once
234      //var alg = new TemporalDifferenceTreeSearchSampler(problem, 30, random, 1);
235      //var alg = new ExhaustiveBreadthFirstSearch(problem, 7);
236      //var alg = new AlternativesContextSampler(problem, random, 17, 4, (rand, numActions) => new RandomPolicy(rand, numActions));
237      //var alg = new ExhaustiveDepthFirstSearch(problem, 17);
238      // var alg = new AlternativesSampler(problem, 17);
239      // var alg = new RandomSearch(problem, random, 17);
240      //var alg = new ExhaustiveRandomFirstSearch(problem, random, 17);
241
242      alg.FoundNewBestSolution += (sentence, quality) => {
243        //Console.WriteLine("{0,4} {1,7} {2}", alg.treeDepth, alg.treeSize, globalStatistics);
244        //Console.ReadLine();
245      };
246      alg.SolutionEvaluated += (sentence, quality) => {
247        iterations++;
248        globalStatistics.AddSentence(sentence, quality);
249        if (iterations % 1000 == 0) {
250          if (iterations % 1000 == 0) Console.Clear();
251          Console.SetCursorPosition(0, 0);
252          alg.PrintStats();
253        }
254        //Console.WriteLine(sentence);
255
256        if (iterations % 10000 == 0) {
257          //Console.WriteLine("{0,4} {1,7} {2}", alg.treeDepth, alg.treeSize, globalStatistics);
258        }
259      };
260
261
262      sw.Start();
263
264      alg.Run(maxIterations);
265
266      sw.Stop();
267
268      Console.Clear();
269      alg.PrintStats();
270      Console.WriteLine(globalStatistics);
271      Console.WriteLine("{0:F2} sec {1,10:F1} sols/sec {2,10:F1} ns/sol",
272        sw.Elapsed.TotalSeconds,
273        maxIterations / (double)sw.Elapsed.TotalSeconds,
274        (double)sw.ElapsedMilliseconds * 1000 / maxIterations);
275    }
276  }
277}
Note: See TracBrowser for help on using the repository browser.