source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.Bandits/BanditPolicies/UCB1Policy.cs @ 11745

Last change on this file since 11745 was 11745, checked in by gkronber, 7 years ago

#2283: worked on contextual MCTS

File size: 1.2 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using System.Text;
6using System.Threading.Tasks;
7
8namespace HeuristicLab.Algorithms.Bandits.BanditPolicies {
9  // policy for k-armed bandit (see Auer et al. 2002)
10  public class UCB1Policy : IBanditPolicy {
11    public int SelectAction(Random random, IEnumerable<IBanditPolicyActionInfo> actionInfos) {
12      var myActionInfos = actionInfos.OfType<DefaultPolicyActionInfo>();
13      int bestAction = -1;
14      double bestQ = double.NegativeInfinity;
15      int totalTries = myActionInfos.Where(a => !a.Disabled).Sum(a => a.Tries);
16
17      int aIdx = -1;
18      foreach (var aInfo in myActionInfos) {
19        aIdx++;
20        if (aInfo.Disabled) continue;
21        if (aInfo.Tries == 0) return aIdx;
22        var q = aInfo.SumReward / aInfo.Tries + Math.Sqrt((2 * Math.Log(totalTries)) / aInfo.Tries);
23        if (q > bestQ) {
24          bestQ = q;
25          bestAction = aIdx;
26        }
27      }
28      Debug.Assert(bestAction > -1);
29      return bestAction;
30    }
31
32    public IBanditPolicyActionInfo CreateActionInfo() {
33      return new DefaultPolicyActionInfo();
34    }
35    public override string ToString() {
36      return "UCB1Policy";
37    }
38  }
39}
Note: See TracBrowser for help on using the repository browser.