Chapter 14 — Lab: Reinforcement Learning
Lab Overview¶
| Exercise | Topic | Points |
|---|---|---|
| 1 | Discounted returns | 10 |
| 2 | Value iteration on a model | 20 |
| 3 | ε-greedy action selection | 10 |
| 4 | The Q-learning and SARSA updates | 20 |
| 5 | Learning to cross the cliff | 20 |
| 6 | The REINFORCE loss | 20 |
| Challenge | UCB for a bandit | +10 |
Complete the code where you see # TODO, then run the check cell under it.
import numpy as np
import torch
def check(name, test):
try:
ok = test()
except NotImplementedError:
print(f'❌ {name}: not implemented yet'); return
except Exception as e:
print(f'❌ {name}: {type(e).__name__}: {e}'); return
print(f'✅ {name}' if ok else f'❌ {name}: wrong result')
print('Setup complete.')Exercise 1: Discounted Returns (10 points)¶
Complete returns_to_go(rewards, gamma): for a list of rewards of one episode, return the array of returns from every time step. Work backwards: .
def returns_to_go(rewards, gamma):
raise NotImplementedError # TODOcheck('the chapter example: 0, 0, 1 with γ = 0.9 gives G_0 = 0.81', lambda: np.isclose(returns_to_go([0, 0, 1], 0.9)[0], 0.81))
check('exercise 1 of the chapter: 1, 0, 2, 4 with γ = 0.5', lambda: np.allclose(returns_to_go([1, 0, 2, 4], 0.5), [2.0, 2.0, 4.0, 4.0]))Exercise 2: Value Iteration (20 points)¶
A model is given as a dictionary P[s][a]: a list of (probability, next_state, reward, done) tuples (the format used by the Gymnasium library). Complete value_iteration(P, gamma, theta): repeat
(with when done) over all states until the largest change is below theta; then return V and the greedy policy (a dict state → action).
def value_iteration(P, gamma=0.9, theta=1e-8):
raise NotImplementedError # TODOdef corridor(step_reward=-1.0, goal_reward=10.0):
"""S1, S2, S3 and a terminal goal G (with no actions); moving left from S1 stays in S1."""
P = {'S1': {}, 'S2': {}, 'S3': {}, 'G': {}}
order = ['S1', 'S2', 'S3', 'G']
for i, s in enumerate(order[:3]):
left, right = order[max(i - 1, 0)], order[i + 1]
P[s]['left'] = [(1.0, left, step_reward, False)]
P[s]['right'] = [(1.0, right, goal_reward if right == 'G' else step_reward, right == 'G')]
return P
check('the chapter corridor: V = 6.2, 8, 10', lambda: np.allclose([value_iteration(corridor())[0][s] for s in ['S1', 'S2', 'S3']], [6.2, 8, 10]))
check('the policy is "right" everywhere', lambda: set(value_iteration(corridor())[1].values()) == {'right'})
check('with γ = 0.5 (chapter exercise 2)', lambda: np.allclose([value_iteration(corridor(), gamma=0.5)[0][s] for s in ['S1', 'S2', 'S3']], [1, 4, 10]))Exercise 3: ε-Greedy (10 points)¶
Complete epsilon_greedy(q_values, eps, rng): with probability eps return a uniformly random action index, otherwise the index of the largest value (use rng.random() and rng.integers).
def epsilon_greedy(q_values, eps, rng):
raise NotImplementedError # TODOdef _eps_ok():
rng = np.random.default_rng(0)
picks = np.array([epsilon_greedy([0.1, 0.9, 0.3, 0.2], 0.2, rng) for _ in range(20000)])
freq = np.bincount(picks, minlength=4) / len(picks)
return abs(freq[1] - 0.85) < 0.01 and np.all(np.abs(freq[[0, 2, 3]] - 0.05) < 0.01)
check('the best action 85% of the time, each other one 5% (ε = 0.2, 4 actions)', _eps_ok)
check('ε = 0 is greedy', lambda: epsilon_greedy([3, 1, 7], 0.0, np.random.default_rng(0)) == 2)Exercise 4: The Q-Learning and SARSA Updates (20 points)¶
Q is a NumPy array indexed Q[state, action]. Complete both updates, in place, and return the new value. When done is true, the target is just r.
Q-learning: target
SARSA: target for the action actually chosen next
def q_learning_update(Q, s, a, r, s2, done, alpha, gamma):
raise NotImplementedError # TODO
def sarsa_update(Q, s, a, r, s2, a2, done, alpha, gamma):
raise NotImplementedError # TODOdef _table():
Q = np.zeros((2, 3)); Q[0, 0] = 0.5; Q[1] = [1.0, 2.0, 0.0]
return Q
check('the chapter example: 0.5 becomes 0.53', lambda: np.isclose(q_learning_update(_table(), 0, 0, -1.0, 1, False, 0.1, 0.9), 0.53))
check('SARSA with the next action 0', lambda: np.isclose(sarsa_update(_table(), 0, 0, -1.0, 1, 0, False, 0.1, 0.9), 0.5 + 0.1 * (-1 + 0.9 - 0.5)))
check('terminal transitions ignore the next state', lambda: np.isclose(q_learning_update(_table(), 0, 0, 5.0, 1, True, 0.5, 0.9), 2.75))
def _inplace():
Q = _table(); q_learning_update(Q, 0, 0, -1.0, 1, False, 0.1, 0.9)
return np.isclose(Q[0, 0], 0.53)
check('the table is updated in place', _inplace)Exercise 5: Crossing the Cliff (20 points)¶
The cliff of the chapter: a 4×12 grid, start bottom-left, goal bottom-right, the cells between them are the cliff (−100 and back to start), −1 per step. Complete train(method, episodes, alpha, eps, seed) (γ = 1) using your functions from Exercises 3 and 4. For SARSA, choose the next action before the update and then take it. Return the Q table.
ROWS, COLS = 4, 12
START, GOAL = 3 * COLS + 0, 3 * COLS + 11
ACTIONS = [(-1, 0), (0, 1), (1, 0), (0, -1)] # up, right, down, left
def cliff_step(s, a):
r, c = divmod(s, COLS)
r, c = min(max(r + ACTIONS[a][0], 0), ROWS - 1), min(max(c + ACTIONS[a][1], 0), COLS - 1)
if r == 3 and 0 < c < 11:
return START, -100.0, False
s2 = r * COLS + c
return s2, -1.0, s2 == GOAL
def greedy_path(Q, max_steps=50):
s, path = START, [START]
for _ in range(max_steps):
s, _, done = cliff_step(s, int(np.argmax(Q[s])))
path.append(s)
if done:
return path
return path
def train(method, episodes=500, alpha=0.1, eps=0.1, seed=0):
rng = np.random.default_rng(seed)
Q = np.zeros((ROWS * COLS, 4))
raise NotImplementedError # TODO: episodes of epsilon-greedy steps with the right update (gamma = 1)
return Qdef _cliff_ok():
q_path, s_path = greedy_path(train('q-learning')), greedy_path(train('sarsa'))
edge = lambda path: sum(divmod(s, COLS)[0] == 2 for s in path) # cells in the row next to the cliff
print(f' Q-learning path: {len(q_path) - 1} steps, {edge(q_path)} beside the cliff; SARSA path: {len(s_path) - 1} steps, {edge(s_path)} beside the cliff')
safe = edge(s_path) < edge(q_path)
return q_path[-1] == GOAL and len(q_path) - 1 == 13 and s_path[-1] == GOAL and len(s_path) - 1 > 13 and safe
check('Q-learning finds the 13-step edge path; SARSA a longer, safer one', _cliff_ok)Question. In one or two sentences: why does each method choose its path, and which would you use to train a real robot?
Your answer:
Exercise 6: The REINFORCE Loss (20 points)¶
Complete reinforce_loss(log_probs, rewards, gamma): compute the returns-to-go of the episode (Exercise 1), normalise them (subtract their mean, divide by their standard deviation plus 1e-8), and return as a PyTorch scalar. log_probs is a 1-D tensor that requires gradients; the minus sign turns gradient descent on the loss into ascent on the return.
def reinforce_loss(log_probs, rewards, gamma=0.99):
raise NotImplementedError # TODOdef _loss_ok():
lp = torch.tensor([-0.5, -1.0, -0.2], requires_grad=True)
loss = reinforce_loss(lp, [1.0, 1.0, 1.0], gamma=1.0)
G = np.array([3.0, 2.0, 1.0]); Gn = (G - G.mean()) / (G.std() + 1e-8)
loss.backward()
return np.isclose(loss.item(), -(np.array([-0.5, -1.0, -0.2]) * Gn).sum(), atol=1e-6) and np.allclose(lp.grad.numpy(), -Gn, atol=1e-6)
check('value and gradient on a 3-step episode', _loss_ok)Question. After normalisation, the early steps of a long episode get a positive weight and the last steps a negative one. What does that mean for the actions taken just before the pole fell?
Your answer:
Challenge: UCB (+10 points)¶
Complete ucb_action(Q, N, t, c): if some action has never been tried (N[a] == 0), return the first such action; otherwise return . Then run it on 300 random 10-armed bandits of 1000 pulls (code given) and compare its average reward with ε-greedy.
def ucb_action(Q, N, t, c=2.0):
raise NotImplementedError # TODOdef bandit_average(choose, runs=300, k=10, T=1000, seed=0):
rng = np.random.default_rng(seed)
total = 0.0
for _ in range(runs):
means, Q, N = rng.normal(0, 1, k), np.zeros(k), np.zeros(k)
for t in range(1, T + 1):
a = choose(Q, N, t, rng)
r = rng.normal(means[a], 1.0)
N[a] += 1; Q[a] += (r - Q[a]) / N[a]
total += r
return total / (runs * T)
check('UCB tries every arm once first', lambda: ucb_action(np.array([5.0, 0, 0]), np.array([3, 0, 0]), 4) == 1)
check('then the optimistic estimate decides', lambda: ucb_action(np.array([1.0, 0.9]), np.array([100, 1]), 101) == 1)
def _ucb_better():
ucb = bandit_average(lambda Q, N, t, rng: ucb_action(Q, N, t))
eg = bandit_average(lambda Q, N, t, rng: epsilon_greedy(Q, 0.1, rng))
print(f' average reward per pull: UCB {ucb:.3f}, ε-greedy {eg:.3f}')
return ucb > eg
check('UCB earns more than ε-greedy', _ucb_better)Lab Report¶
Submit this notebook with every check cell showing ✅ and your answers to the two questions.