Free cookie consent management tool by TermsFeed Policy Generator

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

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

#2283: performance tuning and reactivated random-roll-out policy in sequential search

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