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 | using HeuristicLab.Common;
|
---|
8 |
|
---|
9 | namespace HeuristicLab.Algorithms.Bandits.BanditPolicies {
|
---|
10 | // policy for k-armed bandit (see Auer et al. 2002)
|
---|
11 | public class UCB1Policy : IBanditPolicy {
|
---|
12 | public double MaxReward { get; private set; }
|
---|
13 | public UCB1Policy(double maxReward = 1.0) {
|
---|
14 | this.MaxReward = maxReward;
|
---|
15 | }
|
---|
16 | public int SelectAction(Random random, IEnumerable<IBanditPolicyActionInfo> actionInfos) {
|
---|
17 | var myActionInfos = actionInfos.OfType<DefaultPolicyActionInfo>();
|
---|
18 | double bestQ = double.NegativeInfinity;
|
---|
19 | int totalTries = myActionInfos.Sum(a => a.Tries);
|
---|
20 |
|
---|
21 | var bestActions = new List<int>();
|
---|
22 | int aIdx = -1;
|
---|
23 | foreach (var aInfo in myActionInfos) {
|
---|
24 | aIdx++;
|
---|
25 | double q;
|
---|
26 | if (aInfo.Tries == 0) {
|
---|
27 | q = double.PositiveInfinity;
|
---|
28 | } else {
|
---|
29 |
|
---|
30 | //q = aInfo.SumReward / aInfo.Tries + MaxReward * Math.Sqrt((2 * Math.Log(totalTries)) / aInfo.Tries);
|
---|
31 | q = aInfo.MaxReward + MaxReward * Math.Sqrt((2 * Math.Log(totalTries)) / aInfo.Tries);
|
---|
32 | }
|
---|
33 | if (q > bestQ) {
|
---|
34 | bestQ = q;
|
---|
35 | bestActions.Clear();
|
---|
36 | bestActions.Add(aIdx);
|
---|
37 | } else if (q.IsAlmost(bestQ)) {
|
---|
38 | bestActions.Add(aIdx);
|
---|
39 | }
|
---|
40 | }
|
---|
41 | Debug.Assert(bestActions.Any());
|
---|
42 | return bestActions.SelectRandom(random);
|
---|
43 | }
|
---|
44 |
|
---|
45 | public IBanditPolicyActionInfo CreateActionInfo() {
|
---|
46 | return new DefaultPolicyActionInfo();
|
---|
47 | }
|
---|
48 | public override string ToString() {
|
---|
49 | return string.Format("UCB1Policy({0})", MaxReward);
|
---|
50 | }
|
---|
51 | }
|
---|
52 | }
|
---|