Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
08/24/15 13:56:27 (9 years ago)
Author:
gkronber
Message:

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

Location:
branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization
Files:
1 added
10 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/HeuristicLab.Algorithms.GrammaticalOptimization.csproj

    r12290 r12893  
    3232    <WarningLevel>4</WarningLevel>
    3333    <Prefer32Bit>false</Prefer32Bit>
     34    <UseVSHostingProcess>true</UseVSHostingProcess>
    3435  </PropertyGroup>
    3536  <ItemGroup>
     37    <Reference Include="HeuristicLab.Algorithms.DataAnalysis-3.4">
     38      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Algorithms.DataAnalysis-3.4.dll</HintPath>
     39    </Reference>
     40    <Reference Include="HeuristicLab.Common-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     41      <SpecificVersion>False</SpecificVersion>
     42      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Common-3.3.dll</HintPath>
     43    </Reference>
     44    <Reference Include="HeuristicLab.Core-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     45      <SpecificVersion>False</SpecificVersion>
     46      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Core-3.3.dll</HintPath>
     47    </Reference>
     48    <Reference Include="HeuristicLab.Data-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     49      <SpecificVersion>False</SpecificVersion>
     50      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Data-3.3.dll</HintPath>
     51    </Reference>
     52    <Reference Include="HeuristicLab.Problems.DataAnalysis-3.4">
     53      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Problems.DataAnalysis-3.4.dll</HintPath>
     54    </Reference>
     55    <Reference Include="HeuristicLab.Random-3.3, Version=3.3.0.0, Culture=neutral, PublicKeyToken=ba48961d6f65dcec, processorArchitecture=MSIL">
     56      <SpecificVersion>False</SpecificVersion>
     57      <HintPath>..\..\..\trunk\sources\bin\HeuristicLab.Random-3.3.dll</HintPath>
     58    </Reference>
    3659    <Reference Include="System" />
    3760    <Reference Include="System.Core" />
    3861  </ItemGroup>
    3962  <ItemGroup>
     63    <Compile Include="SentenceBandit.cs" />
    4064    <Compile Include="ISequentialDecisionPolicy.cs" />
    4165    <Compile Include="SequentialDecisionPolicies\GenericPolicy.cs" />
     
    6084    </ProjectReference>
    6185    <ProjectReference Include="..\HeuristicLab.Common\HeuristicLab.Common.csproj">
    62       <Project>{3A2FBBCB-F9DF-4970-87F3-F13337D941AD}</Project>
     86      <Project>{3a2fbbcb-f9df-4970-87f3-f13337d941ad}</Project>
    6387      <Name>HeuristicLab.Common</Name>
     88    </ProjectReference>
     89    <ProjectReference Include="..\HeuristicLab.Problems.Bandits\HeuristicLab.Problems.Bandits.csproj">
     90      <Project>{E8138227-0C64-4E85-B676-21D3B97F254F}</Project>
     91      <Name>HeuristicLab.Problems.Bandits</Name>
    6492    </ProjectReference>
    6593    <ProjectReference Include="..\HeuristicLab.Problems.GrammaticalOptimization\HeuristicLab.Problems.GrammaticalOptimization.csproj">
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/ISequentialDecisionPolicy.cs

    r11850 r12893  
    1212  // we also assume that the policy can fail to select one of the followStates
    1313  public interface ISequentialDecisionPolicy<in TState> {
    14     bool TrySelect(Random random, TState curState, IEnumerable<TState> afterStates, out int selectedStateIdx); // selectedState \in afterStates
     14    bool TrySelect(System.Random random, TState curState, IEnumerable<TState> afterStates, out int selectedStateIdx); // selectedState \in afterStates
    1515
    1616    // state-trajectory are the states of the episode, at the end we recieved the reward (only for the terminal state)
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/SequentialDecisionPolicies/GenericFunctionApproximationGrammarPolicy.cs

    r12027 r12893  
    3232    private int[] actionIndexMap; // don't allocate each time
    3333
    34     public bool TrySelect(Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx) {
     34    public bool TrySelect(System.Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx) {
    3535      // fail if all states are done (corresponding state infos are disabled)
    3636      if (afterStates.All(s => Done(s))) {
     
    6060        originalIdx++;
    6161      }
    62      
    63      
     62
     63
    6464      // TODO: policy should be a parameter of the function approximation policy
    6565      if (random.NextDouble() < 0.2) {
     
    7474            bestIdxs.Add(i);
    7575            bestQ = activeAfterStates[i];
    76           } else if (activeAfterStates[i].IsAlmost(bestQ)) {
     76          } else if (HeuristicLab.Common.Extensions.IsAlmost(activeAfterStates[i], bestQ)) {
    7777            bestIdxs.Add(i);
    7878          }
     
    8080        selectedStateIdx = actionIndexMap[bestIdxs[random.Next(bestIdxs.Count)]];
    8181      }
    82      
     82
    8383      return true;
    8484    }
     
    133133        //double alpha = 1.0 / GetFeatureTries(feature.Id);
    134134        //alpha = Math.Max(alpha, 0.001);
    135        
     135
    136136        // simple setting of constant alpha = 0.01 works very well for poly-10 (100% success rate for 20 runs within 40000 evaluations))
    137137        var alpha = 0.01;
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/SequentialDecisionPolicies/GenericGrammarPolicy.cs

    r12290 r12893  
    44using System.Linq;
    55using System.Text;
     6using System.Text.RegularExpressions;
    67using System.Threading.Tasks;
     8using HeuristicLab.Algorithms.Bandits.BanditPolicies;
     9using HeuristicLab.Algorithms.DataAnalysis;
    710using HeuristicLab.Common;
     11using HeuristicLab.Problems.DataAnalysis;
    812using HeuristicLab.Problems.GrammaticalOptimization;
    913
     
    1822    private readonly IProblem problem;
    1923    private readonly IBanditPolicy banditPolicy;
     24    public double[] OptimalPulls { get; private set; }
    2025
    2126    public GenericGrammarPolicy(IProblem problem, IBanditPolicy banditPolicy, bool useCanonicalPhrases = false) {
     
    3035    private int[] actionIndexMap; // don't allocate each time
    3136
    32     public bool TrySelect(Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx) {
     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
    3352      // fail if all states are done (corresponding state infos are disabled)
    3453      if (afterStates.All(s => Done(s))) {
     
    5574      }
    5675
    57       selectedStateIdx = actionIndexMap[banditPolicy.SelectAction(random, activeAfterStates.Take(idx))];
    58 
     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      }
    5992      return true;
    6093    }
    6194
     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    }
    62168
    63169
     
    72178    }
    73179
     180    private int rewardUpdatesSinceLastTraining = 0;
     181    private HashSet<string> statesWritten = new HashSet<string>();
    74182    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;
    75201      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
    76206        GetStateInfo(state).UpdateReward(reward);
    77 
     207        //reward *= 0.95;
    78208        // only the last state can be terminal
    79209        if (problem.Grammar.IsTerminal(state)) {
     
    83213    }
    84214
     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
    85254
    86255    public void Reset() {
    87256      stateInfo.Clear();
    88257      done.Clear();
     258      OptimalPulls = new double[300]; // max sentence length is limited anyway
    89259    }
    90260
     
    97267    public double GetValue(string state) {
    98268      var s = CanonicalState(state);
    99       if (stateInfo.ContainsKey(s)) return stateInfo[s].Value;
     269      if (stateInfo.ContainsKey(s)) return stateInfo[s].MaxReward;
    100270      else return 0.0; // TODO: check alternatives
    101271    }
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/SequentialDecisionPolicies/GenericPolicy.cs

    r12298 r12893  
    2828    private int[] actionIndexMap; // don't allocate each time
    2929
    30     public bool TrySelect(Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx) {
     30    public bool TrySelect(System.Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx) {
    3131      // fail if all states are done (corresponding state infos are disabled)
    3232      if (afterStates.All(s => Done(s))) {
     
    101101
    102102
    103     private int SelectBoltzmann(Random random, IEnumerable<double> qs, double beta = 10) {
     103    private int SelectBoltzmann(System.Random random, IEnumerable<double> qs, double beta = 10) {
    104104      // select best
    105105
     
    122122    }
    123123
    124     private int SelectEpsGreedy(Random random, IEnumerable<double> qs, double eps = 0.2) {
     124    private int SelectEpsGreedy(System.Random random, IEnumerable<double> qs, double eps = 0.2) {
    125125      if (random.NextDouble() >= eps) { // eps == 0 should be equivalent to pure exploitation, eps == 1 is pure exploration
    126126        // select best
     
    136136            bestActions.Add(aIdx);
    137137            bestQ = q;
    138           } else if (q.IsAlmost(bestQ)) {
     138          } else if (HeuristicLab.Common.Extensions.IsAlmost(q,bestQ)) {
    139139            bestActions.Add(aIdx);
    140140          }
     
    148148    }
    149149
    150     private int SelectRandom(Random random, IEnumerable<double> qs) {
     150    private int SelectRandom(System.Random random, IEnumerable<double> qs) {
    151151      return qs
    152152         .Select((aInfo, idx) => Tuple.Create(aInfo, idx))
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/SequentialDecisionPolicies/GrammarPolicy.cs

    r11793 r12893  
    2424    }
    2525
    26     public abstract bool TrySelect(Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx);
     26    public abstract bool TrySelect(System.Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx);
    2727
    2828    public virtual void UpdateReward(IEnumerable<string> stateTrajectory, double reward) {
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/SequentialDecisionPolicies/RandomPolicy.cs

    r11793 r12893  
    1313    }
    1414
    15     public override bool TrySelect(Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx) {
     15    public override bool TrySelect(System.Random random, string curState, IEnumerable<string> afterStates, out int selectedStateIdx) {
    1616      // never fail => allows re-visits of terminal states
    1717      selectedStateIdx = random.Next(afterStates.Count());
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/Solvers/ExhaustiveRandomFirstSearch.cs

    r11850 r12893  
    1313    private readonly System.Collections.Generic.SortedList<double, Sequence> sortedList = new SortedList<double, Sequence>();
    1414    private readonly IProblem problem;
    15     private readonly Random random;
     15    private readonly System.Random random;
    1616
    17     public ExhaustiveRandomFirstSearch(IProblem problem, Random random, int maxLen) {
     17    public ExhaustiveRandomFirstSearch(IProblem problem, System.Random random, int maxLen) {
    1818      this.maxLen = maxLen;
    1919      this.problem = problem;
    20       this.random = new Random();
     20      this.random = new System.Random();
    2121    }
    2222
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/Solvers/RandomSearch.cs

    r11850 r12893  
    55  public class RandomSearch : SolverBase {
    66    private readonly int maxLen;
    7     private readonly Random random;
     7    private readonly System.Random random;
    88    private readonly IProblem problem;
    99
    10     public RandomSearch(IProblem problem, Random random, int maxLen) {
     10    public RandomSearch(IProblem problem, System.Random random, int maxLen) {
    1111      this.maxLen = maxLen;
    1212      this.random = random;
  • branches/HeuristicLab.Problems.GrammaticalOptimization-gkr/HeuristicLab.Algorithms.GrammaticalOptimization/Solvers/SequentialSearch.cs

    r12876 r12893  
    66using System.Runtime.InteropServices;
    77using System.Text;
     8using System.Windows.Markup;
    89using HeuristicLab.Algorithms.Bandits;
    910using HeuristicLab.Algorithms.Bandits.BanditPolicies;
     
    4041    private readonly int maxLen;
    4142    private readonly IProblem problem;
    42     private readonly Random random;
     43    private readonly System.Random random;
    4344    private readonly int randomTries;
    4445    private readonly IGrammarPolicy behaviourPolicy;
     
    5152    private readonly List<string> stateChain;
    5253
    53     public SequentialSearch(IProblem problem, int maxLen, Random random, int randomTries, IGrammarPolicy behaviourPolicy) {
     54    public SequentialSearch(IProblem problem, int maxLen, System.Random random, int randomTries, IGrammarPolicy behaviourPolicy) {
    5455      this.maxLen = maxLen;
    5556      this.problem = problem;
     
    117118          GenerateFollowStates(n); // creates child nodes for node n
    118119
     120
    119121          int selectedChildIdx;
    120122          if (!behaviourPolicy.TrySelect(random, n.phrase, n.children.Select(ch => ch.phrase), out selectedChildIdx)) {
    121123            return false;
    122124          }
     125
    123126          phrase.ReplaceAt(phrase.FirstNonTerminalIndex, 1, n.children[selectedChildIdx].alternative);
    124127
     
    167170    }
    168171
     172
     173
    169174    private void DistributeReward(double reward) {
    170175      behaviourPolicy.UpdateReward(stateChain, reward);
    171176    }
     177
    172178
    173179
     
    178184      bestQuality = 0.0;
    179185      tries = 0;
     186      //rootNode = new TreeNode("a*b+c*d+e*f+E", new ReadonlySequence("$"));
    180187      rootNode = new TreeNode(problem.Grammar.SentenceSymbol.ToString(), new ReadonlySequence("$"));
    181188    }
     
    194201
    195202      var n = rootNode;
    196 
     203      int lvl = 0;
    197204      while (n != null) {
    198205        var phrase = n.phrase;
    199206        Console.ForegroundColor = ConsoleColor.White;
     207       
     208        if (lvl++ > 10) return;
     209
    200210        Console.WriteLine("{0,-30}", phrase);
    201211        var children = n.children;
    202212        if (children == null || !children.Any()) break;
    203         var triesEnumerable = children.Select(ch => policy.GetTries(ch.phrase));
    204         double maxTries = triesEnumerable.Where(v => !double.IsInfinity(v)).DefaultIfEmpty(1).Max();
    205         maxTries = Math.Max(maxTries, 1.0);
     213        var valuesEnumerable = children.Select(ch => policy.GetValue(ch.phrase));
     214        double maxValue = valuesEnumerable.Where(v => !double.IsInfinity(v)).DefaultIfEmpty(0).Max();
     215        maxValue = Math.Max(maxValue, 1.0);
    206216        // write phrases
    207217        foreach (var ch in children) {
    208           SetColorForValue(policy.GetTries(ch.phrase) / maxTries);
     218          //SetColorForValue(policy.GetValue(ch.phrase) / maxValue);
    209219          Console.Write(" {0,-4}", ch.phrase.Substring(Math.Max(0, ch.phrase.Length - 3), Math.Min(3, ch.phrase.Length)));
    210220        }
     
    213223        // write values
    214224        foreach (var ch in children) {
    215           SetColorForValue(policy.GetTries(ch.phrase) / maxTries);
     225          //SetColorForValue(policy.GetValue(ch.phrase) / maxValue);
    216226          if (!double.IsInfinity(policy.GetValue(ch.phrase)))
    217227            Console.Write(" {0:F2}", policy.GetValue(ch.phrase) * 10.0);
     
    223233        // write tries
    224234        foreach (var ch in children) {
    225           SetColorForValue(policy.GetTries(ch.phrase) / maxTries);
     235          //SetColorForValue(policy.GetValue(ch.phrase) / maxValue);
    226236          Console.Write(" {0,4}", policy.GetTries(ch.phrase));
    227237        }
    228238        Console.WriteLine();
    229         int selectedChildIdx;
    230         if (!policy.TrySelect(random, phrase, children.Select(ch => ch.phrase), out selectedChildIdx)) {
    231           break;
    232         }
     239        var triesArr = valuesEnumerable.ToArray();
     240        //var selectedChildIdx = Array.IndexOf(triesArr, triesArr.Max());
     241        var valuesArr = children.Select(ch => policy.GetValue(ch.phrase)).ToArray();
     242        int selectedChildIdx = Enumerable.Range(0, children.Length).OrderByDescending(i => valuesArr[i]).ThenByDescending(i => triesArr[i]).First();
     243
     244        //int selectedChildIdx;
     245        //if (!policy.TrySelect(random, phrase, children.Select(ch => ch.phrase), out selectedChildIdx)) {
     246        //  break;
     247        //}
    233248        n = n.children[selectedChildIdx];
    234249      }
Note: See TracChangeset for help on using the changeset viewer.