Rev | Line | |
---|
[11710] | 1 | using System;
|
---|
| 2 | using System.Collections.Generic;
|
---|
[11727] | 3 | using System.Diagnostics;
|
---|
[11710] | 4 | using System.Linq;
|
---|
| 5 | using System.Text;
|
---|
| 6 | using System.Threading.Tasks;
|
---|
| 7 |
|
---|
| 8 | namespace HeuristicLab.Algorithms.Bandits {
|
---|
[11732] | 9 | public class UCBNormalPolicy : IPolicy {
|
---|
[11710] | 10 |
|
---|
[11732] | 11 | public int SelectAction(Random random, IEnumerable<IPolicyActionInfo> actionInfos) {
|
---|
| 12 | var myActionInfos = actionInfos.OfType<MeanAndVariancePolicyActionInfo>().ToArray(); // TODO: performance
|
---|
[11710] | 13 | int bestAction = -1;
|
---|
| 14 | double bestQ = double.NegativeInfinity;
|
---|
[11732] | 15 | int totalTries = myActionInfos.Where(a => !a.Disabled).Sum(a => a.Tries);
|
---|
| 16 |
|
---|
| 17 | for (int a = 0; a < myActionInfos.Length; a++) {
|
---|
| 18 | if (myActionInfos[a].Disabled) continue;
|
---|
| 19 | if (totalTries <= 1 || myActionInfos[a].Tries <= 1 || myActionInfos[a].Tries <= Math.Ceiling(8 * Math.Log(totalTries))) return a;
|
---|
| 20 |
|
---|
| 21 | var tries = myActionInfos[a].Tries;
|
---|
| 22 | var avgReward = myActionInfos[a].AvgReward;
|
---|
| 23 | var rewardVariance = myActionInfos[a].RewardVariance;
|
---|
| 24 | var estVariance = 16 * rewardVariance * (Math.Log(totalTries - 1) / tries);
|
---|
[11730] | 25 | if (estVariance < 0) estVariance = 0; // numerical problems
|
---|
[11710] | 26 | var q = avgReward
|
---|
[11730] | 27 | + Math.Sqrt(estVariance);
|
---|
[11710] | 28 | if (q > bestQ) {
|
---|
| 29 | bestQ = q;
|
---|
[11727] | 30 | bestAction = a;
|
---|
[11710] | 31 | }
|
---|
| 32 | }
|
---|
[11732] | 33 | Debug.Assert(bestAction > -1);
|
---|
[11710] | 34 | return bestAction;
|
---|
| 35 | }
|
---|
[11727] | 36 |
|
---|
[11732] | 37 | public IPolicyActionInfo CreateActionInfo() {
|
---|
| 38 | return new MeanAndVariancePolicyActionInfo();
|
---|
[11727] | 39 | }
|
---|
| 40 |
|
---|
[11730] | 41 | public override string ToString() {
|
---|
| 42 | return "UCBNormalPolicy";
|
---|
| 43 | }
|
---|
[11710] | 44 | }
|
---|
| 45 | }
|
---|
Note: See
TracBrowser
for help on using the repository browser.