Unit 6 · Reinforcement Learning Fundamentals · Course Outcome CO4
Nobody tells you the answer — or the question.
Unit 3 removed the labels and kept the data. This unit removes the data too. There is no training set: the agent must act to find out what happens, the consequences of a choice may not arrive for many steps, and every step spent finding out is a step not spent doing well. Learning and performing are now the same activity.
Section 6.1
Six squares, four actions
And no instructions whatsoever.
The agent starts at the top left. Somewhere there is a goal worth +1 and a pit worth −1, both ending the episode. Every other move pays nothing.
It is not told where they are, what the actions do, or that walls exist. It finds out by moving.
Section 6.2
Every square has an exact value
How good is it to be here, if you play well?
With a discount of γ = 0.9, the values are pure powers of γ: 1.00 next to the goal, 0.90 two steps away, 0.81 at the start.
Three steps to the goal, and 0.9² × 1 = 0.81. The whole of section 6.2 is about why that number is what it is.
Section 6.3
Reward travels backwards, one step per episode
How does a distant goal reach the start?
Episode 1 teaches the agent only the very last move. Episode 2 teaches the move before it. Not until episode 4 does anything at the start square change at all.
Watch the goal action climb 0.5, 0.75, 0.875 — that is 1 − 0.5ⁿ, and every figure in section 6.3 is exact.
Sections 6.3 and 6.4
Exploring is not free
And it is not always worth it.
On this grid, a purely greedy agent gets total regret 1.95 over 500 episodes and a perfect policy. At ε = 0.1 it pays 26.68 for no benefit at all.
Add one small reward near the start, though, and greedy finds the real goal 1.5% of the time while a decaying ε finds it 77%. Both facts are measured, and both are in section 6.3.
The colour contract, one last time
Teal and rose keep the meanings they have had since Unit 2 — the good outcome and the bad one. Amber is still what the model learns, which here means the Q-values and the policy read off them. Violet, which meant the backward pass in Unit 4, now means exploration: an action taken because the agent chose to find out rather than because it thought the action was best. Those two are the only kinds of move an agent makes, and telling them apart is most of section 6.3.
What you need before this chapter
Less than you might expect. From Unit 1: expected values, and the idea of an update that moves a current estimate a fraction of the way toward a target — section 6.3's rule has exactly the shape of gradient descent's. From Unit 2B: the discipline of asking what a reported number is entitled to claim, which matters more here than anywhere else in the course. From Unit 3: the experience of a problem with no labels, and the habit of checking whether a method found real structure or merely produced output.
None of Units 4 or 5 is required. Everything in this unit is a small table of numbers updated by one formula, and it can be done entirely by hand. Neural networks reappear only in the closing note, as the thing that replaces the table when the table becomes too large.
The spine: six squares
One environment for the whole unit, small enough that every value in it can be computed exactly and checked by hand.
Three things about this design are deliberate and each earns its place later.
The pit sits directly right of the square right of the start. So the tempting short path along the top row walks straight into it, and the agent must learn a hazard by experiencing it — there is no way to be told.
The shortest safe path is three steps, and there are exactly two of them: down-then-right-then-right, or right-then-down-then-right. That produces a genuine tie at the start square, which section 6.3 uses to show why tie-breaking is not a detail.
Every optimal value is a whole power of γ. Because the only reward is +1 at the end, the value of a square is exactly γ raised to the number of steps remaining, so the entire value function is 0.9², 0.9¹, 0.9⁰ and nothing else.
What makes this different from every other unit
In Units 2 to 5 the data existed before the model did. You could look at it, split it, and compute a metric on a part you held back. Here the data is produced by the agent's own behaviour, so a bad policy generates bad data, which teaches a bad policy. There is no held-out set, because the agent cannot observe what would have happened had it acted differently.
Three consequences run through the whole unit. Feedback is evaluative rather than instructive: a reward of 0 says "that was worth nothing", not "you should have gone left". Consequences are delayed, so which of the last twenty actions earned the reward is a real question — the credit-assignment problem. And exploring costs real reward, which no supervised learner ever had to pay.
Agent, Environment and Reward
A loop with four nouns in it, and one design decision — the reward function — that determines everything the agent will ever do.
The question
A supervised model is shown inputs paired with correct answers. What do you do when nobody knows the correct answer, but you can tell afterwards whether things went well?
Chess has no correct move, only moves that tend to win. A robot learning to walk has no labelled joint angles. A recommendation system finds out whether a suggestion was good only after making it. In all three the feedback is a score rather than a target, and it arrives late.
The intuition
Training a dog. You cannot explain the trick. You can only let it try things and give it a biscuit when something in the right direction happens. Two features of that situation define the whole field: the feedback evaluates rather than instructs, and the biscuit may arrive several actions after the one that earned it.
The formal treatment
That last line is the entire difficulty. Maximising the next reward is easy and usually wrong: on the spine grid every immediate reward is 0 for the first two moves of the optimal path, so an agent that maximised immediate reward would have no reason to move at all.
The discount factor
Two reasons γ < 1 is standard. It keeps the return finite when an episode might never end, which is a mathematical necessity rather than a preference. And it encodes genuine impatience: a reward now is usually worth more than the same reward later. The horizon it implies is roughly 1/(1−γ) steps, so γ = 0.9 is a ten-step outlook and γ = 0.99 a hundred-step one.
Depth — the reward function is the specification, and it is where things go wrong
The reward function is not a hint or a hyperparameter. It is the complete statement of what you want, and the agent will maximise it rather than your intention. Every gap between the two is a gap the agent is free to exploit, and a sufficiently good optimiser will find it.
The failure has a name, reward hacking, and the documented examples are instructive rather than exotic. A boat-racing agent rewarded for score rather than for finishing learned to circle a lagoon collecting the same three pickups forever, never completing the course, and scored higher than any human. A cleaning robot rewarded for "no visible mess" can satisfy that by covering the mess. A recommender rewarded for engagement will find that outrage is engaging.
Two practical rules follow. Reward what you want, not how you think it should be achieved. Rewarding a chess agent for capturing pieces produces an agent that captures pieces and loses; reward winning. And be careful with shaping — adding intermediate rewards to speed learning changes the objective unless it is done in a specific form (a difference of a potential function) that provably leaves the optimal policy unchanged. Section 6.3's local-optimum experiment shows a small extra reward doing exactly this kind of damage, measured.
This is 2.6's argument arriving in its sharpest form. There the model optimised a proxy and the harm was in what it predicted; here the agent optimises a proxy and the harm is in what it does.
The worked example
Worked 6.1 — returns along three different paths
the discount, appliedγ = 0.9, compute the discounted return from the start for: (a) the shortest safe path; (b) a four-step path that wastes one move; (c) the two-step path along the top row into the pit.Two wasted moves cost 0.1539 of return — the discount is what makes delay expensive, and it is the only thing that does, since no move is charged a fee.
The pit path is worth −0.9 rather than −1, because even a bad outcome is discounted by arriving one step late.
Notice what would happen at γ = 1. Path (a) and path (b) would both be worth exactly 1, so the agent would have no reason to prefer the shorter one — with no discount and no step cost, dawdling is free. The discount is doing the work that a step penalty would otherwise have to do, and it is worth knowing both options exist: a reward of −0.04 per move is the common alternative and gives a different, also reasonable, value function.
The pitfalls
Where marks are lost
- Maximising immediate reward instead of return. On the spine that policy never moves, since every first step pays 0.
- Off-by-one on the discount. A reward received on the k-th transition is discounted by
γᵏ⁻¹, notγᵏ. Three steps to the goal givesγ². - Using
γ = 1on a task that might not terminate. The return is then unbounded and the value function is undefined. - Confusing reward with return. Reward is one number from one transition; return is the discounted sum from here on. Value is the expected return.
- Rewarding the method rather than the goal. The agent optimises exactly what you wrote down.
- Adding shaping rewards casually. They change the optimal policy unless they take the potential-difference form.
Practice
P6.1.1 (direct) — An agent receives rewards 0, 0, 2, 0, −1, 5 over six steps. Compute the return from t = 0 at γ = 0.5, γ = 0.9 and γ = 1.
The three answers differ by an order of magnitude on identical rewards, and the ordering of what matters flips: at γ = 0.5 the near +2 contributes 0.5 and the distant +5 only 0.156, while at γ = 0.9 the +5 dominates at 2.95. γ is not a tuning knob for convergence speed; it changes which policy is optimal.
P6.1.2 (variation) — Rewrite the spine grid with a step penalty of −0.04 per move and γ = 1. Compute the return of the three paths from Worked 6.1 and compare the rankings.
The ranking is identical to Worked 6.1's — (a) then (b) then (c) — so this formulation also prefers the short safe path, and either design would train a correct agent. The numbers differ because they answer slightly different questions: discounting says "later is worth less", while a step penalty says "moving costs something".
The practical difference appears when episodes can fail to terminate. With γ = 1 and no step penalty, an agent that circles forever accumulates 0 and is not punished; with a step penalty it accumulates −∞ and is strongly punished. So a step penalty makes γ = 1 safe on tasks that might loop, which is exactly why the classic textbook grid world uses −0.04.
P6.1.3 (interpretation) — A warehouse robot is rewarded +1 per parcel delivered and trains to a high score, but staff report it blocks aisles and ignores parcels on high shelves. Diagnose.
The agent is doing exactly what it was paid for, and the reward function is an incomplete statement of the job. Nothing in +1 per parcel mentions aisles, so obstructing one is free; nothing distinguishes an easy parcel from a hard one, so ignoring high shelves is optimal if they take longer. Both behaviours increase the reward. This is not a training failure and more training will make it worse.
What to change. Add the missing costs explicitly — a penalty for time spent stationary in an aisle, and a time cost per delivery so that a slow parcel is worse than a fast one rather than equally good. Consider rewarding completion of an assigned manifest rather than parcels freely chosen, which removes the incentive to cherry-pick. And check whether the shelf problem is really a reward issue at all: if the robot physically cannot reach high shelves, no reward fixes it and the diagnosis is mechanical.
What not to do is add a large penalty for blocking aisles and stop. That invites the next unintended solution — refusing to enter aisles — and the pattern repeats. The reliable move is to write down what a good outcome actually is, in full, and to watch the resulting behaviour rather than only the score. Which is 4.8's reporting argument in a setting where the model's output is behaviour rather than a prediction.
P6.1.4 (synthesis) — Using 2.1 and 3.5, compare the evaluation problem here with supervised and unsupervised learning. What is available in each?
Supervised learning has an external referent. Section 2.1's protocol works because held-out labels exist independently of the model, so "is this prediction right" is a well-posed question with an answer nobody had to invent.
Unsupervised learning has none, which was section 3.5's central difficulty. "Better" had to be assembled from geometry, stability under resampling, and comparison against a null model — three weaker substitutes.
Reinforcement learning has a referent, but you designed it. Reward is an objective, measurable signal, so unlike clustering there is a definite sense in which one policy beats another. But the signal is your own specification rather than a fact about the world, so a high score means the agent satisfied your statement of the goal, which the depth box shows is a different claim from satisfying the goal.
And there is a difficulty neither of the others has: no held-out set. The agent generates its own data by acting, so it cannot observe the counterfactual and cannot be evaluated on experience it did not have. Section 6.4's answer is to report several different quantities — cumulative reward, regret, episode length, success rate — because each is gameable alone, and to average over many seeds because the variance between runs is larger here than anywhere else in the course.
Markov Decision Processes
The formal object underneath the loop, one assumption that makes it tractable, and the recursion that computes every value in the grid exactly.
The question
The loop of section 6.1 is a description, not a mathematical object. To prove anything — that an optimal policy exists, that an algorithm converges to it — you need to say precisely what an environment is.
The formal treatment
This assumption is what makes everything computable, because it means a value can be attached to a state rather than to a whole history — six numbers instead of one per possible path. It is also an assumption about your state representation rather than about the world, and it is frequently false as stated.
The spine grid satisfies it: knowing the square is enough, since how the agent arrived changes nothing about what happens next. A poker hand does not, unless the state includes the cards already seen. A single video frame does not tell you which way a ball is moving, which is why frames are usually stacked. When the Markov property fails, the standard fix is to enlarge the state until it holds, and that is a modelling decision made before any learning begins.
Value functions and the Bellman equations
The recursion is the whole idea. A long-horizon problem is decomposed into one immediate decision plus a subproblem of the same shape, which is dynamic programming applied to sequential decisions. And the theorem worth quoting is that for a finite MDP with γ < 1, an optimal deterministic policy always exists and the Bellman operator is a contraction, so value iteration converges to V* from any starting point.
The worked example
Worked 6.2 — solving the grid exactly by backward induction
every value a power of γV* for all four non-terminal squares, then Q* for the start and for the square beside the pit.| col 0 | col 1 | col 2 | |
|---|---|---|---|
| row 0 | 0.81 = 0.9² | 0.90 = 0.9¹ | PIT |
| row 1 | 0.90 = 0.9¹ | 1.00 = 0.9⁰ | GOAL |
Every value is γ raised to the number of steps remaining, which is what you should expect when the only reward is a single +1 at the end. If your arithmetic ever produces a value on this grid that is not a power of 0.9, it is wrong.
The gap between the best action and the worst is 1.9, the largest anywhere on the grid.
And note that walking into a wall is not free: it costs a factor of
γ, so Q = 0.729 against 0.81. Wasting a step is penalised by the discount alone.One observation worth carrying into section 6.3. These values were computed by knowing P and R. Backward induction needs a map of the environment — which square each action leads to, and what it pays. An agent dropped into this grid has none of that, and section 6.3 is about reaching the same numbers without it.
The pitfalls
Where marks are lost
- Giving terminal states a non-zero value.
V(terminal) = 0. The+1is earned on the transition into the goal, not by sitting in it. - Forgetting that a wall move still costs a discount. Staying put is worth
γV(s), notV(s). - Confusing
VᴵwithV*.Vᴵevaluates a given policy;V*assumes optimal play thereafter. The Bellman expectation equation has no max in it; the optimality equation does. - Claiming the Markov property is a fact about the environment. It is a property of the state representation, and enlarging the state can make it hold.
- Reading a policy off
Vwithout knowingP. You cannot — that is whyQis the more useful object and why the algorithm is called Q-learning. - Assuming a stochastic policy is ever needed here. For a finite MDP an optimal deterministic policy always exists. Randomness is for exploration, not for optimality.
Practice
P6.2.1 (direct) — Recompute V* for the whole spine grid with γ = 0.5, and say what changes about the optimal policy.
The optimal policy is exactly the same. Every value is 0.5 raised to the steps remaining rather than 0.9, so the ordering of actions in every state is unchanged and the same two shortest paths are optimal.
That is the general situation when there is a single positive terminal reward and no step cost: γ rescales the values but cannot reorder them, because a shorter path is better at every γ < 1. γ changes the policy only when there is a genuine trade between a small near reward and a large distant one — which is exactly the local-optimum grid of section 6.3, where at low γ the near +0.3 would genuinely be worth more.
P6.2.2 (variation) — Make the grid slippery: an action succeeds with probability 0.8 and otherwise moves the agent perpendicular, 0.1 each way. Compute Q(( 0,1), right), the move into the pit.
Still clearly the worst action at (0,1), but noticeably less bad than the deterministic −1.0000, because a fifth of the time the slip saves the agent from its own decision.
Two honest caveats. The true slippery values differ from the deterministic ones, so a proper solution requires re-running value iteration on the stochastic MDP rather than substituting as done here — this calculation is illustrative of the form, not exact. And slipperiness changes the optimal policy in a specific direction: it makes the agent prefer routes that stay away from the pit even at the cost of extra steps, because a slip near a hazard is expensive. That is the standard lesson of the classic slippery grid world.
P6.2.3 (interpretation) — A team models a hospital's bed-allocation problem as an MDP with state "number of free beds". Assess the Markov assumption.
It almost certainly fails, and the failures are enumerable. The number of free beds does not determine the distribution of what happens next, because several things that matter are missing from it. Time: admissions have a strong daily and weekly cycle, so five free beds at 3 a.m. on a Tuesday and five on a Friday evening lead to very different futures. Who is in the beds: ten patients due for discharge tomorrow is a different state from ten admitted this morning, and the count cannot distinguish them. Pending arrivals: an ambulance already en route is information about the next transition that the count omits.
The fix is to enlarge the state until the property holds, which is a modelling decision, not a learning one. Add time of day and day of week, a summary of expected discharges over the next day, current admissions in progress, and perhaps a coarse case-mix. Each addition makes the assumption more nearly true and makes the state space larger, which is the trade the depth of section 6.3 will describe.
And check whether the enlarged space is still tractable. Free beds (0–50) × hour (24) × day (7) × expected discharges (0–20) is already about 176,000 states, which a table can just about hold but which will need a great deal of data to fill. Beyond that, tabular methods stop being available and function approximation is required, which is where Unit 5's networks re-enter the story.
Worth adding that a violated Markov assumption does not announce itself. The algorithm will run, converge to something, and be systematically wrong in ways that look like noise — so the assumption should be argued for before training, not diagnosed after.
P6.2.4 (synthesis) — Using 1.4 and 3.1.1, identify what backward induction has in common with algorithms you have already met, and what is genuinely new.
The alternating structure is familiar. Value iteration alternates between evaluating the current estimate and improving it, exactly as k-means alternates assign and update (3.1.1) and as EM alternates E and M steps (3.1.4). All three are fixed-point iterations that improve a quantity monotonically until nothing changes, and all three converge because each step cannot make things worse.
What is genuinely different is the guarantee. k-means and EM converge to a local optimum, and section 3.1.1 measured the cost: 28 of 220 initialisations reached a worse answer, silently. Value iteration on a finite MDP with γ < 1 converges to the global optimum from any starting point, because the Bellman operator is a contraction with modulus γ — each sweep shrinks the error by a factor of at least γ. There are no local optima to be trapped in, and no restarts are needed. That is a much stronger guarantee than anything in Units 3 to 5.
What it costs is knowledge of the environment. Backward induction needs P and R in advance — a complete map. k-means needed only the data. So the strong guarantee is bought with an assumption that is usually unavailable, and section 6.3 gives it up: Q-learning reaches the same Q* using only sampled experience, and the price is that convergence becomes asymptotic and depends on visiting every state-action pair often enough.
The connection to 1.4 is the update itself. Value iteration's sweep and Q-learning's rule both move a current estimate toward a target, and section 6.3 will show that Q ← Q + α[target − Q] has precisely the shape of a gradient-descent step with α as the learning rate — the same object, in a setting where the target is itself an estimate.
Q-Learning
The Bellman equation turned into an update rule that needs no map of the environment — and a measured answer to how much exploration is worth paying for.
The question
Section 6.2 computed every value on the grid exactly, using P and R. An agent dropped into the grid has neither. It cannot compute Σₛ' P(s'|s,a)… because it does not know P. What it can do is move, and observe one (s, a, r, s') at a time.
So the question is whether a single sampled transition can stand in for the expectation.
The intuition
You have an estimate of how good an action is. You try it, and you see what happened: the immediate reward, plus your own current estimate of how good the square you landed in is. That combination is a better estimate than the one you started with, because part of it is real observation rather than guesswork.
So move your estimate a fraction of the way toward it. Not all the way — one sample is noisy — but a fraction. Repeat forever.
The formal treatment: deriving the update
Compare that with gradient descent from section 1.4. Both have the form new estimate = old estimate + step size × error, with α playing exactly the role of the learning rate: α = 1 replaces the estimate with the sample outright, and α = 0 never learns. It is the same object, in a setting where the target is itself partly an estimate — which is why the method is called bootstrapping, and why its convergence proof is harder than gradient descent's.
Three properties are worth naming because they are what make this algorithm important.
Model-free. Nowhere does P or R appear as a known quantity — only sampled r and s'. The agent never builds a map.
Off-policy. The update uses maxₐ' Q(s',a'), the value of the best next action, regardless of which action the agent will actually take next. So the agent can behave randomly and still learn the optimal policy. This is the property that lets exploration be safe, and it is what distinguishes Q-learning from SARSA, which uses the action actually taken and therefore learns the value of its own exploratory policy instead.
It converges. Given that every state-action pair is visited infinitely often and α decays suitably, Q converges to Q* with probability 1. The first condition is why exploration is not optional in general.
The worked example
Worked 6.3a — four episodes by hand, every update shown
α = 0.5, γ = 0.9, Q starts at zeroOnly the last update moved. The first two had r = 0 and landed in squares whose Q was still all zero, so the target was 0 and the error was 0. The agent has learned exactly one thing: that entering the goal from (1,1) is worth something.
Now the second update moved, because max Q at (1,1) is no longer zero. The knowledge has taken one step backwards. The start square still has not changed.
The hazard is learned the only way it can be: by falling in. There is no mechanism by which an agent could be warned, and this single negative experience is now permanently recorded against that action.
| state | up | down | left | right | Q* (right) |
|---|---|---|---|---|---|
| (0,0) | 0.0000 | 0.1013 | 0.0000 | 0.0000 | 0.8100 |
| (0,1) | 0.0000 | 0.0000 | 0.0000 | −0.5000 | −1.0000 |
| (1,0) | 0.0000 | 0.0000 | 0.0000 | 0.4500 | 0.9000 |
| (1,1) | 0.0000 | 0.0000 | 0.0000 | 0.8750 | 1.0000 |
Episode 1 reached (1,1). Episode 2 reached (1,0). Episode 4 was the first to move the start square at all.
The goal action climbs 0.5000, 0.7500, 0.8750 — which is
1 − 0.5ⁿ, approaching Q* = 1 geometrically.The backward propagation is the single most important behaviour to be able to describe, and it explains a practical fact: the number of episodes needed grows with the distance from the reward. On a six-square grid that is a nuisance; on a task where the reward comes after two hundred steps it is fatal, and it is why techniques that propagate faster — eligibility traces, n-step returns, experience replay — exist.
Note also that seven of the sixteen table entries are still exactly zero, because those actions have never been tried. Q-learning learns nothing about an action it does not take, which is the whole argument of the next subsection.
Exploration against exploitation
The agent must choose actions to learn from. If it always takes the action it currently believes is best, it may never discover a better one. If it always acts randomly, it learns a great deal and achieves nothing.
Worked 6.3b — is exploration worth paying for? Two experiments
200 seeds, 500 episodes eachε and measure the final policy and the total regret. Then add a small reward near the start and repeat.| ε | mean return | mean length | success rate | total regret |
|---|---|---|---|---|
| 0.00 | +0.8100 | 3.00 | 1.000 | 1.95 |
| 0.05 | +0.7869 | 3.15 | 0.993 | 14.85 |
| 0.10 | +0.7622 | 3.31 | 0.986 | 26.68 |
| 0.30 | +0.6502 | 3.99 | 0.946 | 85.67 |
| 1.00 | −0.0811 | 11.90 | 0.447 | — |
| 1.0→0.05 | +0.7924 | 3.13 | 0.996 | 60.34 |
Every non-zero
ε pays for exploration and receives nothing in return.That result is genuine and it needs explaining rather than apologising for. The greedy agent is still exploring — just not randomly. Q starts at zero and ties are broken at random, so on the first visit to any square all four actions look identical and the choice is uniform. Zero-initialisation is optimistic here, because the only reward worth finding is positive: an untried action looks as good as the best known one until it proves otherwise, so the agent tries everything once for free.
So on a small, deterministic environment with optimistic initial values, ε-greedy exploration is not merely unnecessary — it is a pure cost. The ε = 1 row shows the other extreme: a permanently random agent reaches the goal 44.7% of the time, takes 11.90 steps, and earns a negative mean return, because a random walk on this grid finds the pit almost as readily as the goal.
Now place a terminal reward of +0.3 at (1,0), one step below the start. The real goal is still worth far more — 0.9² × 1 = 0.81 against a flat 0.30, since that reward arrives on the very first transition and is not discounted at all — but the small one is much easier to find.
| ε | mean return | reaches the real goal |
|---|---|---|
| 0.00 | +0.3068 | 0.015 |
| 0.05 | +0.3627 | 0.134 |
| 0.10 | +0.3650 | 0.149 |
| 0.30 | +0.4112 | 0.380 |
| 1.0→0.05 | +0.6726 | 0.770 |
Optimal would be +0.8100 and 1.000, so even the best schedule leaves a real gap.
Same algorithm, same grid, one extra reward — and the ranking of every row inverts.
The mechanism is that the small reward makes greedy behaviour self-confirming. Once Q((0,0), down) has risen to 0.30 from having collected the +0.3, no other action at the start looks better, so the agent stops going right and never accumulates the experience that would reveal the +1. Its own policy denies it the data that would change its policy.
That is the honest statement of what exploration is for. It is not generally good and it is not free. It is insurance against exactly this failure, and its value depends entirely on whether the environment contains a trap of this kind — which, before you have explored it, you cannot know. Hence the decaying schedule: pay for insurance heavily at first, when ignorance is greatest, and taper it off as the estimates become trustworthy.
Depth — three things that break the table, and what replaces it
Size. A Q-table has one entry per state-action pair. Chess has roughly 10⁴⁵ positions and a camera image has more states than there are atoms in the observable universe. Beyond a few million entries a table is not merely slow, it is impossible — and worse, it cannot generalise: a table that has learned about one state knows nothing about a state one pixel different.
The replacement is function approximation. Represent Q(s,a) as a parameterised function — a neural network, per Units 4 and 5 — and train it by gradient descent on the squared temporal-difference error, [r + γ max Q(s',a'; θ⁻) − Q(s,a; θ)]². That is deep Q-learning, and it is the point at which this unit and Unit 5 join: a convolutional backbone reads the pixels and its output is the Q-table's replacement.
It also loses the convergence guarantee. Q-learning's proof relies on updating one table entry without touching the others; a network's update changes the estimate for every state, so the target moves as you chase it. The two standard repairs are a target network — a frozen copy of θ used to compute the target, updated only occasionally — and experience replay, storing transitions and sampling them in random order, which breaks the correlation between consecutive samples and, incidentally, propagates reward backwards far faster than the one-step-per-episode of Worked 6.3a.
Sample efficiency is the third limitation, and it is not solved. A tabular agent needs many visits per state; a deep agent playing an Atari game needs tens of millions of frames to reach human performance at a task a person learns in minutes. Model-based methods, which learn P and plan against it, are the main line of attack.
The visualization
Q-learning on the grid, one step at a time
interactive — watch reward crawl backwardsEach square shows its four Q-values, amber where the greedy action points, and violet marks a step taken as exploration rather than exploitation. Press Next episode repeatedly from a reset and watch the numbers appear from the goal outwards — nothing at the start square changes until the fourth episode. Then tick the trap and set ε to 0: the agent locks onto the +0.3 and stops improving.
The pitfalls
Where marks are lost
- Using
Q(s', a')for the action actually taken instead of the max. That is SARSA, a different algorithm that learns the value of the exploring policy rather than the optimal one. - Forgetting that
max Q(s',a') = 0whens'is terminal. The commonest arithmetic slip in the topic, and it inflates every value on the grid. - Updating
Q(s',a')instead ofQ(s,a). The update belongs to the action just taken. - Setting
α = 1in a stochastic environment. The estimate then equals the last sample, so it never averages and never converges. - Assuming more exploration is always better. Worked 6.3b: on the plain grid
ε = 0wins on every measure. Exploration is insurance, and insurance has a premium. - Assuming
ε = 0is therefore safe. The same experiment with one extra reward drops it to 1.5%. Neither extreme is a default. - Expecting a table to scale. One entry per state-action pair. Past a few million, function approximation is not optional.
Practice
P6.3.1 (direct) — Q(s,a) = 0.4, the agent takes a, receives r = 0, and lands in s' where the four Q-values are 0.2, 0.7, 0.1, 0.5. With α = 0.5 and γ = 0.9, compute the new Q(s,a). Then repeat with s' terminal.
The two answers differ by 0.315 on identical r, α and γ, purely because of whether the next state is terminal. Note the direction in the terminal case: because the episode ended with no reward, the estimate is revised downward — the action led nowhere and the update says so.
P6.3.2 (variation) — Show that repeatedly updating Q((1,1), right) on the spine grid gives 1 − (1−α)ⁿ after n visits, and give the value at α = 0.5 and α = 0.1 after 5 visits.
Worked 6.3a's first three values — 0.5000, 0.7500, 0.8750 — are exactly this sequence, which is a useful check on that trace. The convergence is geometric with ratio 1−α, so a larger α is strictly faster when the target is constant.
The catch is that the target is usually not constant. In a stochastic environment each visit gives a different sample, and α = 0.5 then means the estimate tracks the last few samples rather than averaging over all of them — so it converges fast to something that keeps jittering. That is why the theory requires α to decay, and why a fixed α is a practical compromise rather than a correct choice.
P6.3.3 (interpretation) — An agent's average reward rises for 2,000 episodes, plateaus well below optimal, and does not improve for another 8,000. ε is fixed at 0.3. Diagnose.
The plateau has two candidate causes and they need opposite fixes, so identify which before acting.
Cause 1: ε = 0.3 is the ceiling, not the policy. An agent that acts randomly 30% of the time cannot achieve the optimal return even with a perfect Q-table, because three moves in ten are thrown away. Worked 6.3b measured exactly this: at ε = 0.30 the mean return was 0.6502 against an optimal 0.8100, with a perfect policy underneath. Test it by evaluating greedily — run episodes with ε = 0 and no learning. If the greedy return is near optimal, nothing is wrong with the agent; the reported number was measuring the exploration premium, and the fix is to decay ε and to report greedy performance separately from training performance.
Cause 2: it is genuinely stuck. If greedy evaluation is also poor, then the plateau is real. Then look for a local optimum of the kind Experiment 2 constructed — a modest reward that is easy to reach and self-confirming. Check whether any state-action pairs remain unvisited after 10,000 episodes, which points at insufficient exploration in a specific region rather than in general. Check the learning rate: a fixed α that is too small learns too slowly to escape, too large and the estimates never settle.
And check the reward function, per 6.1's depth box, because a plateau below what you consider optimal sometimes means the agent has correctly optimised a specification that does not match your intention.
P6.3.4 (synthesis) — Using 1.4, 3.1.1 and 4.5, place the Q-learning update in the wider pattern of this course.
The form is gradient descent's. Section 1.4's update was w ← w − η∇L — move the current estimate in proportion to an error signal. Q-learning's is Q ← Q + αδ, with δ the temporal-difference error and α the learning rate. Section 4.5's stability analysis transfers directly in spirit: too large and the estimate oscillates, too small and it never arrives, and the optimisers of that section are what deep Q-learning actually uses on θ.
What is new is that the target is an estimate. Gradient descent computes an error against a fixed known label. Q-learning computes it against r + γ max Q(s',a'), which contains Q — the thing being learned. That is bootstrapping, and it is why the convergence proof is delicate, why a target network is needed once Q is a network, and why Worked 6.3a's reward propagates only one step per episode: each square can only learn once its neighbour has.
The alternating structure is 3.1.1's. Evaluate the current estimate, improve the policy implied by it, repeat — the same shape as k-means' assign-and-update and EM's E-and-M. And the exploration dilemma is 3.1.1's initialisation problem with a twist: k-means solved a poor local optimum by restarting, which a reinforcement-learning agent cannot do, because a restart does not undo the reward already forgone. Exploration is the only tool available, and unlike a restart it has to be paid for out of the same budget being optimised.
Which is the genuinely new thing in the whole unit. Every earlier method could look at data for free. Here, gathering information and performing well are in direct competition, and Worked 6.3b's two experiments show the trade going both ways depending on the environment. No amount of algorithmic cleverness removes it; it is a property of learning by acting.
Cumulative Reward, Regret and Honest Reporting
Four quantities, each gameable on its own, and the one place in the course where the metric and the objective are the same thing.
The question
Section 2.4 spent a whole unit on the gap between a model's objective and the thing you actually cared about. Reinforcement learning appears to close that gap: the agent maximises reward, and reward is what you wanted. So is evaluation trivial here?
No, for three reasons. Reward measures the agent and your reward function together, so a high score may be a fault in the specification. Performance during learning and performance after learning are different quantities and are constantly confused. And the run-to-run variance is larger than anywhere else in the course.
The four quantities
Each is inadequate alone. An agent can have high cumulative reward and terrible regret, because it learned slowly before learning well. It can have a perfect success rate and a poor return, by reaching the goal every time and taking twenty steps to do it. It can have short episodes because it dies quickly. Report all four, or say which you are optimising and why.
Worked 6.4 — the same agent under all four measures
200 seeds, 500 episodes| ε | mean return | mean length | success rate | total regret |
|---|---|---|---|---|
| 0.00 | +0.8100 | 3.00 | 1.000 | 1.95 |
| 0.05 | +0.7869 | 3.15 | 0.993 | 14.85 |
| 0.10 | +0.7622 | 3.31 | 0.986 | 26.68 |
| 0.30 | +0.6502 | 3.99 | 0.946 | 85.67 |
| 1.00 | −0.0811 | 11.90 | 0.447 | — |
The return column falls monotonically with ε, which looks like a clean verdict. But it is measuring the agent while it explores, so much of the loss is the exploration premium rather than a worse policy. At ε = 0.10, a tenth of all moves are random by construction; the underlying Q-table may still be perfect.
The length column separates two failure modes the return conflates. At ε = 0.30 the length is 3.99 against an optimal 3.00 — the agent is wandering, not failing. At ε = 1.00 the length is 11.90 and the success rate has collapsed to 0.447, which is a different situation entirely.
The success rate is the only column a non-specialist can read, and note that it is the least sensitive: it still reads 0.986 at ε = 0.10, where the return has already lost 6% of its value. A metric that is easy to interpret is often easy to satisfy.
The regret column measures something none of the others do — the total cost of the learning process itself. It separates ε = 0 from ε = 0.05 by a factor of 7.6 while their final policies are nearly identical.
Every claim carries its optimal value beside it, and the seed count is stated because it is the difference between a measurement and an anecdote.
And add the caveat that the experiment of section 6.3 established: this ranking is a property of this environment. Adding one small reward near the start reverses it completely, and the greedy agent that is optimal here reaches the real goal 1.5% of the time there. A reported result in reinforcement learning is a statement about an agent and an environment jointly, never about the agent alone.
Learning during, performance after
This is 2.1's separation of selection from estimation, in a new costume. There, a number used to choose a setting could not also estimate performance. Here, a number earned while deliberately acting randomly cannot also describe the policy learned. Evaluate greedily, periodically, with learning off, and report that.
Depth — why reinforcement learning results are so often irreproducible
The variance between runs is much larger here than in supervised learning, and for structural reasons rather than sloppiness. The agent's data depends on its own early random choices, so two seeds diverge from the first episode and the difference compounds — a lucky early path is reinforced and shapes everything after it. Section 4.7's XOR result, where the same architecture succeeded from 16.5% of initialisations, is the closest analogue in this course, and reinforcement learning is worse.
The consequence is that a result from a single seed is close to meaningless, and published comparisons have repeatedly been shown to reverse when re-run with different seeds or a different implementation of the same algorithm. Henderson and colleagues (2018) demonstrated this on standard benchmarks and it prompted a lasting change in reporting norms.
What honest reporting looks like: at least 5 to 10 seeds, a mean with a spread or interquartile range rather than a best run, the whole learning curve rather than a final number, and every hyperparameter including the seed range. Report the environment version, because small changes to reward scaling or termination conditions change results substantially. And avoid the specific temptation of picking the best seed, which is the reinforcement-learning form of tuning on the test set and is just as invalid.
The visualization
Learning curves, and the cost of exploring
interactive — training against greedy evaluationThe teal curve is training return with exploration included; the amber curve is the greedy policy evaluated separately with learning switched off. At any ε > 0 the amber curve sits above the teal one, and the gap between them is exactly the exploration premium — the thing that must not be reported as the agent's performance. Drop the seed count to 1 and watch the curve become a jagged step function, which is the case for the depth box above. Note that the spread is averaged over the whole curve rather than its tail: on a grid this small every seed converges to exactly 0.810 in the end, so the tail spread is zero and the variance lives entirely in the learning phase.
The pitfalls
Where marks are lost
- Reporting training reward as the result. It includes the exploration premium. Evaluate greedily.
- Reporting a single seed. The variance is larger here than anywhere else in the course. Use 5 to 10 and report the spread.
- Quoting cumulative reward with no optimal value beside it. A return of 0.65 means nothing until you know the optimum is 0.81.
- Confusing regret with final performance. Regret measures the cost of learning. An agent can end optimal and still have enormous regret.
- Using success rate alone. It is the least sensitive of the four and can stay near 1 while the return degrades.
- Comparing agents on different environment versions. Reward scaling and termination rules change results substantially, so the version is part of the result.
- Treating a high score as evidence the task was solved. It is evidence the reward function was maximised, which 6.1's depth box shows is a different claim.
Practice
P6.4.1 (direct) — An agent's returns over 6 episodes are 0.00, 0.00, 0.59, 0.66, 0.73, 0.81, and V*(s₀) = 0.81. Compute the total regret and the mean return over the last three episodes.
The two numbers answer different questions and both are worth reporting. Total regret 2.07 says learning cost the equivalent of about 2.5 optimal episodes — the price of getting here. Mean return 0.7333 describes recent behaviour but is dragged down by episodes 4 and 5, which are already history; the final episode alone achieved the optimum. On a short run like this, quoting the last episode is over-optimistic and the last-three mean is pessimistic, which is why a learning curve is better than either.
P6.4.2 (variation) — Two agents both end with an optimal policy. Agent A has total regret 12 over 500 episodes; agent B has 340. Both report a final return of 0.81. When would you prefer B?
If learning happens offline, in simulation, before deployment — prefer neither, or prefer B if it is more robust. Regret accumulated in a simulator costs compute, not consequences. If both reach the same policy, 340 units of simulated regret is a wall-clock cost and nothing more, and A's advantage largely evaporates.
If learning happens online, on the real system, prefer A decisively. Regret is then real: real recommendations shown to real users, real trades placed, real medication doses given. Agent B was wrong 28 times as expensively on the way to the same answer.
And there is a case for B that the numbers hide. Low regret means the agent explored little, which means it committed early to what it found. On this environment that worked, but section 6.3's second experiment showed a greedy agent locking onto a local optimum and reaching the real goal 1.5% of the time. B's higher regret bought coverage, and coverage is insurance against an environment slightly different from the one tested. If the deployment environment may differ from the training one, B's exploration is a feature.
So the honest answer is that regret alone cannot decide it: you need to know whether the regret was paid in simulation or in reality, and whether the environment is fully known.
P6.4.3 (interpretation) — A paper reports "our method achieves 4,200 mean reward, versus 3,850 for the baseline." What is missing?
Almost everything needed to evaluate the claim, and this is the standard failure the depth box describes.
No seeds and no spread. A single run of each, on a difference of 9%. Reinforcement-learning variance between seeds routinely exceeds that, so the result may reverse on a re-run. Report at least 5 to 10 seeds with a mean and interquartile range, and compare properly rather than by eye.
No scale. 4,200 of what maximum? Without the optimal value, or at minimum a random-policy baseline and a human score, the number is uninterpretable — this is 2.4.2's majority-class argument, unchanged.
No statement of training or evaluation. Was 4,200 earned while exploring, or by a greedy evaluation with learning off? The two differ substantially and only the second describes the method.
No budget and no environment version. A method that wins with ten times the samples has not won on equal terms, so report sample counts and wall-clock cost. And reward scaling or termination rules differ between environment versions, so the version is part of the result.
No learning curve. The final number cannot distinguish an agent that converged quickly and sat at 4,200 from one that spiked there on the last evaluation. The curve, with a spread band across seeds, is the honest presentation and would show both.
P6.4.4 (synthesis) — Using 2.4.6, 3.5 and 4.8, place reinforcement-learning evaluation in the arc of the whole course.
Supervised learning had an external referent and a protocol for using it. Section 2.4.6's rule — select on validation, estimate on test, report a spread — works because held-out labels exist independently of the model. The metrics could be gamed, but the ground truth could not.
Unsupervised learning had no referent at all, which was section 3.5's difficulty. "Better" had to be assembled from geometry, stability and a null baseline, and the honest conclusion was that unsupervised model selection is fundamentally weaker.
Reinforcement learning has a referent that you wrote. Reward is objective and measurable, so one policy definitely beats another under it — a real advantage over Unit 3. But the referent is a specification rather than a fact, so maximising it is not the same as succeeding, and 6.1's reward-hacking examples are what that gap looks like when an optimiser finds it. In a precise sense this is the sharpest version of a problem the course has raised repeatedly: 2.4.2's accuracy, 3.2's silhouette and 4.8's calibration were all proxies too, but here the proxy determines behaviour rather than a prediction, so the consequences are actions in the world.
And one difficulty is entirely new. Every earlier setting could evaluate on data the model did not influence. Here the agent generates its own data, so there is no held-out experience, no counterfactual, and no way to ask what would have happened under a different policy without running it. Section 4.8's insistence on several seeds becomes a requirement rather than good practice, and the separation of training from greedy evaluation is the only substitute available for a train/test split.
The thread running through all four units is a single question: what is this number entitled to claim? The answer has become progressively more restrictive — from "this model predicts held-out labels this well", to "this partition is geometrically tidy and reproducible", to "this agent maximised the objective I wrote, in the environment I tested, from these seeds". Learning to state the last one precisely is most of what a machine learning education is for.
Cheat Sheet
Every formula in this unit, plus the grid's exact numbers.
6.1 The loop
Agent observes sᵗ, acts aᵗ by policy π, receives rᵗ₊₁ and sᵗ₊₁.
Return Gᵗ = Σₖ γᵏ rᵗ₊ₖ₊₁
The agent maximises the return, not the next reward.
A reward on the k-th transition is discounted by γᵏ⁻¹.
Horizon ≈ 1/(1−γ): γ=0.9 is ten steps.
Feedback is evaluative, not instructive, and delayed.
6.1 Reward design
The reward function is the specification. The agent maximises what you wrote.
Reward hacking: the boat that circles a lagoon forever and outscores every human.
Reward the goal, not the method.
Shaping rewards change the optimal policy unless they take the potential-difference form.
γ < 1 or a step penalty — either makes delay costly; a step penalty makes γ=1 safe on looping tasks.
6.2 MDP
(S, A, P, R, γ)
Markov property: the present state contains all of the past that matters. A property of your state representation, not of the world — enlarge the state until it holds.
Vᴵ(s) value of a state · Qᴵ(s,a) value of an action
Q is more useful: π(s) = argmaxₐ Q(s,a) needs no knowledge of P.
6.2 Bellman
V*(s) = maxₐ Σₛ' P(s'|s,a)[R + γV*(s')]
Q*(s,a) = R + γ maxₐ' Q*(s',a') (deterministic)
V(terminal) = 0. The reward is earned on entering.
A wall move still costs a discount: γV(s), not V(s).
Finite MDP, γ<1: an optimal deterministic policy exists, and value iteration converges globally — the operator is a contraction.
6.3 The Q-learning update
δ = r + γ maxₐ' Q(s',a') − Q(s,a)
Q(s,a) ← Q(s,a) + αδ
Same shape as gradient descent, with α as the learning rate — but the target is itself an estimate (bootstrapping).
Model-free: P and R never appear as known.
Off-policy: the max makes it learn π* while behaving otherwise.
Converges to Q* if every (s,a) is visited infinitely often.
6.3 What the trace shows
Reward propagates backwards one step per episode.
Episode 1 moves only the goal action; the start square first changes at episode 4.
Goal action: 0.5, 0.75, 0.875 — exactly 1 − (1−α)ⁿ.
So episodes needed grow with distance from the reward — hence n-step returns and experience replay.
An untried action stays at its initial value forever.
6.3 Exploration
ε-greedy: random with prob ε, else argmax.
Decay: εₖ = max(εₘᵢₙ, ε₀·decayᵏ); 1.0 at 0.99 hits a 0.05 floor at episode 299.
Zero-init is OPTIMISTIC when rewards are positive — ties broken at random already explore.
Plain grid: ε=0 wins, regret 1.95 vs 26.68 at ε=0.1.
With a +0.3 trap: ε=0 finds the real goal 1.5%, decaying ε finds it 77%.
Exploration is insurance, and it has a premium.
6.3 Beyond the table
A table has one entry per (s,a) and cannot generalise.
Deep Q-learning: fit Q(s,a;θ) by gradient descent on the squared TD error.
Loses the convergence guarantee — the target moves as you chase it.
Fixes: a target network, and experience replay, which also propagates reward far faster than one step per episode.
SARSA uses the action taken instead of the max, and learns the exploring policy's value.
6.4 Four measures
Cumulative reward — the headline; hides time and trend
Regret = Σ[V*(s₀) − Gₖ] — the cost of learning, not of the final policy
Episode length — catches dithering; optimal is 3 here
Success rate — the only one a non-specialist reads, and the least sensitive
Each is gameable alone. Report all four with their optimal values beside them.
6.4 Honest reporting
Training performance ≠ evaluation performance. Training return includes the exploration premium; evaluate greedily with learning off.
At ε=0.30, training return 0.6502 while the policy underneath is nearly optimal.
5 to 10 seeds minimum, with a spread. One seed is an anecdote.
Quote the optimal value, the sample budget and the environment version.
Never pick the best seed — that is tuning on the test set.
The grid, exactly
V*: 0.81 0.90 / 0.90 1.00 — pure powers of γ
Q* at (0,0): up 0.729, down 0.81, left 0.729, right 0.81 — a tie
Q* at (0,1): up 0.81, down 0.90, left 0.729, right −1.00
Optimal return from start 0.81 = 0.9²; optimal length 3
If a value on this grid is not a power of 0.9, the arithmetic is wrong.
Common slips
Forgetting max Q(s',a') = 0 at a terminal — the commonest error in the topic.
Using the action taken rather than the max (that is SARSA).
Updating Q(s',a') instead of Q(s,a).
Off-by-one on the discount exponent.
Giving a terminal state a non-zero value.
Reporting training reward as the result.
The spine, end to end
| Quantity | Value | Section |
|---|---|---|
| Return of the 3-step path, γ = 0.9 | 0.8100 | 6.1 |
| Return of a 5-step detour | 0.6561 | 6.1 |
| Return of the 2-step path into the pit | −0.9000 | 6.1 |
| V* across the grid | 0.81, 0.90 / 0.90, 1.00 | 6.2 |
| Q* at the start | 0.729, 0.81, 0.729, 0.81 — a tie | 6.2 |
| Q* for stepping into the pit | −1.0000 | 6.2 |
| V* at γ = 0.5 | 0.25, 0.50 / 0.50, 1.00 — same policy | 6.2 |
| Q-learning, goal action after 1, 2, 3 visits | 0.5000, 0.7500, 0.8750 | 6.3 |
| First episode that changes the start square | episode 4 | 6.3 |
| Q((0,1), right) after falling in the pit once | −0.5000 | 6.3 |
| Closed form of the goal action | 1 − (1−α)ⁿ | 6.3 |
| ε decay: 1.0 at 0.99 reaches the 0.05 floor | episode 299 | 6.3 |
| Plain grid: total regret at ε = 0 / 0.05 / 0.10 | 1.95 / 14.85 / 26.68 | 6.3 |
| Plain grid at ε = 1.00 | return −0.0811, length 11.90, success 0.447 | 6.3 |
| With a +0.3 trap (worth a flat 0.30): reaches the real goal | ε=0 gives 1.5%, decaying ε gives 77% | 6.3 |
| Training return at ε = 0.30 | 0.6502, with a near-optimal policy underneath | 6.4 |
Mixed Self-Test
Ten questions, unlabelled by section.
Q1. Rewards 1, 0, 0, 3 are received over four steps. Compute the return at γ = 0.8, and say how much of it comes from the final reward.
At γ = 0.8 the distant +3 still dominates, because 0.8³ = 0.512 retains over half its value. Drop to γ = 0.5 and it contributes 0.125(3) = 0.375 against the immediate 1, so the ordering of what matters flips. Whether a distant reward is worth pursuing is set by γ, not by the agent.
Q2. On the spine grid, compute Q*((1,0), a) for all four actions and identify the optimal one.
Note the two wall moves are worth 0.81 — more than moving up to a genuinely worse square. Bouncing off a wall wastes one step and costs a single factor of γ; moving up costs a step and lands somewhere further from the goal. And the check that maxₐ Q*(s,a) = V*(s) holds is worth doing every time, since it catches most arithmetic slips.
Q3. An agent has Q(s, ·) = (0.3, 0.9, 0.2, 0.9) and uses ε-greedy with ε = 0.2. Give the probability of each action.
The tie matters more than it looks. If the implementation always breaks ties by taking the first index, action 2 gets 0.85 and action 4 gets 0.05, so the agent systematically ignores an equally good action — and on the spine grid, where the start square has exactly this tie, that means one of the two optimal paths is never explored. Random tie-breaking is a real design decision, not tidiness, and section 6.3 showed it is the mechanism by which a greedy agent explores at all.
Q4. Q(s,a) = 0.6, the agent receives r = −1 and lands in a terminal state. With α = 0.3 and γ = 0.9, give the new value. How many such updates to bring it below 0?
The closed form is the same geometric decay as P6.3.2, with the target at −1 instead of +1: the error shrinks by a factor of 1−α each visit and the estimate approaches the target from wherever it started. Note that one bad experience is not enough to make the action look bad here — the estimate is still positive after the first update — which is why a single catastrophic outcome may be repeated before it is learned.
Q5. Explain why Q-learning is called off-policy, and what would change if the update used Q(s', a') for the action actually taken next.
Off-policy means the policy being learned about is not the policy generating the behaviour. The update's target is r + γ maxₐ' Q(s',a'), which asks "what is this worth if I play optimally from here", regardless of what the agent will actually do next. So the agent can behave randomly, or follow a fixed demonstration, or replay old experience from a policy it no longer uses, and still converge on Q*.
That property is what makes exploration safe. An ε-greedy agent takes deliberately bad actions and its Q-table is not corrupted by them, because the max in the target ignores the exploration. It is also what makes experience replay possible, since stored transitions come from an older, worse policy.
Replacing the max with the action actually taken gives SARSA, an on-policy method, and it learns Qᴵ for the exploring policy rather than Q*. The practical difference is instructive: on a grid with a hazard beside the optimal path, SARSA learns that walking beside the pit is dangerous because it sometimes explores into it, and so prefers a longer safer route. Q-learning learns the optimal path and then walks it while occasionally falling in. Neither is wrong — SARSA evaluates the policy you will actually run, which is the right thing when exploration cannot be switched off in deployment.
Q6. A robot arm has 6 joints, each discretised into 20 positions, and 12 possible actions. How large is the Q-table, and what does that imply?
The memory is merely awkward; the visits are the fatal problem. Even at a thousand transitions per second, visiting each entry once takes about nine days, and Q-learning needs many visits per entry. Worse, the table cannot generalise at all: having learned about one joint configuration it knows nothing about the configuration one increment away, even though they are nearly identical physically.
So this is exactly where the table must be replaced by function approximation. Represent Q(s,a;θ) as a network taking the six joint angles as input, and a single update improves the estimate for every similar configuration at once. That generalisation is the point, not the memory saving — and it is why Units 4 and 5 are prerequisites for anything beyond a toy problem, even though this unit needed none of them.
Q7. An agent is trained with ε = 0.2 throughout and reports a mean return of 0.68 where the optimum is 0.81. A colleague concludes the policy is 16% suboptimal. Assess.
The conclusion does not follow, because the 0.68 was measured while the agent was deliberately acting randomly a fifth of the time. Section 6.4's distinction applies directly: this is a training number, and it includes the exploration premium. The policy underneath may be exactly optimal.
The test is one line: evaluate greedily. Run episodes with ε = 0 and learning switched off. Worked 6.3b measured precisely this situation — at ε = 0.30 the training return was 0.6502 while the underlying policy was very nearly optimal — so the expected outcome here is a greedy return close to 0.81 and a conclusion of "the policy is fine; the report was measuring the wrong thing".
If greedy evaluation also gives 0.68, then the criticism stands and the diagnosis moves on: check for unvisited state-action pairs, check for a local optimum of the kind section 6.3's second experiment constructed, and check the learning rate. But that is a different investigation and it should not be started until the cheap test has been run.
And in either case the report is inadequate. One number, no seeds, no spread, and no statement of whether it was a training or an evaluation figure. Section 6.4's checklist asks for all four measures with their optimal values beside them, over at least five seeds.
Q8. A recommendation agent is rewarded +1 per click. Predict what it will learn, and propose a better reward.
It will learn to maximise clicks, which is not the same as being useful, and the gap is exploitable in specific ways. Expect it to favour content that provokes rather than informs, since outrage and curiosity gaps are reliably clickable. Expect clickbait framing over accurate framing. Expect it to recommend items the user would have found anyway, because those click reliably. And expect no weight at all on whether the user was glad afterwards, because nothing in the reward mentions it.
This is 6.1's reward-hacking argument, and it is not hypothetical — engagement-optimised recommendation is the most consequential deployed example of it.
A better reward has to state more of what you want. Weight a click by dwell time or completion, so a click followed by an immediate bounce is worth little. Include an explicit negative for a hide, a report or an unfollow. Reward returning tomorrow rather than clicking today, which converts a one-step objective into a long-horizon one and is where the discount factor earns its place. And add a diversity term, so that exploiting one narrow interest is penalised.
Two cautions, though. Every added term is another surface to hack, so the list above is an improvement rather than a solution. And some of what you want — whether the recommendation was good for the person — may not be measurable from behaviour at all, in which case no reward function captures it and the honest response is to constrain the agent's action space rather than to keep refining the reward. Section 2.6's argument, arriving where the model's output is behaviour.
Q9. On the spine grid, an agent has learned Q perfectly except that Q((0,1), right) = 0 because it has never stepped into the pit. Is its greedy policy optimal? What is the risk?
The greedy policy is optimal, and the agent has still not learned the environment. Its error is on an action it never takes, so the error is invisible in its behaviour and costs nothing while conditions hold. This is a good illustration of why Q-learning converges only under the condition that every state-action pair is visited infinitely often: without it, Q ≠ Q*, even when π = π*.
The risk is that the policy is correct for the wrong reason and is not robust. If anything perturbs the values — a change in the reward scale, a stochastic transition, a small negative step cost that pushes Q(down) below 0 — then Q(right) = 0 becomes the maximum and the agent walks confidently into the pit. An unexplored action with an optimistic default is a latent failure, and zero-initialisation is exactly such a default when the true value is negative.
Which is the argument for exploration that section 6.3's first experiment appeared to undermine. On that plain grid, greedy was optimal and cheapest; this question shows the sense in which it was nonetheless underinformed, and the trap experiment shows what happens when that underinformation matters.
Q10. Across the whole course, state what supervised, unsupervised and reinforcement learning each require and each provide, and what question runs through all three.
Supervised learning requires labelled examples and provides a function that predicts them. Its great advantage is an external referent: held-out labels exist independently of the model, so "is this prediction correct" has an answer nobody invented. Units 1, 2, 4 and 5 are all this, with progressively more flexible function classes — a line, then six model families, then a network, then a network with architectural assumptions baked in.
Unsupervised learning requires only data and provides a summary of its structure. It has no external referent, which was section 3.5's difficulty: "better" had to be assembled from geometry, reproducibility and a null baseline, and the honest conclusion was that its model selection is fundamentally weaker. Unit 3's payoff figure — PCA optimally retaining 56.7% of the variance while collapsing two of three clusters — is the sharpest statement of what a proxy objective can cost.
Reinforcement learning requires an environment it can act in and provides a policy. Its referent is objective but self-authored: reward is measurable, so one policy definitely beats another, yet a high score certifies only that your specification was maximised. And it is the only one of the three where gathering information competes directly with performing well, so exploration must be paid for out of the budget being optimised.
The question running through all three is what a number is entitled to claim, and the answer has narrowed at every step. Unit 2 could say "this model predicts held-out labels this well, with this spread, on data used once". Unit 3 could say only "this partition is geometrically tidy and survives resampling". Unit 6 can say "this agent maximised the objective I wrote, in the environment I tested, from these seeds, and here is the exploration premium separated out".
Every unit produced at least one number that meant less than it appeared to: accuracy holding at 0.7000 across three genuinely different classifiers; every internal index preferring a finer clustering than the truth; a 56.7%-variance projection destroying the structure; three AUCs of exactly 1.0000 beside an accuracy of 0.8333; and a training return of 0.6502 concealing a near-optimal policy. Learning to state precisely what a result does and does not establish is not a supplement to the technical material. It is the technical material.
Where This Goes Next
The end of the course, and the shortest honest account of what comes after it.
What Unit 6 established, in one paragraph
Take away the labels and the dataset both, and learning becomes something an agent does by acting. The formal object is a Markov decision process, and its Bellman recursion computes every value on the six-square grid exactly — pure powers of γ, with the optimal return from the start being 0.9² = 0.81. Q-learning reaches those same numbers without a map of the environment, by replacing an expectation with a single sample and moving its estimate a fraction toward it, and the hand-worked trace shows reward crawling backwards exactly one step per episode — nothing at the start square moves until the fourth. Exploration is then the genuinely new dilemma: on the plain grid a purely greedy agent wins on every measure with a seventh of the regret, and adding one small reward near the start drops it to finding the real goal 1.5% of the time. Both facts are measured, and neither generalises. And evaluation is the hardest it has been all course, because the agent generates its own data, there is no held-out experience, and a reported return may be measuring the exploration premium rather than the policy.
| From here | Where it leads |
|---|---|
| 6.3 Q-learning with a table | Deep Q-networks. Replace the table with a network, add a target network and experience replay. This is where Units 4 and 5 rejoin the story. |
| 6.3 Learning a value, then acting greedily | Policy-gradient methods — REINFORCE, actor-critic, PPO — which optimise the policy directly and handle continuous action spaces that an argmax cannot. |
6.2 Knowing P and planning against it | Model-based RL, and the AlphaZero family, where a learned model is searched with Monte Carlo tree search. Far more sample-efficient than model-free methods. |
| 6.1 The reward function as a specification | Reward modelling and RLHF — learning the reward from human comparisons rather than writing it down, which is how current language models are aligned to instructions. |
| 6.4 The variance problem | An active reform of empirical standards across the field, and a reason to read published comparisons carefully. |
| 2.6, 4.8, 6.1 Optimising a proxy | AI safety and alignment as a research area: the study of what happens when a capable optimiser is given an imperfect objective. |
Before the exam
Eight things you should be able to do from a blank page. Compute a discounted return from a reward sequence, with the exponent right. State the five components of an MDP and say what the Markov property assumes. Solve a small grid by backward induction and check that maxₐ Q*(s,a) = V*(s). Write the Q-learning update and apply it, remembering that max Q = 0 at a terminal. Trace several episodes and explain why reward propagates backwards one step at a time. Give the ε-greedy action probabilities including tied maxima. Compute regret from a return sequence. And explain why training return and greedy return are different quantities.
The open-book format rewards the cheat sheet above; what it cannot supply is the habit of checking a number against what it is entitled to claim, and that is what the interpretation problems in every unit were for.
Further reading
- Géron, Hands-On Machine Learning, 3rd ed., ch. 18 — the prescribed textbook's treatment, covering policy gradients and deep Q-networks with working code.
- Sutton and Barto, Reinforcement Learning: An Introduction, 2nd ed. — the standard text of the field, freely available online. Chapters 3, 4 and 6 cover exactly this unit and cover it better than any summary can; chapter 6's comparison of Q-learning with SARSA on the cliff-walking grid is worth working through.
- Silver, UCL Course on Reinforcement Learning — lecture videos and slides, freely available. Lectures 1 to 4 map onto sections 6.1 to 6.3 almost exactly.
- Mnih et al., "Human-level control through deep reinforcement learning" (2015) — the DQN paper. Short, and the target network and replay buffer are introduced with the reasoning intact.
- Henderson et al., "Deep Reinforcement Learning that Matters" (2018) — the paper behind section 6.4's depth box. Read it before believing any published comparison.
- Amodei et al., "Concrete Problems in AI Safety" (2016) — where the reward-hacking examples come from, and the clearest short statement of why an imperfect objective given to a capable optimiser is a technical problem rather than a philosophical one.
The last word
Six units, six spines. Five students and a straight line; eight students that six different models all fitted perfectly while disagreeing everywhere between them; twelve students in three clusters that every index agreed on and PCA destroyed; four points that no line can separate and nine weights that can; three shapes read once whole and once one row at a time; and six squares with no instructions at all.
The arithmetic in every one of them was small enough to check by hand, and that was the point. Every claim in these files can be verified with a pencil, and a claim you have verified is a claim you own.
Spine: a six-square grid world with a goal worth +1, a pit worth −1, and γ = 0.9, in which every optimal value is a whole power of γ and the optimal return from the start is exactly 0.81. Every numerical value in this file was computed rather than estimated, and every widget was driven through its range and checked against the printed worked examples.
Previous: Unit 5 — Deep Learning Foundation · This is the final unit of the course.