Chapter 04 · Part 2: Learning values
Monte Carlo evaluation is a sample mean
Estimating a state's value from episodes is a sample-mean problem, and the details that matter are which returns count as the sample, how sure the interval is, and what a constant step size does.
In chapter 1 the value of a state under a policy was defined as an expectation, , where the return is a random variable. Chapter 3 was about choosing actions under uncertainty. This chapter fixes the policy and asks only for estimation: given trajectories generated by , how do we estimate and say how wrong we might be?
The answer starts with the oldest estimator there is, the sample mean. The RL-specific part is deciding what "a sample" is, because one trajectory can pass through the same state many times. We use the notation of the notation page. An episode is a trajectory that ends in a terminal state at a random time ; a visit to is a time with . Monte Carlo evaluation needs episodes, because it waits for the episode to end to see the whole return. Throughout, unless stated (an episodic task makes this safe if episodes end with probability one and returns have finite variance).
What does the sample mean estimate?
If we had independent returns , each distributed as , then
has and , with . The law of large numbers gives consistency, and if the CLT gives . Nothing about the method needs the dynamics : the environment is a black box that produces returns. That is both the appeal of Monte Carlo (no model, no bootstrapping) and its cost (a return carries the noise of every reward and transition until the end of the episode).
The question is how to get independent returns from trajectories.
First-visit: one return per episode
The first-visit estimator uses, from each episode that visits , the return from the first visit only. Let be the first time with . Episodes are generated independently, so the first-visit returns of different episodes are independent. And by the Markov property, conditional on reaching at time , the future after does not depend on how we got there, so
(The first-visit time is a stopping time: the event "first visit is at " depends only on the past, which is why conditioning on it does not distort the future.) Hence, conditional on the number of episodes that visit , the first-visit returns are iid draws with mean , and everything in the previous section applies exactly. If every episode starts at (as in our experiment), is just the number of episodes.
Every-visit: all the returns, with a cost
The every-visit estimator averages the return from every visit to in every episode. It uses more data per episode, which seems like it should help. Let episode have visits to with returns , and put . Then
This is a ratio of two sample means of iid episode-level quantities, , and a ratio estimator is biased in general, because . By the law of large numbers it converges to , which equals : by the Markov property each visit's return has conditional mean , so . So the estimator is consistent. The delta method gives the size of the bias: for ,
so the bias is of order , which is small compared with the standard error, and is therefore not the main problem when is large. The main problem is that the returns within an episode are strongly dependent: the return from a visit includes the rewards that make up the return from every later visit.
Singh and Sutton (1996) analysed exactly this contrast, in the setting of offline TD(1) on undiscounted absorbing Markov chains. In their abstract, the conventional (accumulating-trace) method converges to the every-visit estimate and the replacing-trace method converges to the first-visit estimate. They report that the first is biased, the second unbiased, and that the second has lower mean squared error in the long run. Sutton and Barto (2018) introduce both estimators in chapter 5.
A worked example by hand
Three episodes, . Each episode lists the states visited with the reward received after leaving that state.
| Episode | Steps (state, reward after) |
|---|---|
| 1 | A, 2 → B, → A, 3 → end |
| 2 | A, 1 → end |
| 3 | B, 0 → A, 4 → A, → end |
The return at each visit is the sum of the rewards from that step on.
- Episode 1: the first visit to A has ; B has ; the second visit to A has .
- Episode 2: A has .
- Episode 3: B has ; the first visit to A has ; the second visit to A has .
For state A:
First-visit uses returns, one per episode. Every-visit uses , with episodes 1 and 3 each counting twice. For B, each episode visits it once, so both estimators equal . The two estimators differ only when a state is revisited within an episode.
A case where the bias is a one-line calculation
One state, each step pays , and the episode ends after each step with probability . The length is geometric on with , and . The return from the -th visit is . First-visit uses and is unbiased: . With one episode, every-visit averages , which is , so
It is biased by , a quarter of the value. With episodes it is , and its limit is , using . Consistent, as claimed.
How sure can we be? Confidence intervals
For first-visit with episodes, the sample standard deviation of the returns gives the usual interval
This rests on the CLT, so it needs finite variance and enough episodes that the sample mean is close to normal. Returns are often skewed (long episodes pay much more or much less), so "enough" can be a lot. For small the normal quantile is also too small: with estimated, the correct quantile for normal data is a quantile, for and for .
For every-visit the interval needs more care. Treating all visit-returns as independent draws gives a standard error that is far too small, because visits in the same episode are dependent. The correct unit is the episode. Linearise the ratio: with , define residuals . Then
What is the incremental update, and what does a constant step size do?
Sample means can be computed without storing the data. With ,
The update has the shape "estimate plus step size times error", where the error is the surprise. In chapter 5 the same shape appears with a different target, and the conditions on the step sizes (Robbins–Monro) are discussed there. The step size makes each observation count equally.
Now use a constant : . Unrolling,
an exponentially weighted moving average (EWMA). The weights sum to one, and recent returns count more.
Suppose the returns are iid with mean and variance . Then:
- Bias. . The initial guess decays geometrically in . With the sample-mean step sizes , the first update has and erases at once.
- Variance. , which tends to and does not go to zero.
Compare with a sample mean of observations, with variance . Setting gives the effective sample size
It is the same quantity as for weights that sum to one, familiar from weighted survey means. So is worth observations and is worth . A constant step size is a fixed amount of averaging, and the estimator stops improving after about observations. Its mean squared error is bounded below by however much data arrives.
Why accept that? Because the target may move. If the true mean drifts linearly, , then in steady state the EWMA lags the target:
A sample mean averages over the whole past and lags by , which grows forever. Choosing is a bias–variance choice: a larger means a shorter memory, less lag and more variance. In RL the target moves for two reasons: the environment may be non-stationary, and, as chapter 5 will show, when the value of one state is learned from estimates of other states, the target changes as those estimates improve.
Experiment: bias, variance, coverage
The code in ch04_monte_carlo.py uses a small episodic Markov reward process (a policy has already been folded into the transition probabilities) with two non-terminal states and a terminal state. From state : stay at with probability (reward mean ), go to with probability (reward mean ), stop with probability (reward mean ). From state : go to w.p. (reward mean ), stay w.p. (reward mean ), stop w.p. (reward mean ). Rewards have standard deviation around those means. The true values come from solving the linear system exactly, so we can measure bias.
Every episode starts at state , so first-visit returns are iid and every-visit counts about visits per episode. We run replications of each sample size (number of episodes), and compare first-visit, every-visit, and constant- (updating on first-visit returns, starting at ).
Experiment 0: one-state toy, v = 2 (episode length L ~ Geometric(1/2))
n first-visit mean every-visit mean
1 2.001 1.500
2 2.001 1.667
5 2.003 1.835
20 1.999 1.951
100 2.000 1.990
MRP: P = [[0.6, 0.3, 0.1], [0.5, 0.3, 0.2]] mean rewards = [[1.0, 0.0, 5.0], [2.0, 0.5, -1.0]], reward sd = 1, gamma = 1
Exact values from solving (I - P) v = rbar: v(0) = 8.1154, v(1) = 7.1538
sd of one first-visit return G_0 = 7.660; mean visits to state 0 per episode = 5.388
Experiment 1: estimators of v(0) = 8.1154, 3000 replications per n (alpha methods start at V = 0)
Bias, mean(estimate) - v(0) (Monte Carlo se in parentheses)
n first-visit every-visit alpha=0.1 alpha=0.02
1 +0.027 (0.138) -2.831 (0.087) -7.301 (0.014) -7.953 (0.003)
2 +0.071 (0.099) -1.866 (0.079) -6.560 (0.019) -7.791 (0.004)
5 +0.090 (0.064) -0.898 (0.065) -4.752 (0.026) -7.327 (0.006)
10 +0.099 (0.045) -0.429 (0.052) -2.769 (0.030) -6.613 (0.008)
20 +0.027 (0.031) -0.231 (0.039) -0.998 (0.031) -5.411 (0.010)
50 +0.041 (0.020) -0.057 (0.026) -0.040 (0.032) -2.932 (0.013)
100 +0.033 (0.014) -0.025 (0.018) +0.012 (0.031) -1.056 (0.014)
200 +0.009 (0.010) -0.021 (0.013) -0.011 (0.032) -0.152 (0.014)
Standard deviation of the estimate
n first-visit every-visit alpha=0.1 alpha=0.02
1 7.560 4.773 0.756 0.151
2 5.438 4.304 1.036 0.215
5 3.483 3.569 1.444 0.335
10 2.473 2.870 1.663 0.452
20 1.693 2.153 1.705 0.564
50 1.085 1.408 1.761 0.720
100 0.756 0.996 1.721 0.747
200 0.536 0.708 1.769 0.776
RMSE = sqrt(bias^2 + variance)
n first-visit every-visit alpha=0.1 alpha=0.02
1 7.559 5.549 7.340 7.954
2 5.437 4.691 6.641 7.794
5 3.483 3.679 4.966 7.335
10 2.475 2.901 3.230 6.628
20 1.693 2.165 1.975 5.441
50 1.085 1.409 1.761 3.019
100 0.756 0.996 1.721 1.293
200 0.536 0.708 1.769 0.791
Experiment 2: coverage of nominal 95% intervals (z = 1.96), 3000 replications per n
n first-visit CLT every-visit iid every-visit cluster
2 0.681 0.366 0.475
5 0.847 0.407 0.664
10 0.898 0.431 0.754
20 0.926 0.450 0.811
50 0.940 0.472 0.878
100 0.950 0.470 0.907
200 0.947 0.476 0.920
(Monte Carlo se of a coverage figure near 0.95 is about 0.004)
Experiment 3a: effective sample size of constant alpha, started at V = v(0), n = 200
alpha (2-a)/a sigma^2/Var(V)
0.20 9.0 8.9
0.10 19.0 18.8
0.05 39.0 38.3
0.02 99.0 97.4
Experiment 3b: tracking a target that jumps by +3 after episode 100
returns ~ N(mu_k, sigma^2) with sigma = sd of G_0 above; mean squared error of each estimate
episode sample mean alpha=0.1 alpha=0.02
50 1.14 3.16 8.87
100 0.57 3.01 1.68
110 7.99 4.19 7.39
130 5.79 3.12 3.63
200 2.55 3.09 0.76
300 1.19 3.04 0.59What the numbers show
First-visit is unbiased; every-visit is not. The first-visit bias column is within about two Monte Carlo standard errors of zero at every (the rows are nested, so they are correlated and a single moderate deviation is not alarming). The every-visit bias is at , about of , and shrinks like : bias times is about , , , for . By it is , inside its standard error. The toy in experiment 0 matches the hand calculation: at .
Every-visit trades bias for variance, and the trade reverses. At and every-visit has a much smaller standard deviation ( against ) because it averages about returns per episode, and a smaller RMSE ( against ). Past first-visit wins on RMSE, and by its standard deviation is against . The more-data-per-episode advantage is limited: the extra returns are strongly correlated with the first, so they carry less information than their number suggests. This is the same ordering Singh and Sutton report for the long run. Whether every-visit wins at small depends on the process, so treat the crossover point at as a property of this example.
Interval coverage depends on treating episodes as the unit. The first-visit CLT interval undercovers for small ( at , at ) and reaches nominal coverage ( at , at ). The shortfall at small comes from using where a quantile is needed and from skewed returns; the code does not separate the two causes. The every-visit interval that treats visits as independent covers only – at any , and does not improve with : its standard error is too small by a factor of roughly the square root of the number of visits per episode, so more data only makes the wrong interval more confidently wrong. The cluster-robust interval repairs most of this but is still at at . The bias there is only against a standard deviation of , so most of the remaining gap is not the bias; the cluster standard error is itself an estimated quantity based on a ratio, and its sampling error and skewness shrink more slowly than first-visit's. The code does not test that explanation.
Constant behaves exactly as the EWMA algebra says. Started at , the bias at is , and . At with the bias is against . The standard deviation settles at the predicted floor : against observed at , and against . This is why has an RMSE of at while the sample mean's is : on a stationary target, a constant step size is permanently worse. Table 3a confirms : predicted and measured for .
The constant step size wins when the target moves. In experiment 3b the target jumps by after episode . Before the jump the sample mean is best (MSE against and ). Ten episodes after the jump has the lowest error ( against for the sample mean), and by episode the sample mean's error () is dominated by its own bias, squared, while has recovered (). By episode the sample mean is still lagging (). Which is best depends on how often and how far the target moves, and no value is best for both stationary and moving targets.
Where this leaves us
Monte Carlo evaluation is unbiased and needs no model, but each estimate waits for a full episode and carries the noise of every reward in it. The standard deviation of here is on a value of . Chapter 5 takes the update shape from this chapter, , and replaces the full return with a target that is available after one step. That introduces bias and cuts variance, which is the same trade that every-visit and constant made here in a smaller form.
Exercises
- Pen and paper. Three episodes (), listed as (state, reward after leaving it): Episode X: A,3 → A, → B,2. Episode Y: B,1 → A,0. Episode Z: A,2. Compute the first-visit and every-visit estimates of and .
- Pen and paper. In the one-state toy, show that with a single episode the every-visit estimate is and compute its expectation using . What is the bias as a fraction of ?
- Pen and paper. Derive for the constant- update with iid returns. What gives ?
- Change the code and predict. Change the first row of
Pto[0.9, 0.05, 0.05]so the state revisits itself more. Predict whether the every-visit bias at gets larger or smaller, and whether every-visit still beats first-visit on RMSE at . Then run it. - Change the code and predict. Start the constant- estimators at instead of . Predict the bias and RMSE columns for . Then replace in the first-visit interval with at and predict whether coverage reaches .
Sources
- Sutton, R. S. and Barto, A. G. (2018). Reinforcement Learning: An Introduction, 2nd edition. MIT Press. Chapter 5 (Monte Carlo methods).
- Singh, S. P. and Sutton, R. S. (1996). Reinforcement learning with replacing eligibility traces. Machine Learning 22, 123–158. DOI 10.1007/BF00114726.