Wait until the episode ends, then move every visited state towards the return G it actually got (every visit counts).
Introduction to Reinforcement LearningPart 2 · Learning from experience
Lecture 5Model-free prediction
Learning the value of a policy from experience, with no model: Monte Carlo, temporal-difference learning, how the two differ on the same data, multi-step returns, and eligibility traces. With a first look at function approximation.
Key ideas, one per episode
- Ep. 17Play, see what happened, average. No model needed.
- Ep. 18Learn online, from one step: reward now plus your best guess.
- Ep. 19Trust your state? TD. Don't? Monte Carlo.
- Ep. 20Look a few steps ahead, or look back with traces.
Based on: Lecture 5: Model-Free Prediction, DeepMind × UCL Reinforcement Learning Lecture Series (2021), by Hado van Hasselt. The slides follow that order of topics, in our own words, figures and examples; they are not official material of the original course.
Watch
4 short episodes of ACML Explains for this lecture. Pick one from the list, and open the transcript to read along: each timestamp plays the episode from there. The narration is generated with a voice clone of Teddy, used with his permission.
Episode 17 · 5:08
Monte Carlo learning
No rules, no model. Just play, see what happened, and average. It's enough to learn Blackjack.
Play, see what happened, average. No model needed.
TranscriptEpisode 17
No model
For two whole modules, Bit knew the rules of the world: p, every probability, every reward. Today we take that away. No model. Bit doesn't know how the world works. He only gets to play. There's a theorem: sample the world forever, and you'll know it exactly. Very nice. Good luck sampling even a small game perfectly. So we need methods that learn well from a finite pile of experience. First goal: prediction. Given a policy, learn its values, from samples only. Two methods, this episode and the next: Monte Carlo, and temporal differences. Today, Monte Carlo.
Monte Carlo
Method one is named after a casino: Monte Carlo. The idea is almost embarrassingly simple. Play. See what happened. Average. The name? The casino in Monaco. Rolling dice, many, many times. That's the whole method. You already did this, in module two. A bandit: for each handle, average the rewards you got. That's Monte Carlo. Now add states. Each state is its own little bandit. The episodes still last one step, and actions don't change the next state. Like showing an ad to a user: the user is the state, the ad is the action, a click is the reward. Average the clicks for each kind of user and each ad, and you have a value for every pair.
Features
But with millions of users, you can't keep a table with one number per user. So describe each state with a few features: numbers like age, time of day, past clicks. Call that vector x of s. And make the value a weighted sum of the features: v of s is w times x of s. A linear value function. And here's a nice surprise: a table is a special case. Give each state its own feature, one for that state, zero for everything else. One-hot features, and the weights are exactly the table entries. A linear model sounds weak. With good features, it goes surprisingly far.
Learning the weights
How do we learn w? Minimise the squared error between what happened and what we predicted. Take a gradient step: move w by α, times the error, times the features. Error times feature. Features that were on get the blame, or the credit. Same idea as supervised learning, with the return as the label. And with one-hot features, this is exactly the incremental average from module two. Same formula, new clothes.
Whole episodes
Now, real sequences. Bit plays a whole episode with his policy: state, action, reward, state, and so on, until it ends. For every state he visited, compute the return from there: everything that came after. Then nudge that state's value toward the return. Or just average all the returns you ever saw from it. Count a state once per episode, or every time it appears. First visit, or every visit. Both converge. And the step size: one over the number of visits gives the exact average. A constant α slowly forgets old games, which helps if the world changes. By the law of large numbers, from module two, the average converges to the true value. No p anywhere.
Blackjack
Let's try it on Blackjack. This is the example we played with in class. It's a nice fit: every game is an episode, it always ends, and the rules are a pain to write down as probabilities. You want your cards to sum closer to twenty-one than the dealer's, without going over. The state: your sum, from twelve to twenty-one. The dealer's visible card, ace to ten. And whether you hold a usable ace. Ten times ten times two: two hundred states. Below twelve, you always take a card; you can't go bust. Three numbers describe the whole situation. Near enough, that's the Markov state of Blackjack. Actions: stick, or take another card. The reward comes only at the end: plus one for a win, zero for a draw, minus one for a loss. The policy we'll evaluate: stick on twenty or twenty-one, otherwise always take a card. Bold. Maybe too bold.
What it learned
We ran it. After ten thousand games, the values are bumpy. Especially with a usable ace: those states are rare, so there's little data. After half a million games, the surface is smooth. Half a million games, in seconds, on a laptop. Try that at a real casino. And look: it's only high at twenty and twenty-one. Everywhere else, this policy loses money. Hitting on nineteen is not a great plan. And when the dealer shows an ace, everything drops. Monte Carlo found all of that without knowing a single rule of the game. Two hundred states, and ten thousand games still leave holes. Now imagine chess.
The catch
So what's the catch? Monte Carlo has to wait until the episode ends. Only then is the return known. Long episodes: slow learning. Episodes that never end: no learning at all. And because each return adds up many random steps, it's noisy. Can we learn before we know how the story ends? Yes. Next time: temporal differences. With me so far?
Sample the Bellman equation
Remember the Bellman equation: the value of a state is the expected reward, plus γ times the value of the next state. Dynamic programming computes that expectation, using p. Temporal-difference learning says: I don't have p. But I just took one step. Let me use that one step as a sample. That's the whole idea. The rest is details. It's Bellman's equation again, with one sample instead of the full average.
The TD update
So: Bit is in a state. He acts, gets a reward, and lands in the next state. His target: the reward, plus γ times his current guess for the next state. Nudge the old value toward that target, by a step size α. The gap between the target and the old value has a name: the TD error, δ. In Monte Carlo, we had the return in our hands. In TD, we don't. We hold the reward we just got, plus our previous best guess. That's TD's return. If the next state turned out better than expected, δ is positive, and the value goes up. Worse than expected, it goes down. And notice: no p anywhere. The world just handed Bit the next state. Learning a guess from a guess. It sounds like cheating. It works. The reward is real. Only the rest is a guess. Each step, a little more truth gets in.
Online, and the square
And it's online. You act, and you learn. Right away, after every step. Monte Carlo waits for the end of the episode. Like tasting the soup every minute while you cook, instead of waiting until the guests have left. Now, my favourite figure: the square. Every method lives in a two-dimensional space. How deep you look down the tree, and how wide. One step, one branch: that's TD. The whole branch, to the end: Monte Carlo. One step, but every child: dynamic programming. And the whole tree, everything: exhaustive search. TD and dynamic programming both look one step ahead. The difference: DP averages over every next state. TD uses the one that actually happened. So in the square, TD is the cheap corner. One step, one sample. Four corners, four algorithms. Everything else lives somewhere in between.
Bootstrapping and sampling
Two words to keep them apart. Bootstrapping: the update uses an estimate. Dynamic programming and TD bootstrap. Monte Carlo doesn't. Sampling: the update uses one sample instead of an expectation. Monte Carlo and TD sample. Dynamic programming doesn't. TD is the one that does both: it samples, and it bootstraps. And the same trick works for action values. TD on q has its own name, SARSA. We'll meet it next module.
A trick question
A trick question. Is a dynamic-programming update bigger than a TD update? Than a Monte Carlo one? Bigger than TD: TD looks at one action, DP at all of them. Than Monte Carlo? It depends. Ten children below you, but a branch a hundred steps long? Monte Carlo looks at more. So the size of an update isn't about the method's name. It's about the shape of the tree. Good exam question, by the way. You didn't hear it from me.
Driving home
A classic example: driving home. Leaving the office, I predict thirty minutes. Reaching the car, it's raining: forty in total. The highway goes well: thirty-five. Then I get stuck behind a truck: forty again. Entering my street: forty-three. And I arrive after forty-three minutes. Elapsed time, plus predicted time to go: that's the predicted total. Watch it move. Monte Carlo waits until I'm home, then pulls every prediction toward forty-three. TD adjusts each prediction toward the next one, as I drive. Stuck behind the truck? I already know I was too optimistic on the highway. By the time I'm home, TD has already done most of the learning.
Bias and variance
So TD can learn before knowing the final outcome. From incomplete episodes. Even in tasks that never end. A robot that runs for weeks never reaches an end. TD learns anyway. There's a price, though. The Monte Carlo return is an unbiased estimate of the value. It's what really happened. The TD target uses a guess, so it's biased. Until the guesses are right. But the Monte Carlo return depends on many random actions, rewards and transitions. Lots of noise. The TD target depends on only one step. Monte Carlo: no bias, high variance. TD: some bias, low variance. The classic trade-off. Lower variance means smoother learning: fewer wild jumps, and usually a bigger step size you can afford. In practice, TD often learns faster. But Monte Carlo is more robust when the state isn't really Markov. More on that next time.
Do they agree?
So which one wins? Same data, same world: do they even agree? With enough data and a step size that shrinks properly, both converge to the true values. The question is what happens before that. Spoiler: on finite data, they can disagree. And both are right. Next time: random walks, and a case where they give different answers. Both, kind of, right. With me so far?
A random walk
Last time: Monte Carlo and TD, two ways to learn values from experience. Today, let's race them. The track: a random walk. Five squares in a row, A to E. Bit starts in the middle, on C. Each step, he moves left or right, fifty-fifty. Fall off the right end: one point. Fall off the left: nothing. So the only reward in the whole world sits at the far right edge. So a square's value is the chance of finishing on the right. From the middle: one half. The true values are easy to work out. A is worth one sixth. Each square to the right adds one more sixth, up to five sixths for E. Why such a toy? Because we know the right answer, so we can measure the error exactly.
TD learns it
Start every guess at one half, and run TD with a step size of point one. After the first episode, only one value moved. Bit fell off the left end, and only A felt it. Every other step compared one half with one half. No surprise, no update. After ten episodes, a slope appears. After a hundred, it's close to the truth. Notice the edges learn first. That's where things actually happen. E sits next to the reward, so it learns fast. A sits next to nothing, so it learns from its neighbour. Information flows backwards, one step at a time, from where the rewards are. With a step size of point one, the guesses never fully settle. They jiggle around the truth. A smaller step: smoother, but slower.
The race
Now the race. A hundred runs, a hundred episodes each, and we measure the average error. Monte Carlo, with a few step sizes. Then TD. On this problem, TD learns faster, for every step size we tried. And look at the TD curves. The biggest step size is fastest at first, then stalls higher. The smallest is slow, but ends lowest. Not a theorem, by the way. But a pattern you'll see a lot. Monte Carlo pays for its noise. Every return depends on the whole random path. TD pays for its bias. Early on, it leans on guesses that are still wrong.
Batch learning
Now a different question. Suppose the data is fixed. Just a handful of episodes, and no more. Replay them again and again, until the values stop moving. That's called batch learning. That's the situation in many real projects: you have a log of data, and that's all you'll get. A log of driving data, a hospital's records, a history of games. Fixed. Squeeze everything out of it. With infinite data, both methods find the true values. With finite data, do they agree?
A and B
Two states, A and B. No discounting. Eight episodes. Once: A, reward zero, then B, reward zero, the end. Six times: B, reward one, the end. And once: B, reward zero, the end. What's the value of B? Six good endings out of eight: three quarters. Everyone agrees. What's the value of A? Think about it for a second. Pause the video if you like. I'll wait. Who would you bet on? Monte Carlo says zero. The only time we saw A, the return was zero. TD says three quarters. A always went to B, with reward zero, and B is worth three quarters. Same data. Two answers. Zero, and three quarters.
Who's right?
So who's right? Both. They're answering different questions. Monte Carlo finds the values that best fit the returns it actually saw. Minimum squared error. TD finds the values of the most likely Markov model behind the data. In that model, A always leads to B. And B pays one, three times out of four. TD assumes the world is Markov: what happens after B doesn't care how you got there. It builds the model in its head, without ever writing it down, and answers as if that model were true. It's called the certainty-equivalence estimate: assume your estimated model is the truth, and solve it. With more and more data, both would agree. It's only the finite data that splits them.
The Markov difference
That's the deep difference. TD exploits the Markov property. Monte Carlo doesn't. When the world is Markov, that's a big advantage: TD squeezes more out of the same data. When it isn't? Say Bit only sees part of the state. Then Monte Carlo is safer: it never assumes anything about what comes next. And partial observability is everywhere in robotics. A camera only sees what's in front of it. Remember module one: is the weather Markov? Not really. Then trust the returns. In practice, people mix the two. That's exactly where we go next.
Which to trust
So: TD usually learns faster, and uses the Markov structure. Monte Carlo makes fewer assumptions. Neither is always better. Know what each one assumes. One looks one step ahead. The other looks all the way to the end. Trust your state? TD. Don't trust it? Monte Carlo. Do we have to choose? What about looking three steps ahead? Or ten? Next time. With me so far?
Two extremes
TD looks one step ahead, and leans on a guess. If the guess is bad, the update is biased. And news travels back slowly, one step per episode. Monte Carlo looks all the way to the end. News travels fast, but the updates are noisy. Each has exactly the strength the other one lacks. TD trusts its guesses too early. Monte Carlo trusts nothing but the end. So why not something in between?
n-step returns
The n-step return: add up the next n real rewards, then lean on the guess n steps ahead. n equals one: that's TD. n equals two: two rewards, then a guess. And n equals infinity, all the way to the end: Monte Carlo. Two steps, written out: the next reward, plus γ times the one after, plus γ squared times the guess two steps ahead. It's a dial. TD on one end, Monte Carlo on the other. Same update rule as before. Only the target changes.
Which n?
Does the middle help? We tried it on a longer random walk: nineteen squares. Minus one on the left, plus one on the right. Ten episodes, a hundred runs, every step size from zero to one, and n from one up to five hundred twelve. The winner: n equals four. Not one, not infinity. Somewhere in the middle. That's our own run, by the way. A hundred runs per setting, ten episodes each. And a large n with a large step size? Worse than not learning at all. Too much noise. Why the middle? Short steps lean on bad early guesses. Long ones drown in noise. On another problem, the best n will be different.
The λ-return
But which n? Why choose at all? Mix them. The λ-return: a weighted average of all the n-step returns. One step gets weight one minus λ. Two steps get a bit less. Each further step, multiply by λ again. λ equals zero: only one step. That's TD. λ equals one: everything goes to the end. That's Monte Carlo. And the weights add up to one. A proper average. Same trick as γ: one over one minus λ is roughly the horizon. λ at point nine is like looking about ten steps ahead. So λ is a dial too, but a smooth one. No need to pick a whole number of steps.
The forward view
There's a catch. To compute the λ-return, you need the whole future. You're back to waiting for the end, like Monte Carlo. And for tasks that never end, there is no end to wait for. That's the forward view: stand in a state, and look ahead. Now flip it. Stand in the present, and look back. Instead of asking what comes next, each new error asks: who deserves the credit?
Eligibility traces
Every state Bit visits leaves a trace behind, like a footprint in wet sand. Visit a state: its trace jumps up. Then, every step, all traces fade, by γ times λ. Visit a state twice in a row, and its trace stacks up. Leave it alone, and it fades. With λ at zero, traces vanish at once: plain TD. With λ at one, they fade only by γ. When something surprising happens, a TD error, it's sent backwards to every state, in proportion to its trace. Recent states get more credit. Frequent states get more credit. That's an eligibility trace. Each state keeps its own trace. With features, it's one trace per weight.
Beep, beep, beep, flash
A little story. Bit hears a beep, a beep, a beep, then sees a flash, and gets a star. What earned the star? Recency says: the flash, it came last. Frequency says: the beep, it happened three times. The trace blends both. The beep's footprint built up, three times. The flash's is fresh. The trace doesn't decide who's right. It spreads the credit, and many episodes sort it out. Animal psychologists asked this exact question long before computers did.
Monte Carlo = sum of TD errors
And here's the beautiful part. If the values stay fixed during an episode, the Monte Carlo error is exactly the sum of the discounted TD errors. So with λ equal to one, traces add up to the Monte Carlo update. But they do it one step at a time, as you go. No waiting. No storing the future. Constant work per step, whatever the horizon. That's why traces are everywhere: they turn a look-ahead method into a look-back one. And with λ in between, you get the λ-return's update, approximately, online. The backward view gives you the forward view's answer, without the waiting.
Module five, done
And that's module five, done. Without a model, Bit can now predict: Monte Carlo, TD, n-step returns, and λ with traces. He can tell how good a policy is. But he still can't find a better one. And the same ideas come right back for control, with q instead of v. Five modules in. The next one is where Bit finally learns to act. Next module: control without a model. Q-learning, SARSA, and a trip to the casino. With me so far? See you there.
5:08Episode 17Monte Carlo learningPlay, see what happened, average. No model needed.
5:11Episode 18Temporal-difference learningLearn online, from one step: reward now plus your best guess.
5:03Episode 19Same data, different answersTrust your state? TD. Don't? Monte Carlo.
5:09Episode 20Between TD and Monte CarloLook a few steps ahead, or look back with traces.
Interactive lab
TD vs Monte Carlo lab
A random walk over five states, A to E. Monte Carlo and TD(0) learn from the very same episodes. Compare their estimates with the true values, and their error curves averaged over a hundred runs.
The random walk of Sutton and Barto (Example 6.2): every episode starts in the middle, at C, and steps left or right with equal chance. Leaving on the right pays 1, on the left 0, so the true values are 1/6, 2/6, …, 5/6.
Same episodes, two ways to learn from them
All rewards are 0 except leaving on the right, which pays 1. No discounting (γ = 1). Both estimates start at 0.5 in every state.
Update after every step, towards the reward plus the current estimate of the next state: learning a guess from a guess.
The true values v are 1/6 … 5/6. Constant step sizes never settle exactly, so the error levels off instead of reaching 0.
Press 1 episode to watch a walk.
Estimates and true values
Value of each state after the episodes so far.
Error over episodes
Your run, one episode at a time.
