Chapter 14: Reinforcement Learning — Implementation
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):
A grid world as an MDP; policy iteration and value iteration
Q-learning from experience only, compared with the exact solution
CartPole, the classic balancing task
A Deep Q-Network with experience replay and a target network
REINFORCE, a policy-gradient method
import copy, random, time
import numpy as np
import matplotlib.pyplot as plt
import torch
from torch import nn
import torch.nn.functional as F
np.set_printoptions(precision=2, suppress=True)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 , .
class GridWorld:
MOVES = {'↑': (-1, 0), '→': (0, 1), '↓': (1, 0), '←': (0, -1)}
SIDES = {'↑': '←→', '↓': '←→', '←': '↑↓', '→': '↑↓'}
def __init__(self, rows=4, cols=5, goal=(0, 4), pit=(1, 4), walls=((1, 1), (2, 3)), slip=0.1):
self.rows, self.cols, self.goal, self.pit, self.walls, self.slip = rows, cols, goal, pit, set(walls), slip
self.states = [(r, c) for r in range(rows) for c in range(cols) if (r, c) not in self.walls]
self.actions = list(self.MOVES)
def terminal(self, s):
return s in (self.goal, self.pit)
def move(self, s, a):
r, c = s[0] + self.MOVES[a][0], s[1] + self.MOVES[a][1]
inside = 0 <= r < self.rows and 0 <= c < self.cols and (r, c) not in self.walls
return (r, c) if inside else s
def reward(self, s2):
return 10.0 if s2 == self.goal else (-10.0 if s2 == self.pit else -1.0)
def transitions(self, s, a):
outcomes = [(1 - 2 * self.slip, self.move(s, a))] + [(self.slip, self.move(s, side)) for side in self.SIDES[a]]
return [(p, s2, self.reward(s2), self.terminal(s2)) for p, s2 in outcomes if p > 0]
def sample(self, s, a, rng):
"""Experience: one random step from the model (what a model-free agent observes)."""
outcomes = self.transitions(s, a)
i = rng.choice(len(outcomes), p=[o[0] for o in outcomes])
return outcomes[i][1:]
world = GridWorld()
print(len(world.states), 'states; from (3,0) going ↑:', world.transitions((3, 0), '↑'))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)]
GAMMA = 0.9
def q_from_v(env, V, s, a):
return sum(p * (r + GAMMA * (0 if done else V[s2])) for p, s2, r, done in env.transitions(s, a))
def policy_evaluation(env, policy, theta=1e-8):
V = {s: 0.0 for s in env.states}
while True:
delta = 0
for s in env.states:
if env.terminal(s): continue
v = q_from_v(env, V, s, policy[s])
delta, V[s] = max(delta, abs(v - V[s])), v
if delta < theta:
return V
def policy_iteration(env):
policy = {s: '↑' for s in env.states if not env.terminal(s)}
for iteration in range(1, 100):
V = policy_evaluation(env, policy)
new_policy = {s: max(env.actions, key=lambda a: q_from_v(env, V, s, a)) for s in policy}
if new_policy == policy:
return policy, V, iteration
policy = new_policy
def value_iteration(env, theta=1e-8):
V = {s: 0.0 for s in env.states}
for sweep in range(1, 10000):
newV = {s: 0.0 if env.terminal(s) else max(q_from_v(env, V, s, a) for a in env.actions) for s in env.states}
if max(abs(newV[s] - V[s]) for s in env.states) < theta:
break
V = newV
policy = {s: max(env.actions, key=lambda a: q_from_v(env, V, s, a)) for s in env.states if not env.terminal(s)}
return policy, V, sweep
pi_pi, V_pi, n_pi = policy_iteration(world)
pi_vi, V_vi, n_vi = value_iteration(world)
print(f'policy iteration: {n_pi} improvements value iteration: {n_vi} sweeps')
print('same policy:', pi_pi == pi_vi, ' largest value difference:', max(abs(V_pi[s] - V_vi[s]) for s in world.states))
def show(env, V, policy, title, ax):
grid = np.full((env.rows, env.cols), np.nan)
for s in env.states:
if not env.terminal(s): grid[s] = V[s]
ax.imshow(grid, cmap='RdYlGn', vmin=-6, vmax=8)
for s in env.states:
text = 'GOAL' if s == env.goal else 'PIT' if s == env.pit else f'{policy[s]}\n{V[s]:.1f}'
ax.text(s[1], s[0], text, ha='center', va='center', fontsize=10)
for w in env.walls: ax.add_patch(plt.Rectangle((w[1] - .5, w[0] - .5), 1, 1, color='dimgray'))
ax.add_patch(plt.Rectangle((env.goal[1] - .5, env.goal[0] - .5), 1, 1, color='mediumseagreen', zorder=0))
ax.add_patch(plt.Rectangle((env.pit[1] - .5, env.pit[0] - .5), 1, 1, color='indianred', zorder=0))
ax.set_xticks([]); ax.set_yticks([]); ax.set_title(title)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 = GridWorld(rows=1, cols=4, goal=(0, 3), pit=(9, 9), walls=(), slip=0.0)
_, V_c, sweeps = value_iteration(corridor)
print('corridor values:', [round(V_c[(0, c)], 2) for c in range(3)], f'(after {sweeps} sweeps)')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:
def q_learning(env, episodes=5000, alpha=0.1, eps=0.2, seed=0):
rng = np.random.default_rng(seed)
Q = {(s, a): 0.0 for s in env.states for a in env.actions}
starts = [s for s in env.states if not env.terminal(s)]
for _ in range(episodes):
s = starts[rng.integers(len(starts))]
for _ in range(100):
a = env.actions[rng.integers(4)] if rng.random() < eps else max(env.actions, key=lambda b: Q[(s, b)])
s2, r, done = env.sample(s, a, rng)
target = r if done else r + GAMMA * max(Q[(s2, b)] for b in env.actions)
Q[(s, a)] += alpha * (target - Q[(s, a)])
if done: break
s = s2
return Q
Q = q_learning(world)
pi_q = {s: max(world.actions, key=lambda a: Q[(s, a)]) for s in pi_vi}
V_q = {s: max(Q[(s, a)] for a in world.actions) if not world.terminal(s) else 0.0 for s in world.states}
agree = np.mean([pi_q[s] == pi_vi[s] for s in pi_vi])
print(f'Q-learning agrees with the optimal policy in {agree:.0%} of the states')
fig, axes = plt.subplots(1, 2, figsize=(11, 3.8))
show(world, V_vi, pi_vi, 'Value iteration (knows the model)', axes[0])
show(world, V_q, pi_q, 'Q-learning (5000 episodes of experience)', axes[1])
plt.tight_layout(); plt.show()Q-learning agrees with the optimal policy in 94% of the states

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.
class CartPole:
def __init__(self, seed=0):
self.rng = np.random.default_rng(seed)
def reset(self):
self.state, self.t = self.rng.uniform(-0.05, 0.05, 4), 0
return self.state.copy()
def step(self, action):
x, x_dot, theta, theta_dot = self.state
force = 10.0 if action == 1 else -10.0
cos, sin = np.cos(theta), np.sin(theta)
temp = (force + 0.05 * theta_dot ** 2 * sin) / 1.1 # pole mass 0.1 kg, cart 1 kg, half-length 0.5 m
theta_acc = (9.8 * sin - cos * temp) / (0.5 * (4 / 3 - 0.1 * cos ** 2 / 1.1))
x_acc = temp - 0.05 * theta_acc * cos / 1.1
self.state = np.array([x + 0.02 * x_dot, x_dot + 0.02 * x_acc, theta + 0.02 * theta_dot, theta_dot + 0.02 * theta_acc])
self.t += 1
failed = abs(self.state[0]) > 2.4 or abs(self.state[2]) > 12 * np.pi / 180
return self.state.copy(), 1.0, failed or self.t >= 500, failed
env = CartPole(seed=0)
random_lengths = []
for _ in range(100):
env.reset(); done, n = False, 0
while not done:
_, _, done, _ = env.step(np.random.randint(2)); n += 1
random_lengths.append(n)
print(f'random pushes keep the pole up for {np.mean(random_lengths):.1f} steps on average')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 : 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 ( after every update).
Exploration ε decays from 0.9 to 0.05. The target uses , 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).
def train_dqn(episodes=150, seed=0, capacity=50_000, batch=128, gamma=0.99, lr=5e-4, tau=0.005):
torch.manual_seed(seed); random.seed(seed); np.random.seed(seed)
env = CartPole(seed)
q_net = nn.Sequential(nn.Linear(4, 128), nn.ReLU(), nn.Linear(128, 128), nn.ReLU(), nn.Linear(128, 2))
target_net = copy.deepcopy(q_net)
opt = torch.optim.AdamW(q_net.parameters(), lr=lr, amsgrad=True)
buffer = {k: np.zeros((capacity, 4) if k in ('s', 's2') else capacity, np.float32) for k in ('s', 'a', 'r', 's2', 'fail')}
stored, steps, lengths = 0, 0, []
best_avg, best_net = -1, None
for episode in range(episodes):
s, done, length = env.reset(), False, 0
while not done:
eps = 0.05 + 0.85 * np.exp(-steps / 2000)
if random.random() < eps:
a = random.randrange(2)
else:
with torch.no_grad():
a = int(q_net(torch.tensor(s, dtype=torch.float32)).argmax())
s2, r, done, failed = env.step(a)
i = stored % capacity
buffer['s'][i], buffer['a'][i], buffer['r'][i], buffer['s2'][i], buffer['fail'][i] = s, a, r, s2, failed
stored, steps, length, s = stored + 1, steps + 1, length + 1, s2
if stored >= batch:
idx = np.random.randint(0, min(stored, capacity), batch)
S, A, R, S2, FAIL = (torch.tensor(buffer[k][idx]) for k in ('s', 'a', 'r', 's2', 'fail'))
with torch.no_grad():
target = R + gamma * (1 - FAIL) * target_net(S2).max(1).values
q_sa = q_net(S).gather(1, A.long()[:, None]).squeeze(1)
loss = F.smooth_l1_loss(q_sa, target)
opt.zero_grad(); loss.backward(); nn.utils.clip_grad_value_(q_net.parameters(), 100); opt.step()
with torch.no_grad(): # soft update of the target network
for p_t, p in zip(target_net.parameters(), q_net.parameters()):
p_t.mul_(1 - tau).add_(tau * p)
lengths.append(length)
if np.mean(lengths[-10:]) > best_avg: # keep the best checkpoint
best_avg, best_net = np.mean(lengths[-10:]), copy.deepcopy(q_net)
return best_net, lengths
start = time.time()
dqn_net, dqn_lengths = train_dqn()
print(f'{time.time() - start:.0f} s; best episode {max(dqn_lengths)} steps; mean of the last 20: {np.mean(dqn_lengths[-20:]):.0f}')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 from every step, normalise the returns of the episode (subtracting their mean is the baseline of Section 14.9), and increase in proportion to them.
def train_reinforce(episodes=300, seed=0, gamma=0.99, lr=1e-2):
torch.manual_seed(seed)
env = CartPole(seed)
policy = nn.Sequential(nn.Linear(4, 64), nn.ReLU(), nn.Linear(64, 2))
opt = torch.optim.Adam(policy.parameters(), lr=lr)
lengths, best_avg, best_policy = [], -1, None
for episode in range(episodes):
s, done, log_probs, rewards = env.reset(), False, [], []
while not done:
dist = torch.distributions.Categorical(logits=policy(torch.tensor(s, dtype=torch.float32)))
a = dist.sample()
log_probs.append(dist.log_prob(a))
s, r, done, _ = env.step(int(a))
rewards.append(r)
returns, g = np.zeros(len(rewards)), 0.0
for t in reversed(range(len(rewards))):
g = rewards[t] + gamma * g
returns[t] = g
returns = torch.tensor((returns - returns.mean()) / (returns.std() + 1e-8), dtype=torch.float32)
loss = -(torch.stack(log_probs) * returns).sum() # gradient ascent on the expected return
opt.zero_grad(); loss.backward(); opt.step()
lengths.append(len(rewards))
if np.mean(lengths[-10:]) > best_avg: # keep the best checkpoint
best_avg, best_policy = np.mean(lengths[-10:]), copy.deepcopy(policy)
return best_policy, lengths
start = time.time()
pg_policy, pg_lengths = train_reinforce()
print(f'{time.time() - start:.0f} s; best episode {max(pg_lengths)} steps; mean of the last 20: {np.mean(pg_lengths[-20:]):.0f}')75 s; best episode 500 steps; mean of the last 20: 369
smooth = lambda x, w=10: np.convolve(x, np.ones(w) / w, mode='valid')
plt.figure(figsize=(9, 3.4))
plt.plot(smooth(dqn_lengths), label='DQN'); plt.plot(smooth(pg_lengths), label='REINFORCE')
plt.axhline(np.mean(random_lengths), ls=':', c='gray', label='random pushes'); plt.axhline(500, ls='--', c='k', lw=0.8)
plt.xlabel('episode'); plt.ylabel('steps balanced (moving average of 10)'); plt.legend(); plt.title('Learning to balance CartPole')
plt.show()
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:
def evaluate(model, episodes=10, seed=1000):
env, lengths = CartPole(seed), []
for _ in range(episodes):
s, done, n = env.reset(), False, 0
while not done:
with torch.no_grad():
s, _, done, _ = env.step(int(model(torch.tensor(s, dtype=torch.float32)).argmax()))
n += 1
lengths.append(n)
return lengths
for name, model in [('DQN', dqn_net), ('REINFORCE', pg_policy)]:
print(f'{name:10} steps balanced in 10 greedy episodes: {evaluate(model)}')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:
env = CartPole(seed=123)
s, done, angles, positions = env.reset(), False, [], []
while not done:
with torch.no_grad():
a = int(pg_policy(torch.tensor(s, dtype=torch.float32)).argmax()) # act greedily
s, _, done, _ = env.step(a)
angles.append(np.degrees(s[2])); positions.append(s[0])
fig, axes = plt.subplots(1, 2, figsize=(11, 2.8))
axes[0].plot(angles); axes[0].axhline(12, ls='--', c='r'); axes[0].axhline(-12, ls='--', c='r'); axes[0].set_title(f'Pole angle (degrees), {len(angles)} steps')
axes[1].plot(positions); axes[1].axhline(2.4, ls='--', c='r'); axes[1].axhline(-2.4, ls='--', c='r'); axes[1].set_title('Cart position (m)')
for ax in axes: ax.set_xlabel('step')
plt.tight_layout(); plt.show()
Summary¶
| Section | Result |
|---|---|
| 1 | policy iteration and value iteration find the same optimal grid-world policy; the corridor reproduces the chapter’s values |
| 2 | Q-learning, from experience only, nearly recovers the optimal policy |
| 3 | random pushes balance CartPole for about 20 steps |
| 4–5 | from the reward alone, a DQN learns to balance for about 180 steps in 150 episodes, and REINFORCE’s best checkpoint for the full 500 |