Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 14: Reinforcement Learning

Open in Colab

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 tt the agent observes the state sts_t, chooses an action ata_t, and the environment answers with a reward rt+1r_{t+1} and a new state st+1s_{t+1}. The agent’s goal is to collect as much reward as possible over time, not just now.

Supervised learningReinforcement learning
Feedbackthe correct answera reward: how good, not what would have been best
Timingimmediateoften delayed (a chess game is won or lost at the end)
Dataa fixed datasetproduced by the agent’s own actions
Main difficultygeneralisationcredit 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 (S,A,P,R,γ)(S, A, P, R, \gamma) with

  • SS: the states; AA: the actions;

  • P(s′∣s,a)P(s' \mid s, a): the transition probabilities (the environment may be random: a robot’s wheel slips);

  • R(s,a,s′)R(s, a, s'): the reward;

  • γ∈[0,1)\gamma \in [0, 1): 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 π\pi is the agent’s behaviour: a rule a=π(s)a = \pi(s), or probabilities π(a∣s)\pi(a \mid s).

The return

The agent maximises the return, the discounted sum of future rewards:

Gt=rt+1+γrt+2+γ2rt+3+⋯=∑k=0∞γkrt+k+1G_t = r_{t+1} + \gamma r_{t+2} + \gamma^2 r_{t+3} + \dots = \sum_{k=0}^{\infty} \gamma^k r_{t+k+1}

Discounting keeps the sum finite and prefers sooner rewards; γ\gamma close to 1 makes the agent far-sighted, close to 0 short-sighted.

Example. Rewards 0,0,10, 0, 1 (a goal reached after three steps) with γ=0.9\gamma = 0.9: G=0+0.9⋅0+0.81⋅1=0.81G = 0 + 0.9 \cdot 0 + 0.81 \cdot 1 = 0.81. 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 ss and following π\pi:

Vπ(s)=Eπ[Gt∣st=s]V^\pi(s) = \mathbb{E}_\pi\left[G_t \mid s_t = s\right]

The action-value function fixes the first action:

Qπ(s,a)=Eπ[Gt∣st=s,at=a]Q^\pi(s, a) = \mathbb{E}_\pi\left[G_t \mid s_t = s, a_t = a\right]

Because Gt=rt+1+γGt+1G_t = r_{t+1} + \gamma G_{t+1}, values satisfy a recursive equation, the Bellman expectation equation:

Vπ(s)=∑aπ(a∣s)∑s′P(s′∣s,a)[R(s,a,s′)+γVπ(s′)]V^\pi(s) = \sum_a \pi(a \mid s) \sum_{s'} P(s' \mid s, a)\big[R(s, a, s') + \gamma V^\pi(s')\big]

“The value of a state is the reward I expect now, plus the discounted value of where I expect to land.”

The optimal values V∗V^* and Q∗Q^* are the best achievable by any policy. They satisfy the Bellman optimality equations:

V∗(s)=max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γV∗(s′)],Q∗(s,a)=∑s′P(s′∣s,a)[R(s,a,s′)+γmax⁡a′Q∗(s′,a′)]V^*(s) = \max_a \sum_{s'} P(s' \mid s, a)\big[R(s, a, s') + \gamma V^*(s')\big], \qquad Q^*(s, a) = \sum_{s'} P(s' \mid s, a)\big[R(s, a, s') + \gamma \max_{a'} Q^*(s', a')\big]

Once we know Q∗Q^*, acting optimally is easy: π∗(s)=arg⁡max⁡aQ∗(s,a)\pi^*(s) = \arg\max_a Q^*(s, a). Almost every RL algorithm is a way of solving these equations, exactly or approximately.

14.4 Dynamic Programming

When the model (PP and RR) is known, the Bellman equations can be solved directly.

Policy evaluation computes VπV^\pi by turning the Bellman equation into an update and repeating it until the values stop changing.

Policy iteration alternates:

  1. evaluate the current policy (VπV^\pi);

  2. improve it greedily: π(s)←arg⁡max⁡a∑s′P(s′∣s,a)[R+γVπ(s′)]\pi(s) \leftarrow \arg\max_a \sum_{s'} P(s' \mid s, a)[R + \gamma V^\pi(s')];

until the policy no longer changes. It converges in few iterations.

Value iteration merges the two: it repeats the optimality update

V(s)←max⁡a∑s′P(s′∣s,a)[R(s,a,s′)+γV(s′)]V(s) \leftarrow \max_a \sum_{s'} P(s' \mid s, a)\big[R(s, a, s') + \gamma V(s')\big]

for every state, until convergence, then reads the greedy policy off VV.

Worked example: a corridor

States S1,S2,S3S_1, S_2, S_3 and a terminal goal GG in a row. Actions: left or right (moving left from S1S_1 hits a wall and stays). Each move costs -1, except entering GG, which gives +10. γ=0.9\gamma = 0.9, and we start from V=0V = 0.

SweepV(S1)V(S_1)V(S2)V(S_2)V(S3)V(S_3)
0000
1−1+0.9⋅0=−1-1 + 0.9 \cdot 0 = -1−1+0.9⋅0=−1-1 + 0.9 \cdot 0 = -110+0=1010 + 0 = 10
2−1+0.9⋅(−1)=−1.9-1 + 0.9 \cdot (-1) = -1.9−1+0.9⋅10=8-1 + 0.9 \cdot 10 = 810
3−1+0.9⋅8=6.2-1 + 0.9 \cdot 8 = 6.2810
46.2 (no change: converged)810

(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
<Figure size 650x460 with 1 Axes>

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 (PP, RR), which we rarely have for real problems, and it sweeps every state, impossible for chess (≈1044\approx 10^{44} 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: kk slot machines with unknown average payouts, one state, and the goal of earning as much as possible in TT pulls.

The agent keeps an estimate Q(a)Q(a) 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

    at=arg⁡max⁡a[Q(a)+cln⁡tN(a)]a_t = \arg\max_a \left[Q(a) + c\sqrt{\frac{\ln t}{N(a)}}\right]

    where N(a)N(a) counts how often arm aa was pulled. Rarely tried arms get a bonus: “optimism in the face of uncertainty”.

Source
<Figure size 800x340 with 1 Axes>

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):

V(s)←V(s)+α[Gt−V(s)]V(s) \leftarrow V(s) + \alpha\big[G_t - V(s)\big]

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):

V(st)←V(st)+α[rt+1+γV(st+1)⏟TD target−V(st)]V(s_t) \leftarrow V(s_t) + \alpha\big[\underbrace{r_{t+1} + \gamma V(s_{t+1})}_{\text{TD target}} - V(s_t)\big]

The bracket is the TD error δt\delta_t: how much better or worse things went than expected. (The same signal has been observed in the dopamine neurons of the brain.)

DPMonte CarloTD
Needs a modelyesnono
Learns during an episode—no (waits for the end)yes (every step)
Bootstrapsyesnoyes
Bias / variance—unbiased, high variancesome 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 (s,a,r,s′)(s, a, r, s'):

Q(s,a)←Q(s,a)+α[r+γmax⁡a′Q(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha\Big[r + \gamma \max_{a'} Q(s', a') - Q(s, a)\Big]

while acting ε-greedily on QQ. 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. Q(s,a)=0.5Q(s, a) = 0.5, the agent receives r=−1r = -1, and in s′s' the best action value is 2. With α=0.1\alpha = 0.1 and γ=0.9\gamma = 0.9:

target=−1+0.9×2=0.8,Q(s,a)←0.5+0.1×(0.8−0.5)=0.53\text{target} = -1 + 0.9 \times 2 = 0.8, \qquad Q(s, a) \leftarrow 0.5 + 0.1 \times (0.8 - 0.5) = 0.53

SARSA

SARSA uses the action a′a' the agent actually takes next (the name lists the quintuple s,a,r,s′,a′s, a, r, s', a'):

Q(s,a)←Q(s,a)+α[r+γQ(s′,a′)−Q(s,a)]Q(s, a) \leftarrow Q(s, a) + \alpha\big[r + \gamma Q(s', a') - Q(s, a)\big]

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
<Figure size 1300x340 with 2 Axes>

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 Q(s,a)Q(s, a) 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 Q(s,a;θ)Q(s, a; \boldsymbol{\theta}), 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:

  1. Experience replay: store transitions (s,a,r,s′)(s, a, r, s') in a buffer and train on random mini-batches from it, which breaks the correlations and reuses each experience many times.

  2. A target network: compute targets r+γmax⁡a′Q(s′,a′;θ−)r + \gamma \max_{a'} Q(s', a'; \boldsymbol{\theta}^-) with a copy of the network that is updated only every few thousand steps.

The loss is (r+γmax⁡a′Q(s′,a′;θ−)−Q(s,a;θ))2\big(r + \gamma \max_{a'} Q(s', a'; \boldsymbol{\theta}^-) - Q(s, a; \boldsymbol{\theta})\big)^2. 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 πθ(a∣s)\pi_{\boldsymbol\theta}(a \mid s) that outputs action probabilities, trained to maximise the expected return J(θ)J(\boldsymbol\theta). 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

∇θJ≈∑tGt ∇θlog⁡πθ(at∣st)\nabla_{\boldsymbol\theta} J \approx \sum_t G_t\, \nabla_{\boldsymbol\theta} \log \pi_{\boldsymbol\theta}(a_t \mid s_t)

“Make the actions that were followed by high returns more likely.” Subtracting a baseline b(s)b(s) (for example the average return) from GtG_t 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 Gt−bG_t - b. 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.

FamilyLearnsExamplesStrengths
Value-basedQ(s,a)Q(s, a)Q-learning, DQNsample-efficient (replay); discrete actions
Policy-basedπ(a∣s)\pi(a \mid s)REINFORCEcontinuous actions; stochastic policies
Actor–criticbothA2C, PPO, SACthe usual choice today

14.10 Landmarks and Practice

YearSystemWhat it did
1992TD-Gammon (Tesauro)a neural network trained by TD learning through self-play reached the level of the best backgammon players
2015DQN (DeepMind)learnt Atari games from pixels and the score alone
2016AlphaGobeat Lee Sedol, one of the world’s best Go players, 4–1: deep networks, self-play and tree search (the MCTS of Chapter 4)
2017AlphaZeromastered Go, chess and shogi from the rules alone, by self-play
2022RLHF (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 (S,A,P,R,γ)(S, A, P, R, \gamma), and the agent maximises the discounted return.

  • Value functions VπV^\pi, QπQ^\pi obey the Bellman equations; π∗(s)=arg⁡max⁡aQ∗(s,a)\pi^*(s) = \arg\max_a Q^*(s, a).

  • 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, max⁡\max) 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

  1. With γ=0.5\gamma = 0.5, compute the return of the reward sequence 1,0,2,41, 0, 2, 4.

  2. Repeat the corridor value iteration with γ=0.5\gamma = 0.5. What are the final values? Does the policy change?

  3. Write the Bellman expectation equation for the corridor’s state S2S_2 under the policy “go right with probability 0.5, left with probability 0.5”.

  4. A Q-learning agent has Q(s,a)=2Q(s, a) = 2, receives r=1r = 1 and lands in s′s' where Q(s′,⋅)=(0,3,1)Q(s', \cdot) = (0, 3, 1). With α=0.5\alpha = 0.5 and γ=0.9\gamma = 0.9, compute the new Q(s,a)Q(s, a). What would SARSA compute if the agent’s next action were the first one?

  5. Why does Q-learning take the dangerous path in the cliff task, and why does SARSA not?

  6. Explain why DQN needs experience replay and a target network.

  7. 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.