Line | |
---|
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 | public class UCB1Policy : IPolicy {
|
---|
10 | public int SelectAction(Random random, IEnumerable<IPolicyActionInfo> actionInfos) {
|
---|
11 | var myActionInfos = actionInfos.OfType<DefaultPolicyActionInfo>().ToArray(); // TODO: performance
|
---|
12 | int bestAction = -1;
|
---|
13 | double bestQ = double.NegativeInfinity;
|
---|
14 | int totalTries = myActionInfos.Where(a => !a.Disabled).Sum(a => a.Tries);
|
---|
15 |
|
---|
16 | for (int a = 0; a < myActionInfos.Length; a++) {
|
---|
17 | if (myActionInfos[a].Disabled) continue;
|
---|
18 | if (myActionInfos[a].Tries == 0) return a;
|
---|
19 | var q = myActionInfos[a].SumReward / myActionInfos[a].Tries + Math.Sqrt((2 * Math.Log(totalTries)) / myActionInfos[a].Tries);
|
---|
20 | if (q > bestQ) {
|
---|
21 | bestQ = q;
|
---|
22 | bestAction = a;
|
---|
23 | }
|
---|
24 | }
|
---|
25 | Debug.Assert(bestAction > -1);
|
---|
26 | return bestAction;
|
---|
27 | }
|
---|
28 |
|
---|
29 | public IPolicyActionInfo CreateActionInfo() {
|
---|
30 | return new DefaultPolicyActionInfo();
|
---|
31 | }
|
---|
32 | public override string ToString() {
|
---|
33 | return "UCB1Policy";
|
---|
34 | }
|
---|
35 | }
|
---|
36 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.