RLS RL, Read as Statistics

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 π\pi was defined as an expectation, vπ(s)=Eπ[Gt∣St=s]v_\pi(s) = \mathbb{E}_\pi[G_t \mid S_t = s], where the return Gt=∑k≥0γkRt+k+1G_t = \sum_{k\ge0}\gamma^k R_{t+k+1} 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 π\pi, how do we estimate vπ(s)v_\pi(s) 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 τ=(S0,A0,R1,S1,…,ST)\tau = (S_0, A_0, R_1, S_1, \dots, S_T) that ends in a terminal state at a random time TT; a visit to ss is a time tt with St=sS_t = s. Monte Carlo evaluation needs episodes, because it waits for the episode to end to see the whole return. Throughout, γ=1\gamma = 1 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 nn independent returns G(1),…,G(n)G^{(1)}, \dots, G^{(n)}, each distributed as Gt∣St=sG_t \mid S_t = s, then

v^n=Gˉn=1n∑i=1nG(i)\hat v_n = \bar G_n = \frac1n\sum_{i=1}^n G^{(i)}

has E[v^n]=vπ(s)\mathbb{E}[\hat v_n] = v_\pi(s) and Var⁡(v^n)=σs2/n\operatorname{Var}(\hat v_n) = \sigma_s^2/n, with σs2=Var⁡(Gt∣St=s)\sigma_s^2 = \operatorname{Var}(G_t \mid S_t = s). The law of large numbers gives consistency, and if σs2<∞\sigma_s^2 < \infty the CLT gives n(v^n−vπ(s))→N(0,σs2)\sqrt n(\hat v_n - v_\pi(s)) \to \mathcal{N}(0, \sigma_s^2). Nothing about the method needs the dynamics p(s′,r∣s,a)p(s', r \mid s, a): 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 ss, the return from the first visit only. Let τs\tau_s be the first time with St=sS_t = s. Episodes are generated independently, so the first-visit returns of different episodes are independent. And by the Markov property, conditional on reaching ss at time τs\tau_s, the future after τs\tau_s does not depend on how we got there, so

E[Gτs∣τs<∞]=vπ(s).\mathbb{E}[G_{\tau_s} \mid \tau_s < \infty] = v_\pi(s).

(The first-visit time is a stopping time: the event "first visit is at tt" depends only on the past, which is why conditioning on it does not distort the future.) Hence, conditional on the number nn of episodes that visit ss, the first-visit returns are iid draws with mean vπ(s)v_\pi(s), and everything in the previous section applies exactly. If every episode starts at ss (as in our experiment), nn 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 ss in every episode. It uses more data per episode, which seems like it should help. Let episode ii have NiN_i visits to ss with returns Gi1,…,GiNiG_{i1}, \dots, G_{iN_i}, and put Yi=∑jGijY_i = \sum_{j} G_{ij}. Then

v^nEV=∑i=1nYi∑i=1nNi.\hat v^{\text{EV}}_n = \frac{\sum_{i=1}^n Y_i}{\sum_{i=1}^n N_i}.

This is a ratio of two sample means of iid episode-level quantities, Yˉn/Nˉn\bar Y_n / \bar N_n, and a ratio estimator is biased in general, because E[Yˉ/Nˉ]≠E[Yˉ]/E[Nˉ]\mathbb{E}[\bar Y/\bar N] \ne \mathbb{E}[\bar Y]/\mathbb{E}[\bar N]. By the law of large numbers it converges to E[Y]/E[N]\mathbb{E}[Y]/\mathbb{E}[N], which equals vπ(s)v_\pi(s): by the Markov property each visit's return has conditional mean vπ(s)v_\pi(s), so E[Y]=∑kP(visit k occurs) vπ(s)=E[N] vπ(s)\mathbb{E}[Y] = \sum_k \mathbb{P}(\text{visit } k \text{ occurs})\,v_\pi(s) = \mathbb{E}[N]\,v_\pi(s). So the estimator is consistent. The delta method gives the size of the bias: for R=E[Y]/E[N]R = \mathbb{E}[Y]/\mathbb{E}[N],

E[v^nEV]−R  ≈  1n (EN)2(RVar⁡(N)−Cov⁡(Y,N)),\mathbb{E}\big[\hat v_n^{\text{EV}}\big] - R \;\approx\; \frac{1}{n\,(\mathbb{E}N)^2}\Big(R\operatorname{Var}(N) - \operatorname{Cov}(Y, N)\Big),

so the bias is of order 1/n1/n, which is small compared with the 1/n1/\sqrt n standard error, and is therefore not the main problem when nn 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, γ=1\gamma = 1. Each episode lists the states visited with the reward received after leaving that state.

EpisodeSteps (state, reward after)
1A, 2 → B, −1-1 → A, 3 → end
2A, 1 → end
3B, 0 → A, 4 → A, −2-2 → end

The return at each visit is the sum of the rewards from that step on.

  • Episode 1: the first visit to A has G=2−1+3=4G = 2 - 1 + 3 = 4; B has G=−1+3=2G = -1 + 3 = 2; the second visit to A has G=3G = 3.
  • Episode 2: A has G=1G = 1.
  • Episode 3: B has G=0+4−2=2G = 0 + 4 - 2 = 2; the first visit to A has G=4−2=2G = 4 - 2 = 2; the second visit to A has G=−2G = -2.

For state A:

v^FV(A)=4+1+23=73≈2.33,v^EV(A)=4+3+1+2+(−2)5=85=1.6.\hat v^{\text{FV}}(A) = \frac{4 + 1 + 2}{3} = \frac{7}{3} \approx 2.33, \qquad \hat v^{\text{EV}}(A) = \frac{4 + 3 + 1 + 2 + (-2)}{5} = \frac{8}{5} = 1.6.

First-visit uses 33 returns, one per episode. Every-visit uses 55, with episodes 1 and 3 each counting twice. For B, each episode visits it once, so both estimators equal (2+2)/2=2(2 + 2)/2 = 2. 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 11, and the episode ends after each step with probability 1/21/2. The length LL is geometric on {1,2,… }\{1, 2, \dots\} with E[L]=2\mathbb{E}[L] = 2, and v=E[L]=2v = \mathbb{E}[L] = 2. The return from the kk-th visit is L−k+1L - k + 1. First-visit uses G=LG = L and is unbiased: E[L]=2\mathbb{E}[L] = 2. With one episode, every-visit averages L,L−1,…,1L, L-1, \dots, 1, which is (L+1)/2(L+1)/2, so

E[v^1EV]=E[L]+12=1.5≠2.\mathbb{E}\big[\hat v^{\text{EV}}_1\big] = \frac{\mathbb{E}[L] + 1}{2} = 1.5 \ne 2.

It is biased by −0.5-0.5, a quarter of the value. With nn episodes it is ∑iLi(Li+1)/2 / ∑iLi\sum_i L_i(L_i+1)/2 \,/\, \sum_i L_i, and its limit is E[L(L+1)/2]/E[L]=(6+2)/(2⋅2)=2\mathbb{E}[L(L+1)/2]/\mathbb{E}[L] = (6 + 2)/(2 \cdot 2) = 2, using E[L2]=Var⁡(L)+22=2+4=6\mathbb{E}[L^2] = \operatorname{Var}(L) + 2^2 = 2 + 4 = 6. Consistent, as claimed.

How sure can we be? Confidence intervals

For first-visit with nn episodes, the sample standard deviation ss of the returns gives the usual interval

Gˉn±z0.975 sn.\bar G_n \pm z_{0.975}\,\frac{s}{\sqrt n}.

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 nn the normal quantile 1.961.96 is also too small: with ss estimated, the correct quantile for normal data is a tt quantile, 2.262.26 for n=10n = 10 and 12.712.7 for n=2n = 2.

For every-visit the interval needs more care. Treating all ∑iNi\sum_i N_i 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 v^=∑Yi/∑Ni\hat v = \sum Y_i / \sum N_i, define residuals ei=Yi−v^Nie_i = Y_i - \hat v N_i. Then

se⁡^(v^EV)  =  nn−1∑i=1nei2∑i=1nNi.\widehat{\operatorname{se}}(\hat v^{\text{EV}}) \;=\; \frac{\sqrt{\tfrac{n}{n-1}\sum_{i=1}^n e_i^2}}{\sum_{i=1}^n N_i}.

What is the incremental update, and what does a constant step size do?

Sample means can be computed without storing the data. With Vn=1n∑k≤nGkV_n = \frac1n\sum_{k\le n} G_k,

Vn=Vn−1+1n(Gn−Vn−1).V_n = V_{n-1} + \frac1n\big(G_n - V_{n-1}\big).

The update has the shape "estimate plus step size times error", where the error Gn−Vn−1G_n - V_{n-1} 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 1/n1/n makes each observation count equally.

Now use a constant α∈(0,1]\alpha \in (0,1]: Vn=Vn−1+α(Gn−Vn−1)V_n = V_{n-1} + \alpha(G_n - V_{n-1}). Unrolling,

Vn=(1−α)nV0+α∑k=1n(1−α)n−k Gk,V_n = (1-\alpha)^n V_0 + \alpha\sum_{k=1}^n (1-\alpha)^{n-k}\,G_k,

an exponentially weighted moving average (EWMA). The weights sum to one, and recent returns count more.

Suppose the returns are iid with mean μ\mu and variance σ2\sigma^2. Then:

  • Bias. E[Vn]−μ=(1−α)n(V0−μ)\mathbb{E}[V_n] - \mu = (1-\alpha)^n (V_0 - \mu). The initial guess decays geometrically in nn. With the sample-mean step sizes αk=1/k\alpha_k = 1/k, the first update has α1=1\alpha_1 = 1 and erases V0V_0 at once.
  • Variance. Var⁡(Vn)=σ2α2∑k=1n(1−α)2(n−k)=σ2 α2−α(1−(1−α)2n)\operatorname{Var}(V_n) = \sigma^2\alpha^2\sum_{k=1}^n(1-\alpha)^{2(n-k)} = \sigma^2\,\dfrac{\alpha}{2-\alpha}\big(1 - (1-\alpha)^{2n}\big), which tends to σ2α/(2−α)\sigma^2\alpha/(2-\alpha) and does not go to zero.

Compare with a sample mean of mm observations, with variance σ2/m\sigma^2/m. Setting σ2/m=σ2α/(2−α)\sigma^2/m = \sigma^2\alpha/(2-\alpha) gives the effective sample size

neff=2−αα.n_{\text{eff}} = \frac{2-\alpha}{\alpha}.

It is the same quantity as 1/∑kwk21/\sum_k w_k^2 for weights wkw_k that sum to one, familiar from weighted survey means. So α=0.1\alpha = 0.1 is worth 1919 observations and α=0.02\alpha = 0.02 is worth 9999. A constant step size is a fixed amount of averaging, and the estimator stops improving after about neffn_{\text{eff}} observations. Its mean squared error is bounded below by σ2α/(2−α)\sigma^2\alpha/(2-\alpha) however much data arrives.

Why accept that? Because the target may move. If the true mean drifts linearly, μk=μ0+ck\mu_k = \mu_0 + ck, then in steady state the EWMA lags the target:

E[Vn]−μn  →  − c 1−αα.\mathbb{E}[V_n] - \mu_n \;\to\; -\,c\,\frac{1-\alpha}{\alpha}.

A sample mean averages over the whole past and lags by cn/2cn/2, which grows forever. Choosing α\alpha is a bias–variance choice: a larger α\alpha 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 0,10, 1 and a terminal state. From state 00: stay at 00 with probability 0.60.6 (reward mean 11), go to 11 with probability 0.30.3 (reward mean 00), stop with probability 0.10.1 (reward mean 55). From state 11: go to 00 w.p. 0.50.5 (reward mean 22), stay w.p. 0.30.3 (reward mean 0.50.5), stop w.p. 0.20.2 (reward mean −1-1). Rewards have standard deviation 11 around those means. The true values come from solving the linear system v=rˉ+Pvv = \bar r + P v exactly, so we can measure bias.

Every episode starts at state 00, so first-visit returns are iid and every-visit counts about 5.45.4 visits per episode. We run 30003000 replications of each sample size nn (number of episodes), and compare first-visit, every-visit, and constant-α\alpha (updating on first-visit returns, starting at V0=0V_0 = 0).

Output
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.59

What 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 nn (the rows are nested, so they are correlated and a single moderate deviation is not alarming). The every-visit bias is −2.83-2.83 at n=1n=1, about 35%35\% of v(0)=8.12v(0) = 8.12, and shrinks like 1/n1/n: bias times nn is about −3.7-3.7, −4.5-4.5, −4.3-4.3, −4.6-4.6 for n=2,5,10,20n = 2, 5, 10, 20. By n=200n = 200 it is −0.021-0.021, inside its standard error. The toy in experiment 0 matches the hand calculation: 1.5001.500 at n=1n = 1.

Every-visit trades bias for variance, and the trade reverses. At n=1n = 1 and 22 every-visit has a much smaller standard deviation (4.774.77 against 7.567.56) because it averages about 5.45.4 returns per episode, and a smaller RMSE (5.555.55 against 7.567.56). Past n=5n = 5 first-visit wins on RMSE, and by n=200n = 200 its standard deviation is 0.5360.536 against 0.7080.708. 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 nn depends on the process, so treat the crossover point at n≈5n \approx 5 as a property of this example.

Interval coverage depends on treating episodes as the unit. The first-visit CLT interval undercovers for small nn (0.6810.681 at n=2n = 2, 0.8980.898 at n=10n = 10) and reaches nominal coverage (0.9500.950 at n=100n=100, 0.9470.947 at n=200n=200). The shortfall at small nn comes from using 1.961.96 where a tt 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 3737–48%48\% at any nn, and does not improve with nn: 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 0.9200.920 at n=200n = 200. The bias there is only −0.02-0.02 against a standard deviation of 0.710.71, 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 α\alpha behaves exactly as the EWMA algebra says. Started at V0=0V_0 = 0, the α=0.1\alpha = 0.1 bias at n=20n = 20 is −0.998-0.998, and (0.9)20×8.115=0.987(0.9)^{20} \times 8.115 = 0.987. At n=100n = 100 with α=0.02\alpha = 0.02 the bias is −1.056-1.056 against (0.98)100×8.115=1.076(0.98)^{100}\times 8.115 = 1.076. The standard deviation settles at the predicted floor σα/(2−α)\sigma\sqrt{\alpha/(2-\alpha)}: 7.660.1/1.9=1.7577.66\sqrt{0.1/1.9} = 1.757 against 1.7691.769 observed at n=200n = 200, and 7.660.02/1.98=0.7707.66\sqrt{0.02/1.98} = 0.770 against 0.7760.776. This is why α=0.1\alpha = 0.1 has an RMSE of 1.771.77 at n=200n = 200 while the sample mean's is 0.540.54: on a stationary target, a constant step size is permanently worse. Table 3a confirms neff=(2−α)/αn_{\text{eff}} = (2-\alpha)/\alpha: 19.019.0 predicted and 18.818.8 measured for α=0.1\alpha = 0.1.

The constant step size wins when the target moves. In experiment 3b the target jumps by 33 after episode 100100. Before the jump the sample mean is best (MSE 0.570.57 against 3.013.01 and 1.681.68). Ten episodes after the jump α=0.1\alpha = 0.1 has the lowest error (4.194.19 against 7.997.99 for the sample mean), and by episode 200200 the sample mean's error (2.552.55) is dominated by its own bias, 3×100/200=1.53 \times 100/200 = 1.5 squared, while α=0.02\alpha = 0.02 has recovered (0.760.76). By episode 300300 the sample mean is still lagging (1.191.19). Which α\alpha 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 G0G_0 here is 7.667.66 on a value of 8.18.1. Chapter 5 takes the update shape from this chapter, V←V+α(target−V)V \leftarrow V + \alpha(\text{target} - V), 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 α\alpha made here in a smaller form.

Exercises

  1. Pen and paper. Three episodes (γ=1\gamma = 1), listed as (state, reward after leaving it): Episode X: A,3 → A,−1-1 → B,2. Episode Y: B,1 → A,0. Episode Z: A,2. Compute the first-visit and every-visit estimates of v(A)v(A) and v(B)v(B).
  2. Pen and paper. In the one-state toy, show that with a single episode the every-visit estimate is (L+1)/2(L+1)/2 and compute its expectation using E[L]=2\mathbb{E}[L] = 2. What is the bias as a fraction of vv?
  3. Pen and paper. Derive Var⁡(Vn)\operatorname{Var}(V_n) for the constant-α\alpha update with iid returns. What α\alpha gives neff=50n_{\text{eff}} = 50?
  4. Change the code and predict. Change the first row of P to [0.9, 0.05, 0.05] so the state revisits itself more. Predict whether the every-visit bias at n=5n = 5 gets larger or smaller, and whether every-visit still beats first-visit on RMSE at n=1n=1. Then run it.
  5. Change the code and predict. Start the constant-α\alpha estimators at V0=v(0)V_0 = v(0) instead of 00. Predict the bias and RMSE columns for α=0.02\alpha = 0.02. Then replace 1.961.96 in the first-visit interval with 2.262.26 at n=10n = 10 and predict whether coverage reaches 0.950.95.

Sources