Introduction
So far you discovered RL basics and how to solve problems as big as a tic-tac-toe but you might wonder how to solve larger problems for which we don’t know the model. Welcome to this third part “Learning from Experience”
Where Parts 1 and 2 left us in a few words
Part 1, Modeling the World gave us the framework of RL: An agent in state takes an action , receives a reward and lands in ; and it wants to maximize the return, the discounted sum of the rewards to come:
The value functions score states and actions under a policy : and . Because the return is recursive, they satisfy the Bellman equations, one step plus the discounted value of where it leads:
When the model is known, we can use dynamic programming to solve these equations by sweeps (Part 2, Planning with a Model): the Bellman equation is used as an update rule, applied to every state again and again:
The key idea was that optimal policies are always found by algorithms belonging to generalized policy iteration (GPI) composed of two actions:
- an evaluation that makes the value table consistent with the policy ( converges to );
- an improvement that makes the policy greedy with respect to the value table, and the two meet at and .
Part 2 ended on the limit of this approach: even when the experience decides where to update, every update still needs the model to decide what the update is, which is rarely the case most cases.
What if we don’t have the model?
All the methods we have seen so far compute , which needs the model . This session removes that requirement.
The key idea fits in one line:
Replace the expectation over by an average over experience we draw.
See how we can estimate the model by using experiences only on the following example :
When applying this idea to our problems, we could estimate from a lot of interactions. But this would require a giantic amount of time to cross each pair multiple times. So instead of finding the dynamics and then solving the problem, we keep the steps from GPI, and each one slightly differ:
- Prediction, Part 3.1, this page: the input is a policy and episodes played with ; the output is . The expectation over becomes an average of samples.
- Control, Part 3.2: the input is episodes of interaction; the output is and , the optimal policy is obtained from it.
One key idea for both: as we need many episodes, the environment must be fast to evaluate, we trade prior knowledge against fast interactions.
We will study:
- Monte Carlo evaluation: the value of a state as the average of the returns that followed.
- Temporal-difference evaluation: update after every step, from the next estimate.
- Monte Carlo or TD? How these two give different answers with the same data.
The control problem, i.e. finding a good policy without the model, is the subject of Part 3.2, Learning to Act: Monte Carlo control, SARSA, and Q-learning.
1. Monte Carlo: learning from complete episodes
Monte Carlo methods aim at estimating a dynamics based on a set of observations drawn from a probability distribution.
1.1 An average of returns
Monte Carlo methods are not specific to reinforcement learning. Whenever an expectation can’t be computed analytically, one can draw random samples and average them.
Formally, with independent copies of a random variable ,
with probability one: this is the law of large numbers. The estimate is unbiased, , and its error shrinks like , where is the standard deviation of . It is used to price options, compute integrals in high dimension, or propagates uncertain inputs through finite-element models.
In reinforcement learning, the expectation we want is the value , and the samples are the returns.
The recipe is thus to play episodes with :
and, every time the agent is in , write down the return that followed, .
Monte Carlo policy evaluation estimates by the average of these returns: the empirical mean instead of the true expected return. No model is needed, only episodes.
But the episodes must end: is known only once the episode has terminated, so Monte Carlo works for episodic tasks only.
The average does not need to store the returns. After each new return from , it can be updated in place, as an average written step by step:
This incremental form is what the algorithms below use.
1.2 Evaluating at the first visit or every visit
A state can come back several times in the same episode. To estimate its value fo a given policy, First-visit MC keeps only the return after the first visit to in each episode; every-visit MC keeps them all. See on the example below :
Input: a policy to evaluate
- and for every state
- repeat for each episode
- generate an episode with :
- for , backward in time
- if does not appear in
Every-visit MC is the same algorithm without the if: switch the figure to every visit to see it run.
Running backward builds every return of the episode in a single pass (forward pass would require steps), since . The update with is the incremental form of section 1.1: the running average of the returns, computed without storing them.
For example, with , on an episode that visits twice, the two version give:
First-visit MC adds only the return to the average of . Every-visit MC adds and . Both converge to as the number of visits grows, but they don’t behave the same on the way: the next exercise shows how.
Exercise 1.2 First visit or every visit? Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
An MDP has a single nonterminal state and a single action. From , the agent comes back to with probability , and reaches the terminal state with probability . Every transition gives a reward of , and .
- You observe one episode that lasts steps, so its return is . What is the first-visit MC estimate of ? The every-visit estimate?
- What is the true value , as a function of ?
- A second episode lasts steps. Give both estimates again, after the two episodes.
- Now use the constant step size update , with first-visit returns, and at the start. What is after each of the two episodes? Which step size would give back the first-visit average of question 3?
- Which of the two estimators is unbiased? Why is the other one biased?
Hint
The state is visited at , and the return after the visit at time is the number of steps left, .
Hint
For question 2, write the Bellman equation of this one-state process: one reward of , then, with probability , the same value again.
Hint
For question 5, look at where the ten returns of the first episode come from: how many random draws produced them?
Checkpoint what you should get
After one episode: (first visit) and (every visit). After two: and . With : , then .
Solution
- The state is visited at , with returns . First visit: only counts, . Every visit: .
- From , the number of remaining steps follows a geometric distribution with parameter , and each step gives , so . The Bellman equation gives the same, .
- The second episode gives the return (first visit), or the returns and (every visit). First visit: . Every visit: .
- After episode 1: . After episode 2: . The step size , that is then , gives back the average: , then . A constant gives more weight to recent returns, which is useful only when the problem changes over time.
- First-visit is unbiased: each episode gives one return, an independent sample of given . Every-visit is biased for a finite number of episodes: the returns of one episode are correlated (here all come from the same draw), and long episodes contribute more terms. With , for instance, , but the every-visit estimate after one episode of length is , whose expectation is . It is still consistent: the bias vanishes as the number of episodes grows.
What to notice the take-away
The two estimators read the same data. First-visit throws away the correlated returns and stays unbiased; every-visit uses them all, and pays with a bias that only more episodes remove.
1.3 A constant step size
In the incremental form of section 1.1, comes from the definition of the mean, but replace it by a constant step size , and you can control how older returns are gradually forgotten, which is useful when the policy or the environment drifts:
Read it as: trust the new sample by a fraction of the change.
On the equation is called the target.
This form general form of the equation will come back in every algorithm of this page and of Part 3.2; only the target changes.
Monte Carlo prediction has three properties to keep in mind for what follows:
- Unbiased: is a true sample of .
- High variance: depends on every random event of the episode, every action and every transition until the end.
- Offline: nothing is learned before the episode is over.
An example: blackjack. Writing for every sequence of cards is tedious; simulating games is easy, which makes blackjack the classic Monte Carlo example. Evaluating the policy “stick on 20 or 21” over its 200 states, the value surface is still noisy after 10,000 games and smooth after 500,000: the high variance, in numbers.
What to look at Blackjack, evaluated by Monte Carlo: the value surfaces after 10,000 and 500,000 games
The policy sticks on 20 or 21 and hits otherwise; each game ends with a reward of , or , and is the average over the games where the state was visited, with the state being the player’s sum, the card the dealer shows, and whether the player holds a usable ace. Look at the left column (usable ace), where states are rare: after 10,000 games the surface is still jagged, after 500,000 it is smooth. The wall at 20 and 21 is where sticking wins most of the time.
Optional Monte Carlo as an observer: a control-engineering reading of the update Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
For an engineer, is a hidden constant, and each new return is a noisy measurement of it. The incremental update is then an observer, which corrects its estimate with each new measurement:
The dictionary: hidden state is , the estimate is , the measurement is the return , the innovation is , and the observer gain is the step size .
Since the hidden state is constant, the observer reduces to a first-order filter, , with a single pole at . With the gain it is the exact sample average, the Kalman filter of a constant. With a constant it is an exponential moving average: smooth but slow for a small , fast but noisy for a large one.
2. Temporal differences: learning from every step
The main drawback with Monte Carlo estimation is that one needs the fulln episode to compute the estimation. This section introduces Temporal Difference or TD that precisely aims at solving this issue with a technique called bootstrapping.
2.1 Bootstrapping
After each episode, Monte Carlo update pulls towards the return,
Its problem is that is known only at the end of the episode. But recall that the return is recursive between two consecutive timesteps, and its second part has a name:
Taking the expectation of the first equation, the value of a state is written with the value of the next one:
So after a single step, we can replace the unknown by our current estimate of its expectation, . Updating an estimate from another estimate is called bootstrapping, and it gives the so-called TD(0) update:
For a given state being the state we met at time , the TD target is where is pulled to: one measured reward, then the estimate of what follows.
The difference between the target and the current estimate is the TD error,
a measure of novelty: how much better () or worse () the step went than the estimate predicted. The “(0)” of TD(0) means one real reward before bootstrapping; -step TD and TD() look further ahead (section 3).
TD(0) takes the best of the two previous worlds. It samples, like Monte Carlo: no model is used but it uses samples from what the agent really experienced. And it bootstraps, like dynamic programming: its uses the current estimate in the target. Like DP, it updates after every transition, so it learns during the episode, and it does not even need the episode to end.
See how TD(0) can compute the value function on all states of a 3*3 grid example below :
Input: a policy to evaluate, a step size
- arbitrary for every state , with
- repeat for each episode
- initialize
- repeat until is terminal
- take the action given by in ; observe and
There is no strict criterion of stopping as this process could run forever. We draw a subsequent number of runs that we consider meaningful.
2.2 TD(0) on a random walk
The random walk is a chain of five states, to , between two exits. Every episode starts in ; the policy is a random move at each step, left or right; the reward is on the right exit and everywhere else, with . The value of a state is then the probability of leaving on the right: from to .
Start with for to , , and . Suppose the random policy takes right three times: .
#does it make sense to have the 3 3 grid and this? very similar examples?
Only moves. The first two steps held no surprise: the estimates said , and the next state also said . The reward is felt only at the last step, and it travels back one state per episode. Monte Carlo, on the same episode, would have pulled , and all at once towards the return, .
Exercise 2.2 TD(0) by hand Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
- An agent observes , with , , and . Compute the TD target, the TD error , and the new value of .
- Back to the random walk, after the episode of the figure above. The coin says right three times again: compute the three TD(0) updates of this second episode.
Hint
Target first, ; then the error, target minus ; then move by times the error.
Hint
In question 2, the estimates are those left by the first episode: , the others . Update in the order of the steps, each with the latest values.
Checkpoint what you should get
Question 1: target , error , new value . Question 2: , , .
Solution
- TD target: . TD error: . New value: .
- Step 1, : target , error , . Step 2, : target , error , . Step 3, : target , error , .
What to notice the take-away
In the second episode, moves because it now sees the new : the reward has traveled back one more state. will move only in the third episode. Monte Carlo would have moved all three states from the very first episode, but towards a target, , that is far from their true values, , and .
3. Monte Carlo and TD comparison
Let’s quickly review the practical differences these algorithms have in practice as they influence different family of RL solutions.
3.1 Estimating one the way : Driving home example
An everyday example makes the computing difference concrete. Each evening, leaving the office, you predict how long it will take to get home, and you revise the prediction on the way. The reward of each leg is the minutes it took; the value of a state is the predicted number of minutes still to go, with . The figure shows the elapsed time, the prediction of what remains, and their sum, the predicted total for both algorithms:
Monte Carlo waits until you are home. Then every prediction of the trip moves towards the actual total, minutes: you needed the whole episode to learn anything.
TD learns on the way: each prediction moves towards the next one. At the car, the “30 minutes” of the office already becomes “40”, because it rains, before you know how the trip ends.
3.2 Bias and variance
The two methods both correspond to different tradeoffs on various aspects :
| Monte Carlo | TD(0) | |
|---|---|---|
| update | ✗ at the end of the episode | ✓ after every step |
| bias | ✓ none | ✗ yes: it bootstraps on estimates |
| variance | ✗ high | ✓ low |
| continuing tasks | ✗ no | ✓ yes |
| sample efficiency | ✗ lower | ✓ usually higher |
| converges to | ✓ yes | ✓ yes |
Monte Carlo’s target, , is a true sample of , so it is unbiased; but it sums every random event until the end of the episode, so it is noisy. TD’s target, , contains a single random reward and a single random transition, so it varies much less; but is only an estimate, wrong at the beginning, so the target is biased.
In one sentence : Monte Carlo pays high variance to be unbiased; TD pays some bias for low variance, and learns online.
Watch it on random-walk example :
Early on, Monte Carlo’s average is closer to the truth, but each of its learners is far from it; TD’s learners agree with each other, on a value that is wrong at first. After a few dozen episodes, the low variance wins: TD’s error is lower, at every step size.
3.3 RL in one plot: width and depth
Dynamic Programming (DP), Monte Carlo and TD all update towards a target. They differ in how they build it, among two aspects:
- Width: does the target average over every possible action and next state, which needs the model, or does it use the transition that really happened?
- Depth: does it look one step ahead and then bootstrap on an estimate, or does it go to the end of the episode?
Dynamic programming is full width, one step deep: , no sampling noise but the model is required.
TD(0) is one sample, one step deep: online, low variance, biased.
Monte Carlo is one sample, full depth: it never bootstraps, it is unbiased, and it needs complete episodes.
The fourth corner, full width and full depth, is exhaustive search (which is of course not an appealing solution 😁).
The next exercise shows that the difference is not only about speed: on the same data, Monte Carlo and TD can give different answers, and it is worth knowing which one to trust.
Exercise 3.3 You are the predictor Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
You observe the following episodes of an unknown Markov reward process with two states, and (; each episode is written as state, reward, state, reward, …):
The first episode starts in , gets , moves to , gets and ends. The seven others start in and end right away.
- What is the best estimate of ? Justify.
- Batch Monte Carlo (the average of the observed returns): what is ?
- Batch TD(0) (TD(0) updates repeated over these episodes until stops changing): what is ?
- Draw the Markov process that best explains the data (the maximum-likelihood model). Which of the two answers for is the exact value of this model? Which one minimizes the squared error on the observed returns?
- Which answer would you trust more to predict the next episode that starts in ? Relate your answer to the bias and variance of Monte Carlo and TD.
Hint
Count: in how many of the episodes was visited, and how many times did it end with a reward of ?
Hint
At the fixed point of batch TD(0), the average TD error on every transition is zero. There is only one transition from .
Checkpoint what you should get
for both methods; for batch Monte Carlo, for batch TD(0).
Solution
- was seen times; the process ended with reward in of them and in . Both methods agree: .
- Batch Monte Carlo: the only return observed from is , so .
- Batch TD(0): the only transition from is with reward . At the fixed point its TD error is zero, , so .
- Maximum-likelihood model: from , go to with probability and reward ; from , terminate with reward (probability ) or (probability ). In this model, the value of is exactly : that is the batch TD answer, called the certainty-equivalence estimate. The batch Monte Carlo answer, , is the one that minimizes the squared error on the observed returns.
- The TD answer, . The Markov property says that what happens after does not depend on how was reached, so the observations of tell us about too. Monte Carlo uses only the single episode that started in : unbiased, but one sample is a very noisy estimate (high variance). TD reuses the estimate of by bootstrapping: biased if were wrong, but with much less variance.
What to notice the take-away
Monte Carlo fits the returns it saw; TD fits the Markov process that produced them. When the problem really is Markov, TD’s answer uses more of the data, which is one reason it often learns faster.
Optional Between TD(0) and Monte Carlo: n-step returns and TD(λ) Math needed Compute: arithmetic, a small linear system, applying a formula of the pageend of high school Reason: expectations, inequalities, an argument in words: no new tools, but a chain of reasoningfirst year of university, with a first course in probability Prove: induction, limits, norms, fixed points: a proof, which can be skipped on a first readingabout two years of university math The level says which math is needed, not how long it takes.
TD(0) and Monte Carlo are the two ends of a range. The -step return uses real rewards, then bootstraps:
With it is the TD(0) target; when reaches the end of the episode, it is the Monte Carlo return.
The -return averages all of them, with geometric weights that sum to :
and the update is TD(0) for and Monte Carlo for . Written this way (the forward view), it needs the episode to end, like Monte Carlo.
More in Sutton and Barto, chapters 7 and 12.
4. Quick wrap-up before 3.2
In a few lines:
- To predict without a model: replace the expectation over by an average over experience.
- Monte Carlo averages the returns: unbiased, high variance, needs the end of the episode.
- TD updates after every step, from the next estimate: biased, low variance, online.
- Both are the same update formula, an estimate moved by a step toward a target; only the target changes.
- These approaches are tractable only if the environment is fast to evaluate: learning takes many episodes, so on a simulator, not on the real system.
Part 3.2: Learning to Act uses these estimates to find a good policy, still without a model: exploration, Monte Carlo control, SARSA and Q-learning.