Sign in

Exploration

Exploration strategies

Five ways to make an agent try actions it does not yet think are best: epsilon-greedy, Ornstein-Uhlenbeck noise, Gaussian noise, Boltzmann sampling and an entropy bonus.

Overview

An agent that always takes the action it currently rates highest never finds out whether another action is better. Exploration is the deliberate choice to act against the current estimate some of the time. The simplest form flips a biased coin: mostly act greedily, sometimes act at random, and make random moves rarer as the estimates improve. For continuous actions you add noise to the chosen action instead. For a policy that outputs probabilities, you reward the policy for staying spread out, so it does not commit to one action before it has evidence.

A short history

The trade-off between exploring and exploiting was first studied in bandit problems in the mid twentieth century, and epsilon-greedy and Boltzmann sampling are the simple rules that came out of that work. The Ornstein-Uhlenbeck process is a 1930 model from physics that the DDPG paper borrowed in 2015 to make smooth, correlated action noise. TD3 later showed that plain Gaussian noise works as well. The entropy bonus dates to Ronald Williams and Jing Peng in 1991 and is now part of A3C, PPO and SAC.

How it works

  1. EpsilonGreedy.select draws a random number. If it is below ε\varepsilon it returns a uniformly random action, otherwise the action with the largest Q value, with ties broken at random.
  2. Each call advances the schedule one step. epsilon_at moves ε\varepsilon from epsilon_start to epsilon_end over decay_steps, on a straight line or an exponential curve.
  3. OUNoise.sample advances a noise state that is pulled back toward its mean and kicked by a random draw. Add the result to a deterministic action, and call reset at the start of each episode.
  4. GaussianNoise.apply adds independent noise of standard deviation gaussian_sigma to an action and clips the result to the action bounds.
  5. boltzmann_sample turns Q values into probabilities with a softmax at a given temperature and samples from them, so better actions are tried more often than worse ones.
  6. entropy_bonus returns the loss term −cH H-c_H \, H and its gradient with respect to the logits. Add both to a policy-gradient loss and its gradient.

Watch out for

  • If ε\varepsilon decays to its floor before the agent has seen any reward, the agent settles on its early, uninformed estimates and rarely leaves them.
  • Epsilon-greedy explores without regard to value: a clearly terrible action is tried as often as a promising one. In tasks where one bad move ends the episode this wastes most of the data.
  • OU noise carries over from step to step. If you forget reset between episodes, each episode starts with a leftover push in one direction.
  • Boltzmann sampling depends on the scale of the Q values. The same temperature is nearly greedy when values differ by 100 and nearly uniform when they differ by 0.01.
  • An entropy coefficient that is too large keeps the policy close to uniform, so it never commits to the good actions it has found.

Use cases

When to use it

Use epsilon-greedy or Boltzmann sampling with value methods on discrete actions (Q-learning, DQN), OU or Gaussian noise with deterministic continuous policies (DDPG, TD3), and the entropy bonus with policy-gradient methods (A2C, PPO).

In industry

Games and simulation
DQN agents on Atari start with fully random actions and anneal epsilon down to a small value as their value estimates improve.
Robotics
Continuous control agents add Gaussian noise to motor commands during training so that they try nearby actions without jerky motion.
Recommendation and advertising
Systems show a small share of items at random, an epsilon-greedy rule, to keep learning about options they currently rate low.

Choosing it: what must hold

  • A clear match to the action type: epsilon-greedy or Boltzmann for discrete actions, added noise for continuous deterministic policies.
  • A schedule for reducing exploration, or an entropy weight, chosen for the length of training.
  • Rewards that random or noisy behaviour can reach at least sometimes.

When to choose something else

IfUse instead
Rewards are so sparse that random actions never find themMethods beyond this lesson, such as curiosity bonuses or demonstrations
The policy is already stochastic, as in PPO or SACAn entropy bonus, not added action noise
Exploring in the real system is unsafeLearn in a simulator or a learned model first, as in MBPO or World Models

Math foundations

  1. Epsilon-greedy policy

    π(a∣s)={1−ε+ε∣A∣a=arg⁡max⁡bQ(s,b)ε∣A∣otherwise\pi(a \mid s) = \begin{cases} 1 - \varepsilon + \dfrac{\varepsilon}{|\mathcal{A}|} & a = \arg\max_{b} Q(s, b) \\[6pt] \dfrac{\varepsilon}{|\mathcal{A}|} & \text{otherwise} \end{cases}

    With probability ε\varepsilon the action is uniform over all actions, the greedy one included. So the greedy action gets its own share of the random draws on top of 1−ε1 - \varepsilon.

  2. Decay schedules

    εt=ε0+f (εend−ε0)orεt=ε0(εendε0)f,f=min⁡ ⁣(tT,1)\varepsilon_t = \varepsilon_0 + f \, (\varepsilon_{\text{end}} - \varepsilon_0) \quad\text{or}\quad \varepsilon_t = \varepsilon_0 \left(\frac{\varepsilon_{\text{end}}}{\varepsilon_0}\right)^{f}, \qquad f = \min\!\left(\frac{t}{T}, 1\right)

    The linear form drops by the same amount every step. The exponential form drops by the same ratio every step, so it falls fast at first and slowly later. Both reach εend\varepsilon_{\text{end}} at step TT and stay there.

  3. Ornstein-Uhlenbeck step

    xt+1=xt+θ (μ−xt) Δt+σΔt  ξt,ξt∼N(0,1)x_{t+1} = x_t + \theta \, (\mu - x_t) \, \Delta t + \sigma \sqrt{\Delta t} \; \xi_t, \qquad \xi_t \sim \mathcal{N}(0, 1)

    The first added term pulls the noise back toward its mean. The second is a fresh random kick. Because xt+1x_{t+1} starts from xtx_t, successive values are similar, which suits physical systems where a push must last several steps to have an effect.

  4. Long-run spread of the OU noise

    std⁡(x∞)=σΔt1−(1−θ Δt)2\operatorname{std}(x_\infty) = \sigma \sqrt{\frac{\Delta t}{1 - (1 - \theta \, \Delta t)^{2}}}

    After many steps the pull and the kicks balance at this standard deviation, which stationary_std returns. It tells you how large the noise really is compared with the action range.

  5. Boltzmann (softmax) sampling

    π(a∣s)=exp⁡ ⁣(Q(s,a)/τ)∑bexp⁡ ⁣(Q(s,b)/τ)\pi(a \mid s) = \frac{\exp\!\big(Q(s, a) / \tau\big)}{\sum_{b} \exp\!\big(Q(s, b) / \tau\big)}

    Actions with higher value get more probability, and the temperature sets how sharply. As τ→0\tau \to 0 it becomes greedy. As τ→∞\tau \to \infty it becomes uniform.

  6. Policy entropy

    H=−∑apalog⁡pa,pa=eza∑bezbH = -\sum_{a} p_a \log p_a, \qquad p_a = \frac{e^{z_a}}{\sum_{b} e^{z_b}}

    Entropy measures how spread out the policy is. It is zero when one action has all the probability and log⁡∣A∣\log |\mathcal{A}| when all actions are equally likely.

  7. Gradient of the entropy

    ∂H∂za=− pa (log⁡pa+H)\frac{\partial H}{\partial z_a} = -\,p_a \, \big(\log p_a + H\big)

    This is what the bonus sends back to the logits. An action whose log probability is above the average −H-H gets its logit pushed down, and one below the average gets pushed up, which flattens the policy.

Symbols

ε\varepsilon
probability of a random action; subscripts 0 and end mark the start and finish of the schedule
∣A∣|\mathcal{A}|
number of discrete actions
Q(s,a)Q(s, a)
estimated value of action a in state s
t,  Tt,\; T
selections made so far, and the length of the decay (decay_steps)
xtx_t
noise state of the OU process at step t
θ\theta
strength of the pull back to the mean (ou_theta)
μ\mu
long-run mean of the OU noise (ou_mu)
σ\sigma
size of the random kicks (ou_sigma)
Δt\Delta t
time step of the OU process (ou_dt)
ξt\xi_t
a standard normal draw
τ\tau
temperature of Boltzmann sampling
zaz_a
the policy's logit for action a
pap_a
probability the policy gives to action a
HH
entropy of the policy, in nats

Worked by hand

Use the defaults: ε\varepsilon goes from 1.0 to 0.05 over 10000 steps, and the OU noise has θ=0.15\theta = 0.15, σ=0.2\sigma = 0.2, Δt=0.01\Delta t = 0.01. Find ε\varepsilon at step 2500 under both schedules, then the long-run spread of the OU noise.

f=2500/10000=0.25f = 2500 / 10000 = 0.25
εlinear=1.0+0.25×(0.05−1.0)=0.7625\varepsilon_{\text{linear}} = 1.0 + 0.25 \times (0.05 - 1.0) = 0.7625
εexp=1.0×0.050.25=0.4729\varepsilon_{\text{exp}} = 1.0 \times 0.05^{0.25} = 0.4729
1−(1−0.15×0.01)2=1−0.99852=0.00299781 - (1 - 0.15 \times 0.01)^{2} = 1 - 0.9985^{2} = 0.0029978
std⁡(x∞)=0.2×0.01/0.0029978=0.365\operatorname{std}(x_\infty) = 0.2 \times \sqrt{0.01 / 0.0029978} = 0.365

A quarter of the way through, the exponential schedule already explores much less than the linear one. The OU noise settles at a spread of about 0.37, far above the 0.02 size of a single kick, because kicks accumulate.

Visual example

Loading the example.

Try this

  • Set the selections to 2.5 thousand and switch the schedule: ε is 0.7625 on the straight line and 0.4729 on the exponential curve.
  • Lower the temperature τ toward 0.05 and watch Boltzmann sampling turn greedy, then raise it to 2.
  • Open continuous actions and raise θ: the OU path stops drifting and starts to look like the Gaussian noise.

Code sample

import numpy as np
from impl import EpsilonGreedy, OUNoise, entropy_bonus
from config import ExplorationConfig

cfg = ExplorationConfig(decay_steps=1000, action_dim=2)
eps = EpsilonGreedy(cfg)
action = eps.select(np.array([0.1, 0.9, 0.3]))    # random with probability eps.epsilon, else argmax; steps the schedule

noise = OUNoise(cfg)
noisy_action = np.clip(np.zeros(2) + noise.sample(), -1.0, 1.0)

loss, dlogits = entropy_bonus(np.array([[2.0, 0.0, -1.0]]), cfg.entropy_coef)   # add to the policy loss
Read the implementation (129 lines)
"""Exploration strategies: epsilon-greedy, Ornstein-Uhlenbeck and Gaussian noise, Boltzmann sampling, entropy bonus.

NumPy only. Every random draw comes from a generator seeded by the config.
"""
from __future__ import annotations

import numpy as np

try:
    from .config import ExplorationConfig
except ImportError:  # run from the template's own folder
    from config import ExplorationConfig


def softmax(logits: np.ndarray) -> np.ndarray:
    """Softmax over the last axis. logits: shape (..., n_actions)."""
    z = np.asarray(logits, dtype=float)
    z = z - z.max(axis=-1, keepdims=True)
    e = np.exp(z)
    return e / e.sum(axis=-1, keepdims=True)


class EpsilonGreedy:
    """Random action with probability epsilon, greedy action otherwise, with a decaying epsilon."""

    def __init__(self, config: ExplorationConfig | None = None) -> None:
        self.config = config or ExplorationConfig()
        self.rng = np.random.default_rng(self.config.seed)
        self.step = 0

    def epsilon_at(self, step: int) -> float:
        """Epsilon after `step` selections."""
        c = self.config
        frac = min(max(step, 0) / c.decay_steps, 1.0)
        if c.schedule == "linear":
            return c.epsilon_start + frac * (c.epsilon_end - c.epsilon_start)
        if c.epsilon_end == 0.0 or c.epsilon_start == 0.0:
            return c.epsilon_start if frac < 1.0 else c.epsilon_end
        return c.epsilon_start * (c.epsilon_end / c.epsilon_start) ** frac

    @property
    def epsilon(self) -> float:
        return self.epsilon_at(self.step)

    def select(self, q_values: np.ndarray, advance: bool = True) -> int:
        """Pick an action for one state. q_values: shape (n_actions,). `advance` moves the schedule one step."""
        q = np.asarray(q_values, dtype=float)
        if self.rng.random() < self.epsilon:
            action = int(self.rng.integers(len(q)))
        else:
            best = np.flatnonzero(q == q.max())  # break ties at random so the first action is not favoured
            action = int(self.rng.choice(best))
        if advance:
            self.step += 1
        return action


class OUNoise:
    """Ornstein-Uhlenbeck process: temporally correlated noise that drifts back toward `ou_mu`."""

    def __init__(self, config: ExplorationConfig | None = None) -> None:
        self.config = config or ExplorationConfig()
        self.rng = np.random.default_rng(self.config.seed)
        self.state = np.full(self.config.action_dim, self.config.ou_mu, dtype=float)

    def reset(self) -> None:
        """Put the process back at its mean (call at the start of every episode)."""
        self.state = np.full(self.config.action_dim, self.config.ou_mu, dtype=float)

    def sample(self) -> np.ndarray:
        """Advance one time step and return the noise, shape (action_dim,)."""
        c = self.config
        kick = c.ou_sigma * np.sqrt(c.ou_dt) * self.rng.standard_normal(c.action_dim)
        self.state = self.state + c.ou_theta * (c.ou_mu - self.state) * c.ou_dt + kick
        return self.state.copy()

    def stationary_std(self) -> float:
        """Long-run standard deviation of the discretized process: sigma * sqrt(dt / (1 - (1 - theta * dt)^2))."""
        c = self.config
        a = 1.0 - c.ou_theta * c.ou_dt
        return float(c.ou_sigma * np.sqrt(c.ou_dt / (1.0 - a * a)))


class GaussianNoise:
    """Independent zero-mean Gaussian noise for continuous actions."""

    def __init__(self, config: ExplorationConfig | None = None) -> None:
        self.config = config or ExplorationConfig()
        self.rng = np.random.default_rng(self.config.seed)

    def sample(self) -> np.ndarray:
        """Return one noise vector, shape (action_dim,)."""
        return self.config.gaussian_sigma * self.rng.standard_normal(self.config.action_dim)

    def apply(self, action: np.ndarray, low: float = -1.0, high: float = 1.0) -> np.ndarray:
        """Add noise to `action` (shape (action_dim,)) and clip the result to [low, high]."""
        return np.clip(np.asarray(action, dtype=float) + self.sample(), low, high)


def boltzmann_sample(q_values: np.ndarray, temperature: float, rng: np.random.Generator) -> int:
    """Sample one action with probability softmax(q_values / temperature). q_values: shape (n_actions,)."""
    if temperature <= 0:
        raise ValueError(f"temperature must be positive, got {temperature}")
    probs = softmax(np.asarray(q_values, dtype=float) / temperature)
    return int(rng.choice(len(probs), p=probs))


def categorical_entropy(logits: np.ndarray) -> np.ndarray:
    """Entropy H = -sum_a p_a log p_a of softmax(logits), in nats. logits: (..., n_actions) -> (...)."""
    z = np.asarray(logits, dtype=float)
    z = z - z.max(axis=-1, keepdims=True)
    log_p = z - np.log(np.exp(z).sum(axis=-1, keepdims=True))
    return -(np.exp(log_p) * log_p).sum(axis=-1)


def entropy_bonus(logits: np.ndarray, entropy_coef: float) -> tuple[float, np.ndarray]:
    """Loss term that rewards high policy entropy, and its gradient.

    logits: shape (batch, n_actions).
    Returns (loss, dlogits) with loss = -entropy_coef * mean_b H(softmax(logits_b)) and dlogits of the same shape
    as logits. For one row, dH/dlogit_a = -p_a * (log p_a + H).
    """
    z = np.asarray(logits, dtype=float)
    p = softmax(z)
    log_p = np.log(np.clip(p, 1e-300, None))
    h = -(p * log_p).sum(axis=-1, keepdims=True)
    dh = -p * (log_p + h)
    batch = z.shape[0]
    return float(-entropy_coef * h.mean()), -entropy_coef * dh / batch
Repository
Not published yet
Needs
Python 3.10 and NumPy
Tests
12, run with python3 -m unittest -v

Practice

Create EpsilonGreedy(ExplorationConfig(decay_steps=1000)) and call select 1000 times on the Q values 0.1, 0.9, 0.3, recording epsilon and the chosen action. Plot the share of greedy choices in windows of 100 steps. Repeat with schedule set to exponential. Then draw 5000 values from OUNoise.sample and compare their standard deviation with stationary_std().

Check on learning

  1. With 4 actions and ε=0.2\varepsilon = 0.2, how often is the greedy action taken? Why is the answer not 0.8?
    A way to think about it

    The random branch picks uniformly among all actions. Add the greedy action's share of that branch to the greedy branch.

  2. An agent in a maze gets reward only at the exit, about 200 correct moves away. Why does epsilon-greedy with independent random moves struggle here, and which of the other strategies has a property that helps?
    A way to think about it

    Compute how far a sequence of independent left and right moves travels on average. Then think about what correlated noise does over many steps.

  3. You double every reward in the environment. Which of the five strategies changes its behaviour, and in which direction?
    A way to think about it

    Go through them one at a time and ask whether the rule depends on the size of the Q values or only on their order.

  4. The entropy gradient is zero for a uniform policy. Is it also zero for a policy that puts all its probability on one action? What does that mean for a policy that has already collapsed?
    A way to think about it

    Put pap_a close to 1 for one action and close to 0 for the others into −pa(log⁡pa+H)-p_a(\log p_a + H) and see what each term does.

  5. A DDPG agent with OU noise works at ou_dt of 0.01 but explores far too much at ou_dt of 1.0 with the same σ\sigma. Explain using the long-run spread.
    A way to think about it

    Evaluate the stationary standard deviation for both settings and compare each with an action range of -1 to 1.