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 — Implementation

Open in Colab

This notebook builds reinforcement learning up from a table to neural networks, with every environment written in a few lines of NumPy (no extra library):

  1. A grid world as an MDP; policy iteration and value iteration

  2. Q-learning from experience only, compared with the exact solution

  3. CartPole, the classic balancing task

  4. A Deep Q-Network with experience replay and a target network

  5. REINFORCE, a policy-gradient method

1. A Grid World and Dynamic Programming

The grid of the chapter: a goal (+10), a pit (−10), two walls, −1 per move, and slippery moves (80% as intended, 10% to each side). transitions(s, a) returns the list of (probability, next state, reward, terminal): this is the model PP, RR.

18 states; from (3,0) going ↑: [(0.8, (2, 0), -1.0, False), (0.1, (3, 0), -1.0, False), (0.1, (3, 1), -1.0, False)]
policy iteration: 4 improvements   value iteration: 38 sweeps
same policy: True   largest value difference: 1.3230744055903187e-08

Policy iteration needs only a handful of improvements (each with a full evaluation inside); value iteration needs more, cheaper sweeps. Both reach the same optimal policy.

The chapter’s corridor example is a 1×4 grid without slipping:

corridor values: [6.2, 8.0, 10.0] (after 4 sweeps)

2. Q-Learning from Experience

Now the agent does not know transitions. It can only act and observe what happens (sample). Tabular Q-learning with ε-greedy exploration, starting each episode from a random state:

Q-learning agrees with the optimal policy in 94% of the states
<Figure size 1100x380 with 2 Axes>

Without ever seeing the transition probabilities, Q-learning recovers (almost) the same values and policy, just from trial and error. Where it differs, the values of the alternatives are close, or the state is rarely visited.

3. CartPole

A pole is hinged on a cart; pushing the cart left or right (force ±10 N) must keep the pole upright. The state is (cart position, cart velocity, pole angle, pole angular velocity); each step lasts 0.02 s and earns +1; the episode ends if the pole tilts more than 12° or the cart leaves the track, or after 500 steps. These are the standard equations of motion of the classic benchmark.

random pushes keep the pole up for 21.2 steps on average

4. A Deep Q-Network

The state is continuous, so no table can hold QQ: a network maps the 4 numbers to 2 action values. The two stabilisers of Section 14.8 are here:

  • a replay buffer of past transitions, sampled at random in mini-batches of 128;

  • a target network, a slowly moving copy (θ−←0.995 θ−+0.005 θ\boldsymbol\theta^- \leftarrow 0.995\,\boldsymbol\theta^- + 0.005\,\boldsymbol\theta after every update).

Exploration ε decays from 0.9 to 0.05. The target uses 1−failed1 - \text{failed}, so that reaching the 500-step limit is not treated as a failure. Deep RL training curves rise and fall, so we also keep the best checkpoint: a copy of the network from the moment the average of the last 10 episodes was highest (the RL cousin of early stopping, Chapter 15).

94 s; best episode 500 steps; mean of the last 20: 191

5. REINFORCE

The policy network outputs two action probabilities. After each episode we compute the discounted return GtG_t from every step, normalise the returns of the episode (subtracting their mean is the baseline of Section 14.9), and increase log⁡π(at∣st)\log\pi(a_t \mid s_t) in proportion to them.

75 s; best episode 500 steps; mean of the last 20: 369
<Figure size 900x340 with 1 Axes>

Both methods go from about 20 steps (random pushes) to balancing for hundreds of steps, from the reward alone. Their curves are noisy: performance can collapse after a good stretch, and the curves would differ with another random seed. Instability is a well-known feature of deep RL, which is why we keep the best checkpoint, and why serious comparisons average many seeds.

The kept checkpoints, acting greedily (no exploration) on 10 new episodes:

DQN        steps balanced in 10 greedy episodes: [177, 174, 185, 179, 177, 211, 156, 182, 198, 162]
REINFORCE  steps balanced in 10 greedy episodes: [500, 500, 500, 500, 500, 500, 500, 500, 500, 500]

With these budgets, REINFORCE’s checkpoint balances the pole for the full 500 steps every time; the DQN, after only 150 episodes, holds it for about 180 steps. DQN learns more slowly here (in our tests, twice as many episodes brought it to the 500-step limit too) but it reuses every experience through its replay buffer, which matters when experience is expensive. Neither result says that one method is better in general: on other tasks, and with other settings, the order often reverses.

Watching the REINFORCE checkpoint for one episode:

<Figure size 1100x280 with 2 Axes>

Summary

SectionResult
1policy iteration and value iteration find the same optimal grid-world policy; the corridor reproduces the chapter’s values
2Q-learning, from experience only, nearly recovers the optimal policy
3random pushes balance CartPole for about 20 steps
4–5from the reward alone, a DQN learns to balance for about 180 steps in 150 episodes, and REINFORCE’s best checkpoint for the full 500