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
EpsilonGreedy.selectdraws a random number. If it is below it returns a uniformly random action, otherwise the action with the largest Q value, with ties broken at random.- Each call advances the schedule one step.
epsilon_atmoves fromepsilon_starttoepsilon_endoverdecay_steps, on a straight line or an exponential curve. OUNoise.sampleadvances a noise state that is pulled back toward its mean and kicked by a random draw. Add the result to a deterministic action, and callresetat the start of each episode.GaussianNoise.applyadds independent noise of standard deviationgaussian_sigmato an action and clips the result to the action bounds.boltzmann_sampleturns 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.entropy_bonusreturns the loss term and its gradient with respect to the logits. Add both to a policy-gradient loss and its gradient.
Watch out for
- If 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
resetbetween 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
| If | Use instead |
|---|---|
| Rewards are so sparse that random actions never find them | Methods beyond this lesson, such as curiosity bonuses or demonstrations |
| The policy is already stochastic, as in PPO or SAC | An entropy bonus, not added action noise |
| Exploring in the real system is unsafe | Learn in a simulator or a learned model first, as in MBPO or World Models |
Math foundations
Epsilon-greedy policy
With probability 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 .
Decay schedules
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 at step and stay there.
Ornstein-Uhlenbeck step
The first added term pulls the noise back toward its mean. The second is a fresh random kick. Because starts from , successive values are similar, which suits physical systems where a push must last several steps to have an effect.
Long-run spread of the OU noise
After many steps the pull and the kicks balance at this standard deviation, which
stationary_stdreturns. It tells you how large the noise really is compared with the action range.Boltzmann (softmax) sampling
Actions with higher value get more probability, and the temperature sets how sharply. As it becomes greedy. As it becomes uniform.
Policy entropy
Entropy measures how spread out the policy is. It is zero when one action has all the probability and when all actions are equally likely.
Gradient of the entropy
This is what the bonus sends back to the logits. An action whose log probability is above the average gets its logit pushed down, and one below the average gets pushed up, which flattens the policy.
Symbols
- probability of a random action; subscripts 0 and end mark the start and finish of the schedule
- number of discrete actions
- estimated value of action a in state s
- selections made so far, and the length of the decay (decay_steps)
- noise state of the OU process at step t
- strength of the pull back to the mean (ou_theta)
- long-run mean of the OU noise (ou_mu)
- size of the random kicks (ou_sigma)
- time step of the OU process (ou_dt)
- a standard normal draw
- temperature of Boltzmann sampling
- the policy's logit for action a
- probability the policy gives to action a
- entropy of the policy, in nats
Worked by hand
Use the defaults: goes from 1.0 to 0.05 over 10000 steps, and the OU noise has , , . Find at step 2500 under both schedules, then the long-run spread of the OU noise.
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 lossRead 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
- With 4 actions and , 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.
- 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.
- 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.
- 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 close to 1 for one action and close to 0 for the others into and see what each term does.
- A DDPG agent with OU noise works at
ou_dtof 0.01 but explores far too much atou_dtof 1.0 with the same . 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.