Free cookie consent management tool by TermsFeed Policy Generator

source: branches/HeuristicLab.Problems.GrammaticalOptimization/HeuristicLab.Algorithms.Bandits/Policies/UCTPolicy.cs @ 12503

Last change on this file since 12503 was 12503, checked in by aballeit, 9 years ago

#2283 added GUI and charts; fixed MCTS

File size: 1.6 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Diagnostics;
4using System.Linq;
5using System.Text;
6using System.Threading.Tasks;
7using HeuristicLab.Common;
8
9namespace HeuristicLab.Algorithms.Bandits.BanditPolicies {
10  /* Kocsis et al. Bandit based Monte-Carlo Planning */
11  public class UCTPolicy : IBanditPolicy {
12    private readonly double c;
13
14    public UCTPolicy(double c = 1.0) {
15      this.c = c;
16    }
17
18
19    public int SelectAction(Random random, IEnumerable<IBanditPolicyActionInfo> actionInfos) {
20      var myActionInfos = actionInfos.OfType<DefaultPolicyActionInfo>();
21      double bestQ = double.NegativeInfinity;
22      int totalTries = myActionInfos.Sum(a => a.Tries);
23
24      int aIdx = -1;
25      var bestActions = new List<int>();
26      foreach (var aInfo in myActionInfos) {
27        aIdx++;
28        double q;
29        if (aInfo.Tries == 0) {
30          q = double.PositiveInfinity;
31        } else {
32            q = aInfo.SumReward / aInfo.Tries + 2.0 * c * Math.Sqrt(Math.Log(totalTries) / aInfo.Tries);
33        }
34        if (q > bestQ) {
35          bestActions.Clear();
36          bestQ = q;
37          bestActions.Add(aIdx);
38        } else if (q.IsAlmost(bestQ)) {
39          bestActions.Add(aIdx);
40        }
41
42      }
43      Debug.Assert(bestActions.Any());
44      return bestActions.SelectRandom(random);
45    }
46
47    public IBanditPolicyActionInfo CreateActionInfo() {
48      return new DefaultPolicyActionInfo();
49    }
50
51    public override string ToString() {
52      return string.Format("UCTPolicy({0:F2})", c);
53    }
54  }
55}
Note: See TracBrowser for help on using the repository browser.