1 | using System;
|
---|
2 | using System.Collections.Generic;
|
---|
3 | using System.Diagnostics;
|
---|
4 | using System.Linq;
|
---|
5 | using System.Text;
|
---|
6 | using System.Threading.Tasks;
|
---|
7 |
|
---|
8 | namespace HeuristicLab.Algorithms.Bandits {
|
---|
9 | /* Kocsis et al. Bandit based Monte-Carlo Planning */
|
---|
10 | public class UCTPolicy : BanditPolicy {
|
---|
11 | private readonly int[] tries;
|
---|
12 | private readonly double[] sumReward;
|
---|
13 | private int totalTries = 0;
|
---|
14 | private readonly double c;
|
---|
15 |
|
---|
16 | public UCTPolicy(int numActions, double c = 1.0)
|
---|
17 | : base(numActions) {
|
---|
18 | this.tries = new int[numActions];
|
---|
19 | this.sumReward = new double[numActions];
|
---|
20 | this.c = c;
|
---|
21 | }
|
---|
22 |
|
---|
23 | public override int SelectAction() {
|
---|
24 | int bestAction = -1;
|
---|
25 | double bestQ = double.NegativeInfinity;
|
---|
26 | foreach (var a in Actions) {
|
---|
27 | if (tries[a] == 0) return a;
|
---|
28 | var q = sumReward[a] / tries[a] + 2 * c * Math.Sqrt(Math.Log(totalTries) / tries[a]);
|
---|
29 | if (q > bestQ) {
|
---|
30 | bestQ = q;
|
---|
31 | bestAction = a;
|
---|
32 | }
|
---|
33 | }
|
---|
34 | return bestAction;
|
---|
35 | }
|
---|
36 | public override void UpdateReward(int action, double reward) {
|
---|
37 | Debug.Assert(Actions.Contains(action));
|
---|
38 | totalTries++;
|
---|
39 | tries[action]++;
|
---|
40 | sumReward[action] += reward;
|
---|
41 | }
|
---|
42 |
|
---|
43 | public override void DisableAction(int action) {
|
---|
44 | base.DisableAction(action);
|
---|
45 | totalTries -= tries[action];
|
---|
46 | tries[action] = -1;
|
---|
47 | sumReward[action] = 0;
|
---|
48 | }
|
---|
49 |
|
---|
50 | public override void Reset() {
|
---|
51 | base.Reset();
|
---|
52 | totalTries = 0;
|
---|
53 | Array.Clear(tries, 0, tries.Length);
|
---|
54 | Array.Clear(sumReward, 0, sumReward.Length);
|
---|
55 | }
|
---|
56 | public override void PrintStats() {
|
---|
57 | for (int i = 0; i < sumReward.Length; i++) {
|
---|
58 | if (tries[i] >= 0) {
|
---|
59 | Console.Write("{0,5:F2}", sumReward[i] / tries[i]);
|
---|
60 | } else {
|
---|
61 | Console.Write("{0,5}", "");
|
---|
62 | }
|
---|
63 | }
|
---|
64 | Console.WriteLine();
|
---|
65 | }
|
---|
66 | public override string ToString() {
|
---|
67 | return string.Format("UCTPolicy({0:F2})", c);
|
---|
68 | }
|
---|
69 | }
|
---|
70 | }
|
---|