Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/SequentialDecisionPolicies/GenericGrammarPolicy.cs @ 13847

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

#2283: experiments on grammatical optimization algorithms (maxreward instead of avg reward, ...)

File size: 13.4 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using System.Text;
6using System.Text.RegularExpressions;
7using System.Threading.Tasks;
8using HeuristicLab.Algorithms.Bandits.BanditPolicies;
9using HeuristicLab.Algorithms.DataAnalysis;
10using HeuristicLab.Common;
11using HeuristicLab.Problems.DataAnalysis;
12using HeuristicLab.Problems.GrammaticalOptimization;
13
14namespace HeuristicLab.Algorithms.Bandits.GrammarPolicies {
15  // this represents grammar policies that use one of the available bandit policies for state selection
16  // any bandit policy can be used to select actions for states
17  // a separate datastructure is used to store visited states and to prevent revisiting of states
18  public sealed class GenericGrammarPolicy : IGrammarPolicy {
19    private Dictionary<string, IBanditPolicyActionInfo> stateInfo; // stores the necessary information for bandit policies for each state (=canonical phrase)
20    private HashSet<string> done;
21    private readonly bool useCanonicalPhrases;
22    private readonly IProblem problem;
23    private readonly IBanditPolicy banditPolicy;
24    public double[] OptimalPulls { get; private set; }
25
26    public GenericGrammarPolicy(IProblem problem, IBanditPolicy banditPolicy, bool useCanonicalPhrases = false) {
27      this.useCanonicalPhrases = useCanonicalPhrases;
28      this.problem = problem;
29      this.banditPolicy = banditPolicy;
30      this.stateInfo = new Dictionary<string, IBanditPolicyActionInfo>();
31      this.done = new HashSet<string>();
32    }
33
34    private IBanditPolicyActionInfo[] activeAfterStates; // don't allocate each time
35    private int[] actionIndexMap; // don't allocate each time
36
37    public bool TrySelect(System.Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx) {
38      //// only for debugging
39      //if (done.Count == 30000) {
40      //  foreach (var pair in stateInfo) {
41      //    var state = pair.Key;
42      //    var info = (DefaultPolicyActionInfo)pair.Value;
43      //    if (info.Tries > 0) {
44      //      Console.WriteLine("{0};{1};{2};{3};{4};{5}", state, info.Tries, info.Value, info.MaxReward,
45      //        optimalSolutions.Contains(problem.CanonicalRepresentation(state)) ? 1 : 0,
46      //        string.Join(";", GenerateFeaturesPoly10(state)));
47      //    }
48      //  }
49      //  System.Environment.Exit(1);
50      //}
51
52      // fail if all states are done (corresponding state infos are disabled)
53      if (afterStates.All(s => Done(s))) {
54        // fail because all follow states have already been visited => also disable the current state (if we can be sure that it has been fully explored)
55        MarkAsDone(curState);
56
57        selectedStateIdx = -1;
58        return false;
59      }
60
61      // determine active actions (not done yet) and create an array to map the selected index back to original actions
62      if (activeAfterStates == null || activeAfterStates.Length < afterStates.Count()) {
63        activeAfterStates = new IBanditPolicyActionInfo[afterStates.Count()];
64        actionIndexMap = new int[afterStates.Count()];
65      }
66      var idx = 0; int originalIdx = 0;
67      foreach (var afterState in afterStates) {
68        if (!Done(afterState)) {
69          activeAfterStates[idx] = GetStateInfo(afterState);
70          actionIndexMap[idx] = originalIdx;
71          idx++;
72        }
73        originalIdx++;
74      }
75
76      //// select terminals first
77      //var terminalAfterstates = afterStates.Select((s, i) => new { s, i }).FirstOrDefault(t => !Done(t.s) && problem.Grammar.IsTerminal(t.s));
78      //if (terminalAfterstates != null) {
79      //  selectedStateIdx = terminalAfterstates.i;
80      //  return true;
81      //}
82
83      if (valueApproximation == null) {
84        // no approximation yet? --> use bandit
85        selectedStateIdx = actionIndexMap[banditPolicy.SelectAction(random, activeAfterStates.Take(idx))];
86      } else if (afterStates.Any(s => problem.Grammar.IsTerminal(s) && !Done(s))) {
87        selectedStateIdx = SelectionMaxValueTerminalAction(random, afterStates);
88      } else {
89        // only internal states? --> use bandit
90        selectedStateIdx = actionIndexMap[banditPolicy.SelectAction(random, activeAfterStates.Take(idx))];
91      }
92      return true;
93    }
94
95    private int SelectionMaxValueTerminalAction(System.Random random, IEnumerable<string> afterStates) {
96      int idx = 0;
97      var terminalStates = new List<string>();
98      var originalIdx = new List<int>();
99      foreach (var state in afterStates) {
100        if (problem.Grammar.IsTerminal(state) && !Done(state)) {
101          terminalStates.Add(state);
102          originalIdx.Add(idx);
103        }
104        idx++;
105      }
106
107      return originalIdx[SelectionMaxValueAction(random, terminalStates)];
108    }
109
110    private IRegressionSolution valueApproximation;
111    private int SelectionMaxValueAction(System.Random random, IEnumerable<string> afterStates) {
112
113      // eps greedy
114      //if (random.NextDouble() < 0.1) return Enumerable.Range(0, afterStates.Count()).SelectRandom(random);
115
116      Dataset ds;
117      string[] variablesNames;
118      CreateDataset(afterStates, afterStates.Select<string, IBanditPolicyActionInfo>(_ => null), out ds, out variablesNames);
119
120      var v = valueApproximation.Model.GetEstimatedValues(ds, Enumerable.Range(0, ds.Rows)).ToArray();
121
122      //boltzmann exploration
123      //double beta = 100;
124      //var w = v.Select(vi => Math.Exp(beta * vi));
125      //
126      //return Enumerable.Range(0, v.Length).SampleProportional(random, w);
127
128      return Enumerable.Range(0, v.Length).MaxItems(i => v[i]).SelectRandom(random);
129    }
130
131    private void UpdateValueApproximation() {
132      Dataset ds;
133      string[] variableNames;
134      CreateDataset(stateInfo.Keys, stateInfo.Values, out ds, out variableNames);
135      var problemData = new RegressionProblemData(ds, variableNames.Skip(1), variableNames.First());
136      //problemData.TestPartition.Start = problemData.TestPartition.End; // all data are training data
137      valueApproximation = GradientBoostedTreesAlgorithmStatic.TrainGbm(problemData, new SquaredErrorLoss(), 50, 0.1,
138        0.5, 0.5, 100);
139      Console.WriteLine(valueApproximation.TrainingRSquared);
140      Console.WriteLine(valueApproximation.TestRSquared);
141    }
142
143    private void CreateDataset(IEnumerable<string> states, IEnumerable<IBanditPolicyActionInfo> infos, out Dataset ds, out string[] variableNames) {
144      variableNames = new string[] { "maxValue" }.Concat(GenerateFeaturesPoly10("E").Select((_, i) => "f" + i)).ToArray();
145
146      int rows = infos.Zip(states, (info, state) => new { info, state }).Count(i => i.info == null || (i.info.Tries == 1 && Done(i.state)));
147      int cols = variableNames.Count();
148
149      var variableValues = new double[rows, cols];
150      int n = 0;
151      foreach (var pair in states.Zip(infos, Tuple.Create)) {
152        var state = pair.Item1;
153        var info = (DefaultPolicyActionInfo)pair.Item2;
154        if (info == null || (info.Tries == 1 && Done(state))) {
155          if (info != null) {
156            variableValues[n, 0] = info.MaxReward;
157          }
158          int col = 1;
159          foreach (var f in GenerateFeaturesPoly10(state)) {
160            variableValues[n, col++] = f;
161          }
162          n++;
163        }
164      }
165
166      ds = new Dataset(variableNames, variableValues);
167    }
168
169
170    private IBanditPolicyActionInfo GetStateInfo(string state) {
171      var s = CanonicalState(state);
172      IBanditPolicyActionInfo info;
173      if (!stateInfo.TryGetValue(s, out info)) {
174        info = banditPolicy.CreateActionInfo();
175        stateInfo[s] = info;
176      }
177      return info;
178    }
179
180    private int rewardUpdatesSinceLastTraining = 0;
181    private HashSet<string> statesWritten = new HashSet<string>();
182    public void UpdateReward(IEnumerable<string> stateTrajectory, double reward) {
183      rewardUpdatesSinceLastTraining++;
184      if (rewardUpdatesSinceLastTraining == 5000) {
185        rewardUpdatesSinceLastTraining = 0;
186        //// write
187        //foreach (var pair in stateInfo) {
188        //  var state = pair.Key;
189        //  var info = (DefaultPolicyActionInfo)pair.Value;
190        //  if (!statesWritten.Contains(state) && info.Tries > 0) {
191        //    Console.WriteLine("{0};{1};{2};{3};{4}", state, info.Tries, info.Value, info.MaxReward, string.Join(";", GenerateFeaturesPoly10(state)));
192        //    statesWritten.Add(state);
193        //  }
194        //}
195        //
196        //Console.WriteLine();
197        //UpdateValueApproximation();
198      }
199
200      int lvl = 0;
201      foreach (var state in stateTrajectory) {
202        double alpha = 0.99;
203        OptimalPulls[lvl] = alpha * OptimalPulls[lvl] + (1 - alpha) * (problem.IsOptimalPhrase(state) ? 1.0 : 0.0);
204        lvl++;
205
206        GetStateInfo(state).UpdateReward(reward);
207        //reward *= 0.95;
208        // only the last state can be terminal
209        if (problem.Grammar.IsTerminal(state)) {
210          MarkAsDone(state);
211        }
212      }
213    }
214
215    private IEnumerable<double> GenerateFeaturesPoly10(string state) {
216      // yield return problem.IsOptimalPhrase(state) ? 1 : 0;
217      foreach (var f in problem.GetFeatures(state)) yield return f.Value;
218
219      //if (!state.EndsWith("E")) state = state + "+E";
220      //int len = state.Length;
221      //Debug.Assert(state[len - 1] == 'E');
222      //foreach (var sy0 in new char[] { '+', '*' }) {
223      //  foreach (var sy1 in problem.Grammar.TerminalSymbols) {
224      //    foreach (var sy2 in new char[] { '+', '*' }) {
225      //      yield return state.Length > 3 && state[len - 4] == sy0 && state[len - 3] == sy1 && state[len - 2] == sy2 ? 1 : 0;
226      //    }
227      //  }
228      //}
229
230      //yield return state.Length;
231      //foreach (var terminalSy in problem.Grammar.TerminalSymbols) {
232      //  yield return state.Length > 2 && state[0] == terminalSy && state[1] == '+' ? 1 : 0;
233      //  yield return state.Length > 2 && state[0] == terminalSy && state[1] == '*' ? 1 : 0;
234      //}
235      // yield return optimalSolutions.Contains(problem.CanonicalRepresentation(state)) ? 1 : 0;
236      //foreach (var term in optimalTerms) yield return Regex.Matches(problem.CanonicalRepresentation(state), term).Count == 1 ? 1 : 0;
237      //var len = state.Length;
238      //yield return len;
239      //foreach (var t in problem.Grammar.TerminalSymbols) {
240      //  yield return state.Count(ch => ch == t);
241      //}
242      //// pairs
243      //foreach (var u in problem.Grammar.TerminalSymbols) {
244      //  foreach (var v in problem.Grammar.TerminalSymbols) {
245      //    int n = 0;
246      //    for (int i = 0; i < state.Length - 1; i++) {
247      //      if (state[i] == u && state[i + 1] == v) n++;
248      //    }
249      //    yield return n;
250      //  }
251      //}
252    }
253
254
255    public void Reset() {
256      stateInfo.Clear();
257      done.Clear();
258      OptimalPulls = new double[300]; // max sentence length is limited anyway
259    }
260
261    public int GetTries(string state) {
262      var s = CanonicalState(state);
263      if (stateInfo.ContainsKey(s)) return stateInfo[s].Tries;
264      else return 0;
265    }
266
267    public double GetValue(string state) {
268      var s = CanonicalState(state);
269      if (stateInfo.ContainsKey(s)) return stateInfo[s].MaxReward;
270      else return 0.0; // TODO: check alternatives
271    }
272
273    // the canonical states for the value function (banditInfos) and the done set must be distinguished
274    // sequences of different length could have the same canonical representation and can have the same value (banditInfo)
275    // however, if the canonical representation of a state is shorter then we must not mark the canonical state as done when all possible derivations from the initial state have been explored
276    // eg. in the ant problem the canonical representation for ...lllA is ...rA
277    // even though all possible derivations (of limited length) of lllA have been visited we must not mark the state rA as done
278    private void MarkAsDone(string state) {
279      var s = CanonicalState(state);
280      // when the lengths of the canonical string and the original string are the same we also disable the actions
281      // always disable terminals
282      Debug.Assert(s.Length <= state.Length);
283      if (s.Length == state.Length || problem.Grammar.IsTerminal(state)) {
284        Debug.Assert(!done.Contains(s));
285        done.Add(s);
286      } else {
287        // for non-terminals where the canonical string is shorter than the original string we can only disable the canonical representation for all states in the same level
288        Debug.Assert(!done.Contains(s + state.Length));
289        done.Add(s + state.Length); // encode the original length of the state, states in the same level of the tree are treated as equivalent
290      }
291    }
292
293    // symmetric to MarkDone
294    private bool Done(string state) {
295      var s = CanonicalState(state);
296      if (s.Length == state.Length || problem.Grammar.IsTerminal(state)) {
297        return done.Contains(s);
298      } else {
299        // it is not necessary to visit states if the canonical representation has already been fully explored
300        if (done.Contains(s)) return true;
301        if (done.Contains(s + state.Length)) return true;
302        for (int i = 1; i < state.Length; i++) {
303          if (done.Contains(s + i)) return true;
304        }
305        return false;
306      }
307    }
308
309    private string CanonicalState(string state) {
310      if (useCanonicalPhrases) {
311        return problem.CanonicalRepresentation(state);
312      } else
313        return state;
314    }
315  }
316}
Note: See TracBrowser for help on using the repository browser.