Skip to content

Epsilon-greedy: explore with a fixed probability

← Bandits

A desk has three execution algorithms and no idea which one fills orders best. Every day it uses the best one so far, except on a fraction epsilon of the days, when it tries another at random. A robot that tunes a controller gain picks its options the same way, in the last section.

The mean regret per day of epsilon-greedy over 1000 days, for 25 values of epsilon, on five execution algorithms.

1. A first example: five execution algorithms, one desk

Three execution algorithms fill an order well with probability 0.2, 0.5 and 0.8, and the reward is 1 when the fill is good. After 500 days the policy has learned which one to use.

import numpy as np
from dense_armor.core.online.bandit import EpsilonGreedy

rng = np.random.default_rng(0)
rate = {"twap": 0.2, "vwap": 0.5, "pov": 0.8}
desk = EpsilonGreedy(arms=["twap", "vwap", "pov"], epsilon=0.1, seed=0)
for _ in range(500):
    arm = desk.pull()
    desk.update(arm, float(rng.binomial(1, rate[arm])))
print(desk.pull())
pov

With probability 1 - epsilon play the arm with the highest running mean; otherwise play a uniformly random arm. Every arm is played once first, so an arm has at least one sample before the comparison. A constant epsilon never stops exploring: the regret grows linearly with the number of plays (Auer et al. 2002, page 5).

The mean regret per day of epsilon-greedy over 1000 days: the mean regret per day against the days seen, on five execution algorithms.

On five execution algorithms with rates 0.2, 0.35, 0.5, 0.65 and 0.8, the mean regret per day of epsilon 0 reads 0.081, 0.02 and 0.004 after 50, 200 and 1000 days, epsilon 0.1 reads 0.078, 0.036 and 0.03, and epsilon 0.3 reads 0.132, 0.094 and 0.088.

The picture follows the same 1000 days for 25 values of epsilon between 0 and 0.5, scored as the mean regret per day so far: the rate of the best algorithm minus the rate of the one that was pulled. On this easy stream the lowest regret is at epsilon 0, because every arm is played once first, and it rises with epsilon: at epsilon 0.5 it reads 0.186, 0.137 and 0.147 after 50, 200 and 1000 days. A fixed exploration costs a regret that does not go to zero.

class or function what it does
EpsilonGreedy plays the best arm so far, and a random arm with probability epsilon

2. What it does

With probability 1 - epsilon the policy plays the arm with the highest running mean reward; otherwise it plays an arm chosen uniformly at random. Each arm is played once before the first choice, so that every arm has a sample even with epsilon = 0. A constant epsilon gives a linear regret; the logarithmic bound requires epsilon_n = c K / (d^2 n), where d is a lower bound on the gap to the best arm. This class keeps epsilon constant, which is the baseline the paper compares against.

Source: Auer, P., Cesa-Bianchi, N., Fischer, P. (2002). Finite-time analysis of the multiarmed bandit problem. Machine Learning 47(2-3), 235-256. Section 3, "epsilon-greedy rule", page 5; Figure 3 and Theorem 3, pages 5-6; the choice epsilon_n = cK / (d^2 n) on page 10.

3. The parameters

Parameter Meaning Default
arms the sequence of arms, any hashables none
epsilon exploration probability, in [0, 1] 0.1
seed seed of the random generator 0

EpsilonGreedy raises ValueError if epsilon is outside [0, 1]. The methods that every policy shares (pull, update, n_seen_, state_dict, clone...) are on the shared methods page.

4. The same policy on a controller gain

A controller has three candidate gains and a good run is a reward of 1. The gain 8.0 works with probability 0.8.

import numpy as np
from dense_armor.core.online.bandit import EpsilonGreedy

rng = np.random.default_rng(0)
rate = {0.5: 0.2, 8.0: 0.8, 30.0: 0.5}
tuner = EpsilonGreedy(arms=[0.5, 8.0, 30.0], epsilon=0.1, seed=0)
for _ in range(500):
    kp = tuner.pull()
    tuner.update(kp, float(rng.binomial(1, rate[kp])))
print(tuner.pull())
8.0

After 500 tries the policy picks the gain 8.0.

API reference

EpsilonGreedy

EpsilonGreedy(
    arms: Sequence[Any], epsilon: float = 0.1, seed: int = 0
)

Bases: BanditPolicy

Epsilon-greedy policy.

With probability 1 - epsilon the policy plays the arm with the highest running mean reward; otherwise it plays an arm chosen uniformly at random. Each arm is played once before the first choice, so that every arm has a sample even with epsilon = 0. The paper shows that a constant epsilon gives a linear regret; the logarithmic bound requires epsilon_n = c K / (d^2 n), where d is a lower bound on the gap to the best arm. This class keeps epsilon constant, which is the baseline the paper compares against.

Parameters:

Name Type Description Default
arms Sequence[Any]

the sequence of arms.

required
epsilon float

exploration probability, in [0, 1].

0.1
seed int

seed of the random generator.

0

Raises:

Type Description
ValueError

if epsilon is outside [0, 1].

Examples:

>>> from dense_armor.core.online.bandit import EpsilonGreedy
>>> p = EpsilonGreedy(arms=[0, 1], epsilon=0.0, seed=0)
>>> for _ in range(20):
...     a = p.pull()
...     _ = p.update(a, 1.0 if a == 1 else 0.0)
>>> p.pull()
1
References

Auer, P., Cesa-Bianchi, N., Fischer, P. (2002). Finite-time analysis of the multiarmed bandit problem. Machine Learning 47(2-3), 235-256. Section 3, "epsilon-greedy rule", page 5; Figure 3 and Theorem 3, pages 5-6; the choice epsilon_n = cK / (d^2 n) on page 10.

Initialise the policy.

Parameters:

Name Type Description Default
arms Sequence[Any]

the sequence of arms.

required
epsilon float

exploration probability, in [0, 1].

0.1
seed int

seed of the random generator.

0

Raises:

Type Description
ValueError

if epsilon is outside [0, 1].

Source code in dense_armor/core/online/bandit/ucb.py
def __init__(
    self,
    arms: Sequence[Any],
    epsilon: float = 0.1,
    seed: int = 0,
) -> None:
    """Initialise the policy.

    Args:
        arms: the sequence of arms.
        epsilon: exploration probability, in ``[0, 1]``.
        seed: seed of the random generator.

    Raises:
        ValueError: if ``epsilon`` is outside ``[0, 1]``.
    """
    super().__init__(arms=arms, seed=seed)
    if not 0.0 <= float(epsilon) <= 1.0:
        raise ValueError("epsilon must be in [0, 1]")
    self.epsilon = float(epsilon)
    self.counts_: dict[Any, int] = {a: 0 for a in self.arms}
    self.means_: dict[Any, float] = {a: 0.0 for a in self.arms}

pull

pull(context: dict | None = None) -> Any

Choose an arm.

Plays every arm once (round-robin over the untried arms), then explores with probability epsilon and otherwise plays the arm with the highest running mean.

Parameters:

Name Type Description Default
context dict | None

unused.

None

Returns:

Type Description
Any

The chosen arm.

Source code in dense_armor/core/online/bandit/ucb.py
def pull(self, context: dict | None = None) -> Any:
    """Choose an arm.

    Plays every arm once (round-robin over the untried arms), then
    explores with probability ``epsilon`` and otherwise plays the
    arm with the highest running mean.

    Args:
        context: unused.

    Returns:
        The chosen arm.
    """
    for a in self.arms:
        if self.counts_[a] == 0:
            return a
    if self._rng.random() < self.epsilon:
        return self.arms[int(self._rng.integers(len(self.arms)))]
    best = max(self.means_.values())
    for a in self.arms:
        if self.means_[a] == best:
            return a
    return self.arms[0]

update

update(
    arm: Any, reward: float, context: dict | None = None
) -> EpsilonGreedy

Learn from the reward of arm.

Parameters:

Name Type Description Default
arm Any

the arm that was pulled.

required
reward float

the observed reward.

required
context dict | None

unused.

None

Returns:

Type Description
EpsilonGreedy

The policy itself.

Source code in dense_armor/core/online/bandit/ucb.py
def update(
    self,
    arm: Any,
    reward: float,
    context: dict | None = None,
) -> "EpsilonGreedy":
    """Learn from the reward of ``arm``.

    Args:
        arm: the arm that was pulled.
        reward: the observed reward.
        context: unused.

    Returns:
        The policy itself.
    """
    if not self._valid(arm, reward):
        self.n_missing_ += 1
        return self
    n = self.counts_[arm] + 1
    self.counts_[arm] = n
    m = self.means_[arm]
    self.means_[arm] = m + (float(reward) - m) / n
    self.n_seen_ += 1
    return self

Details

Choices

  • The figures are drawn with the library by docs/assets/bandit/make_bandit_style_figures.py. Five execution algorithms with success rates 0.2, 0.35, 0.5, 0.65 and 0.8 (or the stated gap), 1000 days, the regret of a day is the rate of the best algorithm minus the rate of the one that was pulled, and the surface is the mean over the days so far.