Chapter 14: Reinforcement Learning
Reinforcement learning is learning what to do, how to map situations to actions, so as to maximize a numerical reward signal.
Richard Sutton and Andrew Barto, Reinforcement Learning: An Introduction
14.1 Learning from Rewards¶
In supervised learning a teacher gives the right answer for every example. Nobody tells a child the right muscle commands for riding a bicycle: it tries, falls, and adjusts. Reinforcement learning (RL) learns from such trial and error, guided by a numerical reward.
At each step the agent observes the state , chooses an action , and the environment answers with a reward and a new state . The agent’s goal is to collect as much reward as possible over time, not just now.
| Supervised learning | Reinforcement learning | |
|---|---|---|
| Feedback | the correct answer | a reward: how good, not what would have been best |
| Timing | immediate | often delayed (a chess game is won or lost at the end) |
| Data | a fixed dataset | produced by the agent’s own actions |
| Main difficulty | generalisation | credit assignment and exploration |
Where it is used. Games (backgammon, Atari, Go, chess), robot control, data-centre cooling, recommendation, traffic lights, chip layout, and the fine-tuning of chatbots from human preferences (RLHF, Section 14.10).
14.2 Markov Decision Processes¶
A Markov decision process (MDP) is the mathematical model of the loop: a tuple with
: the states; : the actions;
: the transition probabilities (the environment may be random: a robot’s wheel slips);
: the reward;
: the discount factor.
The Markov property: the next state depends only on the current state and action, not on the earlier history. The state must contain everything that matters (in chess: the board and whose turn it is).
A policy is the agent’s behaviour: a rule , or probabilities .
The return¶
The agent maximises the return, the discounted sum of future rewards:
Discounting keeps the sum finite and prefers sooner rewards; close to 1 makes the agent far-sighted, close to 0 short-sighted.
Example. Rewards (a goal reached after three steps) with : . Reaching the goal in two steps would give 0.9: discounting rewards speed.
14.3 Value Functions and the Bellman Equations¶
How good is it to be in a state? The state-value function of a policy is the expected return starting from and following :
The action-value function fixes the first action:
Because , values satisfy a recursive equation, the Bellman expectation equation:
“The value of a state is the reward I expect now, plus the discounted value of where I expect to land.”
The optimal values and are the best achievable by any policy. They satisfy the Bellman optimality equations:
Once we know , acting optimally is easy: . Almost every RL algorithm is a way of solving these equations, exactly or approximately.
14.4 Dynamic Programming¶
When the model ( and ) is known, the Bellman equations can be solved directly.
Policy evaluation computes by turning the Bellman equation into an update and repeating it until the values stop changing.
Policy iteration alternates:
evaluate the current policy ();
improve it greedily: ;
until the policy no longer changes. It converges in few iterations.
Value iteration merges the two: it repeats the optimality update
for every state, until convergence, then reads the greedy policy off .
Worked example: a corridor¶
States and a terminal goal in a row. Actions: left or right (moving left from hits a wall and stays). Each move costs -1, except entering , which gives +10. , and we start from .
| Sweep | |||
|---|---|---|---|
| 0 | 0 | 0 | 0 |
| 1 | |||
| 2 | 10 | ||
| 3 | 8 | 10 | |
| 4 | 6.2 (no change: converged) | 8 | 10 |
(Each sweep uses the values of the previous sweep; in each state the best action is right.) The good news travels back from the goal one state per sweep, and the greedy policy is “always go right”.
Source
import numpy as np
import matplotlib.pyplot as plt
# A 4x5 grid world: goal +10 at top right, a pit -10 below it, walls, -1 per step, 80% intended move / 10% each side.
ROWS, COLS = 4, 5
GOAL, PIT, WALLS = (0, 4), (1, 4), {(1, 1), (2, 3)}
MOVES = {'↑': (-1, 0), '→': (0, 1), '↓': (1, 0), '←': (0, -1)}
SIDES = {'↑': '←→', '↓': '←→', '←': '↑↓', '→': '↑↓'}
states = [(r, c) for r in range(ROWS) for c in range(COLS) if (r, c) not in WALLS]
def step(s, a):
r, c = s[0] + MOVES[a][0], s[1] + MOVES[a][1]
return s if not (0 <= r < ROWS and 0 <= c < COLS) or (r, c) in WALLS else (r, c)
def outcomes(s, a):
return [(0.8, step(s, a))] + [(0.1, step(s, side)) for side in SIDES[a]]
def reward(s2):
return 10 if s2 == GOAL else (-10 if s2 == PIT else -1)
V = {s: 0.0 for s in states}
for sweep in range(100):
newV = {s: 0.0 if s in (GOAL, PIT) else max(sum(p * (reward(s2) + 0.9 * V[s2]) for p, s2 in outcomes(s, a)) for a in MOVES) for s in states}
if max(abs(newV[s] - V[s]) for s in states) < 1e-6: break
V = newV
policy = {s: max(MOVES, key=lambda a: sum(p * (reward(s2) + 0.9 * V[s2]) for p, s2 in outcomes(s, a))) for s in states if s not in (GOAL, PIT)}
grid = np.full((ROWS, COLS), np.nan)
for s in states:
if s not in (GOAL, PIT): grid[s] = V[s]
fig, ax = plt.subplots(figsize=(6.5, 4.6))
ax.imshow(grid, cmap='RdYlGn', vmin=-6, vmax=8)
for s in states:
label = 'GOAL\n+10' if s == GOAL else ('PIT\n−10' if s == PIT else f'{policy[s]}\n{V[s]:.1f}')
ax.text(s[1], s[0], label, ha='center', va='center', fontsize=12 if s in policy else 10)
for w in WALLS: ax.add_patch(plt.Rectangle((w[1] - 0.5, w[0] - 0.5), 1, 1, color='dimgray'))
ax.add_patch(plt.Rectangle((GOAL[1] - 0.5, GOAL[0] - 0.5), 1, 1, color='mediumseagreen', zorder=0))
ax.add_patch(plt.Rectangle((PIT[1] - 0.5, PIT[0] - 0.5), 1, 1, color='indianred', zorder=0))
ax.set_xticks([]); ax.set_yticks([])
ax.set_title(f'Value iteration ({sweep} sweeps): V* and the greedy policy\nmoves succeed 80% of the time, slip sideways 20%')
plt.show()
Values fall with the distance from the goal. The cells under the pit point away from it: the only short way up passes through the pit, so the agent goes round. And because moves slip, every value is lower than the step count alone would give: the 20% chance of drifting sideways costs extra steps, and next to the pit it carries a real risk.
Limits of dynamic programming. It needs the model (, ), which we rarely have for real problems, and it sweeps every state, impossible for chess ( positions) or for continuous states. The rest of the chapter learns from experience instead.
14.5 Exploration and Exploitation¶
To learn, an agent must sometimes try actions that look worse: perhaps they are better than it thinks. But every exploratory action costs reward. The simplest setting to study this dilemma is the multi-armed bandit: slot machines with unknown average payouts, one state, and the goal of earning as much as possible in pulls.
The agent keeps an estimate of each arm’s mean reward (the average of what it has received from it) and:
greedy: always pulls the best-looking arm. It can lock onto a mediocre arm forever.
ε-greedy: with probability ε pulls a random arm, otherwise the best-looking one.
UCB (upper confidence bound): pulls the arm with the highest optimistic estimate
where counts how often arm was pulled. Rarely tried arms get a bonus: “optimism in the face of uncertainty”.
Source
rng = np.random.default_rng(0)
def run_bandit(strategy, k=10, T=1000, runs=300):
total = np.zeros(T)
for _ in range(runs):
means = rng.normal(0, 1, k); Q = np.zeros(k); N = np.zeros(k)
for t in range(T):
if strategy == 'greedy': a = np.argmax(Q)
elif strategy == 'ε-greedy (ε = 0.1)': a = rng.integers(k) if rng.random() < 0.1 else np.argmax(Q)
else: a = np.argmax(Q + 2 * np.sqrt(np.log(t + 1) / (N + 1e-9))) if N.min() > 0 else int(np.argmin(N))
r = rng.normal(means[a], 1); N[a] += 1; Q[a] += (r - Q[a]) / N[a]
total[t] += r
return total / runs
plt.figure(figsize=(8, 3.4))
for name in ['greedy', 'ε-greedy (ε = 0.1)', 'UCB (c = 2)']:
curve = run_bandit(name)
plt.plot(np.convolve(curve, np.ones(20) / 20, mode='valid'), label=name)
plt.xlabel('pull'); plt.ylabel('average reward'); plt.legend(); plt.title('10-armed bandit, averaged over 300 random problems')
plt.tight_layout(); plt.show()
Greedy stops improving early; ε-greedy keeps exploring 10% of the time forever; UCB explores where it is unsure and wins in the long run. The same dilemma appears in every RL problem, and in A/B testing, clinical trials and recommendation.
14.6 Monte Carlo Methods¶
Without a model, the agent can still estimate values from experience. Monte Carlo (MC) methods play complete episodes and average the returns that actually followed each state (or state–action pair):
MC needs no model and its estimates are unbiased, but it must wait until the end of an episode, and returns vary a lot from one episode to the next (high variance). It only works for tasks that end.
14.7 Temporal-Difference Learning¶
Temporal-difference (TD) learning updates after every step, using its own current estimate of the next state in place of the rest of the return (bootstrapping):
The bracket is the TD error : how much better or worse things went than expected. (The same signal has been observed in the dopamine neurons of the brain.)
| DP | Monte Carlo | TD | |
|---|---|---|---|
| Needs a model | yes | no | no |
| Learns during an episode | — | no (waits for the end) | yes (every step) |
| Bootstraps | yes | no | yes |
| Bias / variance | — | unbiased, high variance | some bias, low variance |
Q-learning¶
To control (find a good policy) without a model, we learn action values. Q-learning (Watkins, 1989) updates after every step :
while acting ε-greedily on . Its target uses the best next action, whatever the agent actually does next: it learns the optimal policy while behaving exploratorily. It is off-policy.
Worked update. , the agent receives , and in the best action value is 2. With and :
SARSA¶
SARSA uses the action the agent actually takes next (the name lists the quintuple ):
It learns the value of the policy it follows, exploration included: it is on-policy.
The cliff¶
In the classic cliff-walking task the agent crosses a grid along the edge of a cliff: -1 per step, -100 and back to the start for a fall. With ε-greedy exploration:
Source
H, Wd = 4, 12
START, GOAL_C = (3, 0), (3, 11)
ACTS = [(-1, 0), (0, 1), (1, 0), (0, -1)]
def cliff_step(s, a):
r, c = min(max(s[0] + ACTS[a][0], 0), H - 1), min(max(s[1] + ACTS[a][1], 0), Wd - 1)
if r == 3 and 0 < c < 11: return START, -100, False
return (r, c), -1, (r, c) == GOAL_C
def learn(method, episodes=500, alpha=0.5, eps=0.1, seed=0):
rng = np.random.default_rng(seed); Q = np.zeros((H, Wd, 4)); rewards = []
pick = lambda s: rng.integers(4) if rng.random() < eps else int(np.argmax(Q[s]))
for _ in range(episodes):
s, total, done = START, 0, False; a = pick(s)
while not done:
s2, r, done = cliff_step(s, a); total += r; a2 = pick(s2)
target = r + (0 if done else (Q[s2].max() if method == 'Q-learning' else Q[s2][a2]))
Q[s][a] += alpha * (target - Q[s][a]); s, a = s2, a2
rewards.append(total)
return Q, np.array(rewards)
fig, axes = plt.subplots(1, 2, figsize=(13, 3.4), gridspec_kw={'width_ratios': [1.1, 1]})
paths = {}
for name, color in [('SARSA', 'C0'), ('Q-learning', 'C3')]:
runs = [learn(name, seed=s) for s in range(10)]
curve = np.mean([r for _, r in runs], axis=0)
axes[0].plot(np.convolve(curve, np.ones(10) / 10, mode='valid'), color=color, label=name)
Q = runs[0][0]; s, path = START, [START]
for _ in range(40):
s, _, done = cliff_step(s, int(np.argmax(Q[s]))); path.append(s)
if done: break
paths[name] = (path, color)
axes[0].set_ylim(-100, 0); axes[0].set_xlabel('episode'); axes[0].set_ylabel('reward per episode'); axes[0].legend(); axes[0].set_title('Reward while learning (ε = 0.1)')
axes[1].add_patch(plt.Rectangle((0.5, 2.5), 10, 1, color='lightcoral')); axes[1].text(5.5, 3, 'THE CLIFF', ha='center', va='center')
for name, (path, color) in paths.items():
axes[1].plot([p[1] for p in path], [p[0] + (0.08 if name == 'SARSA' else -0.08) for p in path], 'o-', color=color, label=f'{name} greedy path', ms=4)
axes[1].text(0, 3, 'S', ha='center', va='center', fontweight='bold'); axes[1].text(11, 3, 'G', ha='center', va='center', fontweight='bold')
axes[1].set_xlim(-0.5, 11.5); axes[1].set_ylim(3.5, -0.5); axes[1].set_xticks([]); axes[1].set_yticks([]); axes[1].legend(loc='upper center', ncol=2, fontsize=8)
axes[1].set_title('The learnt routes'); plt.tight_layout(); plt.show()
Q-learning learns the optimal route, right along the edge, but while it keeps exploring it sometimes steps off, so it collects less reward during learning. SARSA accounts for its own exploration and learns a safer route away from the edge. Which is “better” depends on whether mistakes during learning matter, as they do for a real robot.
14.8 Deep Reinforcement Learning¶
Tables of cannot cover large or continuous state spaces: an Atari screen has more possible states than atoms in the universe. Function approximation replaces the table by a model , usually a neural network that takes the state and outputs one value per action.
Naively plugging a network into Q-learning is unstable: consecutive experiences are strongly correlated, and the target moves every time the weights change. The Deep Q-Network (DQN; Mnih et al., 2015) added two fixes:
Experience replay: store transitions in a buffer and train on random mini-batches from it, which breaks the correlations and reuses each experience many times.
A target network: compute targets with a copy of the network that is updated only every few thousand steps.
The loss is . With the raw screen pixels as input and a CNN (Chapter 18), one DQN with the same settings learnt dozens of Atari games, matching or beating a professional human tester on many of them. Improvements followed: Double DQN, prioritised replay, duelling networks.
14.9 Policy Gradient Methods¶
Instead of learning values and acting greedily, we can learn the policy itself: a network that outputs action probabilities, trained to maximise the expected return . This handles continuous actions (a robot’s joint torques) and stochastic policies naturally.
The policy gradient theorem gives the gradient in a form we can estimate from episodes. The REINFORCE algorithm (Williams, 1992) uses
“Make the actions that were followed by high returns more likely.” Subtracting a baseline (for example the average return) from leaves the gradient unbiased and greatly reduces its variance.
Actor–critic methods learn both: an actor (the policy) and a critic (a value function) whose TD error replaces . Modern variants, such as PPO (Proximal Policy Optimisation, 2017), also limit how much the policy may change in one update, which makes training stable. PPO is the algorithm behind much of robotics RL and the RLHF of chatbots.
| Family | Learns | Examples | Strengths |
|---|---|---|---|
| Value-based | Q-learning, DQN | sample-efficient (replay); discrete actions | |
| Policy-based | REINFORCE | continuous actions; stochastic policies | |
| Actor–critic | both | A2C, PPO, SAC | the usual choice today |
14.10 Landmarks and Practice¶
| Year | System | What it did |
|---|---|---|
| 1992 | TD-Gammon (Tesauro) | a neural network trained by TD learning through self-play reached the level of the best backgammon players |
| 2015 | DQN (DeepMind) | learnt Atari games from pixels and the score alone |
| 2016 | AlphaGo | beat Lee Sedol, one of the world’s best Go players, 4–1: deep networks, self-play and tree search (the MCTS of Chapter 4) |
| 2017 | AlphaZero | mastered Go, chess and shogi from the rules alone, by self-play |
| 2022 | RLHF (InstructGPT, ChatGPT) | language models fine-tuned with PPO against a reward model learnt from human preferences between answers |
RL from human feedback (RLHF). People compare pairs of answers; a network learns to predict their preferences (the reward model); the language model is then trained by RL to produce answers the reward model scores highly, without drifting too far from its original behaviour. This is how a model that predicts text becomes an assistant that follows instructions (Chapter 21).
Why RL is hard in practice:
Sample inefficiency: millions of episodes, easy in a simulator, impossible on a real robot (so: simulators, then transfer to reality).
Reward design: agents optimise exactly what is rewarded. A boat-racing agent famously learnt to circle forever collecting bonus targets instead of finishing the race: reward hacking.
Safety during learning: exploration can be dangerous (the cliff).
Instability and sensitivity to hyperparameters and random seeds.
14.11 Summary¶
RL learns from rewards through interaction; the problem is modelled as an MDP , and the agent maximises the discounted return.
Value functions , obey the Bellman equations; .
With a model, dynamic programming (policy and value iteration) solves them exactly.
Agents must balance exploration and exploitation (ε-greedy, UCB).
Without a model: Monte Carlo (full returns) and TD (bootstrapped, every step); Q-learning (off-policy, ) and SARSA (on-policy).
DQN (replay, target network) and policy gradients (REINFORCE, actor–critic, PPO) scale RL with neural networks; RLHF aligns language models.
Exercises¶
With , compute the return of the reward sequence .
Repeat the corridor value iteration with . What are the final values? Does the policy change?
Write the Bellman expectation equation for the corridor’s state under the policy “go right with probability 0.5, left with probability 0.5”.
A Q-learning agent has , receives and lands in where . With and , compute the new . What would SARSA compute if the agent’s next action were the first one?
Why does Q-learning take the dangerous path in the cliff task, and why does SARSA not?
Explain why DQN needs experience replay and a target network.
Design a reward for a cleaning robot. How might your agent “hack” it?
Further Reading¶
R. S. Sutton, A. G. Barto, Reinforcement Learning: An Introduction, 2nd ed., MIT Press, 2018 (free online): the standard textbook.
D. Silver, UCL Course on Reinforcement Learning, lecture videos and slides, 2015.
V. Mnih et al., “Human-level control through deep reinforcement learning”, Nature 518, 2015.
D. Silver et al., “Mastering the game of Go with deep neural networks and tree search”, Nature 529, 2016.
L. Ouyang et al., “Training language models to follow instructions with human feedback”, 2022.
C. C. Aggarwal, Artificial Intelligence: A Textbook, Springer, 2021, Chapter 10.