Simple Algorithm
Reinforcement Learning · Fixed Point · 26 min

Monte Carlo Estimation in Depth

First-visit and every-visit estimators: bias, variance and convergence.

Two Monte Carlo estimators read the same episodes and disagree. The unbiased one is not always the more accurate: in a one-state chain, the biased every-visit estimate has less than half the mean squared error of the first-visit estimate after one episode, and 1+p1 + p times more in the long run. This lesson computes such things exactly: the bias and variance of Monte Carlo estimators, how the variance of a return grows with the horizon, what a constant step size buys, and how to put honest error bars on a value.

What you’ll learn

  • Prove that first-visit Monte Carlo is unbiased and that every-visit Monte Carlo is a biased but consistent ratio estimator, and compute both mean squared errors exactly in a one-state chain.
  • Derive the variance of the return as an expected discounted sum of squared TD errors, the variance Bellman equation, and bound its growth with the horizon.
  • Analyze constant-α Monte Carlo as an exponentially weighted average, and derive the step size that best tracks a drifting value.
  • Build asymptotic and finite-sample confidence intervals for Monte Carlo estimates, and narrow them with control variates.

First-visit and every-visit as statistical estimators

Proof. The time of the first visit is a stopping time, so by the strong Markov property the trajectory after it is distributed as a fresh trajectory from ss, independent of how the episode got there; distinct episodes are independent. That gives (a). For (b), apply the same property at every visit: each Gi,jG_{i,j} has conditional mean Vπ(s)V^\pi(s) given that visit jj occurs, so E[Xi]=Vπ(s) E[Ki]\E[X_i] = V^\pi(s)\,\E[K_i]. The pairs (Xi,Ki)(X_i, K_i) are i.i.d. across episodes, and the strong law applied to numerator and denominator gives V^EV→E[X]/E[K]=Vπ(s)\hat V_{\mathrm{EV}} \to \E[X]/\E[K] = V^\pi(s). But V^EV\hat V_{\mathrm{EV}} is a ratio estimator, and the expectation of a ratio is not the ratio of expectations: returns from the same episode share their future, and episodes with many visits are weighted more heavily. ■\blacksquare

Singh and Sutton (1996) analyzed these estimators, for undiscounted absorbing Markov chains, as the batch limits of TD(1) with two kinds of eligibility trace: accumulating traces give every-visit MC, replacing traces first-visit MC. They showed that the every-visit method is biased, the first-visit method unbiased, and that the first-visit method has the lower mean squared error in the long run, with a close relation to the maximum-likelihood estimate. The smallest example already shows the whole story.

DerivationA one-state chain, exactly
  1. V(s)=E[K]=1q,Var⁡(K)=pq2V(s) = \E[K] = \frac1q,\qquad \Var(K) = \frac{p}{q^2}

    One nonterminal state ss. Each step pays reward 1; the chain stays in ss with probability pp and terminates with probability q=1−pq = 1 - p; γ=1\gamma = 1. An episode lasts K∼Geometric(q)K \sim \mathrm{Geometric}(q) steps on {1,2,… }\{1, 2, \dots\}, the returns after its visits are K,K−1,…,1K, K-1, \dots, 1, and

  2. MSEFV(n)=pq2 n\mathrm{MSE}_{\mathrm{FV}}(n) = \frac{p}{q^2\,n}

    First visit. V^FV=Kˉ\hat V_{\mathrm{FV}} = \bar K, the mean episode length, so its mean squared error is pure variance:

  3. bias=−p2q,MSEEV(1)=p24q2+p4q2=p(1+p)4q2  <  pq2=MSEFV(1)\text{bias} = -\frac{p}{2q},\qquad \mathrm{MSE}_{\mathrm{EV}}(1) = \frac{p^2}{4q^2} + \frac{p}{4q^2} = \frac{p(1+p)}{4q^2} \;<\; \frac{p}{q^2} = \mathrm{MSE}_{\mathrm{FV}}(1)

    Every visit, one episode. V^EV=K+(K−1)+⋯+1K=K+12\hat V_{\mathrm{EV}} = \frac{K + (K-1) + \cdots + 1}{K} = \frac{K+1}{2}. Its mean is 12q+12\frac{1}{2q} + \frac12, so it underestimates, and its variance is a quarter of Var⁡(K)\Var(K):

  4. n MSEEV(n)  ⟶  p(1+p)q2=(1+p)⋅n MSEFV(n)n\,\mathrm{MSE}_{\mathrm{EV}}(n) \;\longrightarrow\; \frac{p(1+p)}{q^2} = (1+p)\cdot n\,\mathrm{MSE}_{\mathrm{FV}}(n)

    Every visit, many episodes. With X=K(K+1)/2X = K(K+1)/2, the delta method for the ratio Xˉ/Kˉ\bar X/\bar K gives n MSE→Var⁡(X−VK)/E[K]2n\,\mathrm{MSE} \to \Var\big(X - V K\big)/\E[K]^2. Using the first four moments of the geometric distribution, this is 1+p1 + p times the first-visit constant:

Episodes nnMSEFV\mathrm{MSE}_{\mathrm{FV}}MSEEV\mathrm{MSE}_{\mathrm{EV}}
12.000.75
50.400.37
100.200.23
500.0400.056
n⋅MSEn \cdot \mathrm{MSE} as n→∞n \to \infty23
p=12p = \tfrac12, so V(s)=2V(s) = 2. First-visit values are exact; every-visit values for n≥5n \ge 5 come from simulating 200,000 datasets of nn episodes each. Every-visit is ahead for the first few episodes and behind from somewhere between 5 and 10 on.

Why does first-visit win in the end? Here Kˉ\bar K is the maximum-likelihood estimate of 1/q1/q: the likelihood of nn geometric lengths is maximized at q^=n/∑iKi\hat q = n/\sum_i K_i. It is also the certainty-equivalence value, the value of the chain whose staying probability is the observed fraction of steps that stayed. And it attains the Cramér–Rao bound p/(q2n)p/(q^2 n), so no unbiased estimator does better. Every-visit uses more returns per episode, which helps when episodes are few, but those returns are deterministic functions of the same KK and add nothing asymptotically except bias and extra weight on long episodes.

Predict before you look

In the one-state chain with p=0.8p = 0.8 (true value V=5V = 5), a single episode happens to last K=4K = 4 steps. What is the every-visit estimate?

Show the answer

2.5

The returns after the four visits are 4,3,2,14, 3, 2, 1, whose average is 2.52.5; the first-visit estimate is 44. On average over episodes, every-visit's single-episode estimate is (E[K]+1)/2=3(\E[K] + 1)/2 = 3, a bias of −p/(2q)=−2-p/(2q) = -2: later visits have shorter remaining returns and pull the average down.

How noisy is a return? A Bellman equation for variance

First-visit MC is unbiased, so its error is all variance, Var⁡(Gt∣St=s)/n\Var(G_t \mid S_t = s)/n. How large is the variance of a return, and how does it grow with the horizon? A one-line identity answers both: the Monte Carlo error is a discounted sum of TD errors.

DerivationThe return as a sum of surprises
  1. Gt−Vπ(St)=∑k=tT−1γk−t δkG_t - V^\pi(S_t) = \sum_{k=t}^{T-1}\gamma^{k-t}\,\delta_k

    Let δk=Rk+1+γVπ(Sk+1)−Vπ(Sk)\delta_k = R_{k+1} + \gamma V^\pi(S_{k+1}) - V^\pi(S_k) be the TD error computed with the true values, with Vπ=0V^\pi = 0 at termination. Summing γk−tδk\gamma^{k-t}\delta_k, every intermediate value cancels:

  2. E[δk δj]=E[δk E[δj∣Fj]]=0\E[\delta_k\,\delta_j] = \E\big[\delta_k\,\E[\delta_j \mid \mathcal F_j]\big] = 0

    The Bellman equation says E[Rk+1+γVπ(Sk+1)∣Sk]=Vπ(Sk)\E[R_{k+1} + \gamma V^\pi(S_{k+1}) \mid S_k] = V^\pi(S_k), so each δk\delta_k has conditional mean zero given the history Fk\mathcal F_k up to SkS_k. The δk\delta_k are martingale differences, hence uncorrelated: for j>kj > k, δk\delta_k is known at time jj, and

  3. Var⁡(Gt∣St=s)=E[∑k≥tγ2(k−t) δk2  ∣  St=s]\Var\big(G_t \mid S_t = s\big) = \E\Big[\sum_{k \ge t}\gamma^{2(k-t)}\,\delta_k^2 \;\Big|\; S_t = s\Big]

    Square the sum: the cross terms vanish, and the variance of the return is the expected discounted sum of squared surprises, discounted by γ2\gamma^2:

  4. σ2(s)=E[δt2∣St=s]+γ2 E[σ2(St+1)∣St=s]\sigma^2(s) = \E\big[\delta_t^2 \mid S_t = s\big] + \gamma^2\,\E\big[\sigma^2(S_{t+1}) \mid S_t = s\big]

    Split off the first term and use the Markov property: σ2(s)=Var⁡(Gt∣St=s)\sigma^2(s) = \Var(G_t \mid S_t = s) satisfies its own Bellman equation, with "reward" E[δt2∣St=s]\E[\delta_t^2 \mid S_t = s] and discount γ2\gamma^2 (Sobel, 1982):

Two regimes follow. If transitions are deterministic and only the rewards are noisy, with variance σr2\sigma_r^2 per step, every surprise is a reward fluctuation and σ2=σr2/(1−γ2)\sigma^2 = \sigma_r^2/(1-\gamma^2): the standard deviation grows like the square root of the horizon. At γ=0.95\gamma = 0.95 and σr=1\sigma_r = 1 it is 1/1−0.9025≈3.21/\sqrt{1 - 0.9025} \approx 3.2, and a 95% interval of ±0.1\pm 0.1 needs about (1.96×3.2/0.1)2≈3,900(1.96 \times 3.2/0.1)^2 \approx 3{,}900 episodes. If instead one early random transition decides between futures whose values differ by order Rmax⁡/(1−γ)R_{\max}/(1-\gamma), a single surprise is that large and the standard deviation grows linearly in the horizon. Monte Carlo's cost is set by these surprises, and TD learning, whose target contains only one of them, is designed to avoid paying for all of them at once.

Check your understanding

Why does the variance Bellman equation discount by γ2\gamma^2 rather than γ\gamma?

  1. Because variances of later steps are less reliable
  2. Because the return from the next state enters GtG_t multiplied by γ\gamma, and scaling a random variable by γ\gamma scales its variance by γ2\gamma^2
  3. Because the TD errors are squared, which squares every term of the return
  4. It is a convention; γ\gamma would work equally well
Show the answer

B. Because the return from the next state enters GtG_t multiplied by γ\gamma, and scaling a random variable by γ\gamma scales its variance by γ2\gamma^2

Gt=Rt+1+γGt+1G_t = R_{t+1} + \gamma G_{t+1}, and Var⁡(γX)=γ2Var⁡(X)\Var(\gamma X) = \gamma^2\Var(X). The surprises are uncorrelated, so their variances add with weights γ2k\gamma^{2k}.

Constant step sizes: forgetting and tracking

Constant-α\alpha Monte Carlo, Vn=Vn−1+α(Gn−Vn−1)V_n = V_{n-1} + \alpha(G_n - V_{n-1}), unrolls into an exponentially weighted average:

Vn=(1−α)nV0+∑i=1nα(1−α)n−i Gi.V_n = (1-\alpha)^n V_0 + \sum_{i=1}^n \alpha(1-\alpha)^{n-i}\,G_i.

Its weights have effective sample size (∑iwi)2/∑iwi2→(2−α)/α(\sum_i w_i)^2/\sum_i w_i^2 \to (2-\alpha)/\alpha, so it behaves like an average of the last 2/α2/\alpha or so returns. On a stationary problem with independent returns of variance σ2\sigma^2, the bias decays like (1−α)n(1-\alpha)^n and the variance settles at α2σ2/(1−(1−α)2)=ασ2/(2−α)\alpha^2\sigma^2/(1-(1-\alpha)^2) = \alpha\sigma^2/(2-\alpha): the estimate never converges, it hovers. Why accept that? Because in control the target moves.

DerivationThe best constant step for a drifting value
  1. fn+1=(1−α) fn+α ξn−ηn+1f_{n+1} = (1-\alpha)\,f_n + \alpha\,\xi_n - \eta_{n+1}

    Model the drift as a random walk observed through noisy returns: in round nn the value is Vn⋆=Vn−1⋆+ηnV^\star_n = V^\star_{n-1} + \eta_n with Var⁡(ηn)=τ2\Var(\eta_n) = \tau^2, and the agent sees Gn=Vn⋆+ξnG_n = V^\star_n + \xi_n with Var⁡(ξn)=σ2\Var(\xi_n) = \sigma^2, everything independent. Let fn=Vn−1−Vn⋆f_n = V_{n-1} - V^\star_n be the error of the current estimate as a prediction of this round's value. Substituting the update:

  2. E[f2]=α2σ2+τ21−(1−α)2=α2σ2+τ2α(2−α)\E\big[f^2\big] = \frac{\alpha^2\sigma^2 + \tau^2}{1-(1-\alpha)^2} = \frac{\alpha^2\sigma^2 + \tau^2}{\alpha(2-\alpha)}

    The three terms are independent, so in steady state Ef2=(1−α)2Ef2+α2σ2+τ2\E f^2 = (1-\alpha)^2\E f^2 + \alpha^2\sigma^2 + \tau^2:

  3. α⋆2+r α⋆−r=0⟹α⋆=r2+4r−r2  ≈  τσ(τ≪σ)\alpha^{\star2} + r\,\alpha^\star - r = 0\quad\Longrightarrow\quad \alpha^\star = \frac{\sqrt{r^2 + 4r} - r}{2} \;\approx\; \frac{\tau}{\sigma}\quad(\tau \ll \sigma)

    A small α\alpha lags behind the drift (the τ2/α\tau^2/\alpha term); a large one passes the noise through (the ασ2\alpha\sigma^2 term). Setting the derivative to zero gives a quadratic in α\alpha, with r=τ2/σ2r = \tau^2/\sigma^2:

  4. This α⋆\alpha^\star is exactly the steady-state gain of the Kalman filter for a random walk observed in white noise, so in this model no linear estimator tracks better. The running mean, α=1/n\alpha = 1/n, is the worst choice here: its effective memory keeps growing, so its lag behind the drifting value grows without bound.

Predict before you look

Returns have noise σ=1\sigma = 1 and the value they estimate drifts by τ=0.05\tau = 0.05 per episode. What constant step size minimizes the steady-state squared error?

Show the answer

0.049

r=τ2/σ2=0.0025r = \tau^2/\sigma^2 = 0.0025, so α⋆=(0.00252+0.01−0.0025)/2≈0.0488\alpha^\star = (\sqrt{0.0025^2 + 0.01} - 0.0025)/2 \approx 0.0488, close to τ/σ=0.05\tau/\sigma = 0.05. Its mean squared error is about 0.0510.051, against 0.1180.118 at α=0.2\alpha = 0.2 (too noisy) and 0.1310.131 at α=0.01\alpha = 0.01 (too slow).

In generalized policy iteration the drift is real: every policy change shifts the returns that a state's estimate averages, so constant steps are the norm in practice. The price is that convergence statements then hold only in a weak sense (a noise ball, or convergence with decaying steps), and the interplay between how fast the policy changes and how fast the values average is exactly what makes the convergence of Monte Carlo control delicate (Monte Carlo Control & Its Convergence).

Error bars, sample sizes and control variates

With nn independent first-visit returns, the central limit theorem gives the asymptotic confidence interval V^±1.96 σ^/n\hat V \pm 1.96\,\hat\sigma/\sqrt n. For guarantees at finite nn, use a concentration inequality. If returns lie in an interval of length LL (L=Rmax⁡/(1−γ)L = R_{\max}/(1-\gamma) for rewards in [0,Rmax⁡][0, R_{\max}]), Hoeffding's inequality gives Pr⁡(∣V^−V∣≥ε)≤2e−2nε2/L2\Pr(\abs{\hat V - V} \ge \varepsilon) \le 2e^{-2n\varepsilon^2/L^2}, and Bernstein's inequality, which uses the variance σ2\sigma^2, gives 2e−nε2/(2σ2+2Lε/3)2e^{-n\varepsilon^2/(2\sigma^2 + 2L\varepsilon/3)}. The episodes needed for accuracy ε\varepsilon with probability 1−δ1-\delta:

nHoeffding≥L2ln⁡(2/δ)2ε2,nBernstein≥(2σ2+23Lε)ln⁡(2/δ)ε2n_{\text{Hoeffding}} \ge \frac{L^2\ln(2/\delta)}{2\varepsilon^2},\qquad n_{\text{Bernstein}} \ge \frac{\big(2\sigma^2 + \tfrac23 L\varepsilon\big)\ln(2/\delta)}{\varepsilon^2}
Rewards in [0,1][0, 1] and γ=0.9\gamma = 0.9 give L=10L = 10. For ε=0.1\varepsilon = 0.1 and δ=0.05\delta = 0.05, Hoeffding asks for about 18,40018{,}400 episodes. If the return's standard deviation is σ=1\sigma = 1, Bernstein asks for about 980980: when returns spread over a small part of their possible range, variance-aware bounds are far tighter. Empirical Bernstein bounds use the sample variance instead of σ2\sigma^2, at a small cost.

Any sum of terms with conditional mean zero is a valid control variate for a return. If the expected rewards r(s,a)r(s,a) are known, Z=∑kγk(Rt+k+1−r(St+k,At+k))Z = \sum_k \gamma^k\big(R_{t+k+1} - r(S_{t+k}, A_{t+k})\big) has mean zero, and Gt−Z=∑kγkr(St+k,At+k)G_t - Z = \sum_k \gamma^k r(S_{t+k}, A_{t+k}) keeps the mean while discarding all reward noise. With a model and an approximate value function V^\hat V, take the centered surprises Z=∑k≥tγk−t(δ^k−E[δ^k∣Sk])Z = \sum_{k \ge t}\gamma^{k-t}\big(\hat\delta_k - \E[\hat\delta_k \mid S_k]\big), where δ^k\hat\delta_k is the TD error computed with V^\hat V; telescoping as before,

Gt−Z=V^(St)+∑k≥tγk−t(TπV^−V^)(Sk).G_t - Z = \hat V(S_t) + \sum_{k \ge t}\gamma^{k-t}\big(\mathcal T^\pi\hat V - \hat V\big)(S_k).

With V^=Vπ\hat V = V^\pi the sum vanishes and the estimate is Vπ(St)V^\pi(S_t) with zero variance: what remains is governed by the Bellman residual of V^\hat V. A model-free learner cannot compute TπV^\mathcal T^\pi\hat V, which is why policy-gradient methods use the one control variate they can always center, a state-dependent baseline (Baselines & Variance Reduction), and why off-policy evaluation combines models with importance weights in doubly robust estimators.

Key takeaways

  • First-visit MC averages i.i.d. returns (strong Markov property), so it is unbiased with variance σ2/n\sigma^2/n; every-visit MC is a ratio estimator, consistent but biased.
  • In a one-state chain, every-visit has MSE p(1+p)/(4q2)p(1+p)/(4q^2) against p/q2p/q^2 after one episode, but 1+p1 + p times first-visit's asymptotically; first-visit is there the maximum-likelihood estimate and attains the Cramér–Rao bound.
  • Gt−Vπ(St)=∑kγkδkG_t - V^\pi(S_t) = \sum_k\gamma^k\delta_k with uncorrelated true TD errors, so Var⁡(Gt∣s)\Var(G_t \mid s) is the expected γ2\gamma^2-discounted sum of squared surprises and obeys a Bellman equation; it grows like the horizon or its square.
  • Constant-α\alpha MC is an exponentially weighted average with a noise floor ασ2/(2−α)\alpha\sigma^2/(2-\alpha); for a value drifting by τ\tau per round, the best constant step is about τ/σ\tau/\sigma, the Kalman gain.
  • Variance-aware (Bernstein) intervals can need far fewer episodes than range-based (Hoeffding) ones; control variates remove noise in proportion to their correlation with it, perfectly for a control variate built from VπV^\pi.

Check yourself

In the interactive lesson these are scored with your confidence, and what you miss comes back for review.

Question 1

Why are the first-visit returns from different episodes independent and identically distributed?

  1. Because every episode starts in ss
  2. Because the first visit is a stopping time, so by the strong Markov property the future after it is a fresh trajectory from ss, independent of the past and of other episodes
  3. Because rewards are bounded
  4. Because first-visit MC uses a step size of 1/N1/N
Show the answer

B. Because the first visit is a stopping time, so by the strong Markov property the future after it is a fresh trajectory from ss, independent of the past and of other episodes

Whatever happened before the first visit, the process restarts at ss at that random time, so each first-visit return has the law of the return from ss. Episodes need not start in ss, and boundedness only matters for finite variance.

Question 2

In the one-state chain with p=12p = \tfrac12, which estimator has the lower mean squared error after one episode, and which after 50 episodes?

  1. First-visit after one episode; every-visit after 50
  2. First-visit in both cases, because it is unbiased
  3. Every-visit after one episode; first-visit after 50
  4. Every-visit in both cases, because it uses more returns
Show the answer

C. Every-visit after one episode; first-visit after 50

After one episode every-visit's MSE is p(1+p)/(4q2)=0.75p(1+p)/(4q^2) = 0.75 against first-visit's 22: its bias is small compared with the variance it removes. Asymptotically every-visit's MSE is (1+p)=1.5(1+p) = 1.5 times first-visit's; at n=50n = 50 they are about 0.0560.056 and 0.0400.040.

Question 3

Constant-α\alpha Monte Carlo runs on a problem whose values never change, with independent returns of variance σ2\sigma^2. What happens to its mean squared error as n→∞n \to \infty?

  1. It tends to 0, like the running mean's
  2. It grows without bound
  3. It settles at about ασ2/(2−α)\alpha\sigma^2/(2-\alpha)
  4. It settles at σ2\sigma^2, as if only one return were used
Show the answer

C. It settles at about ασ2/(2−α)\alpha\sigma^2/(2-\alpha)

The bias decays like (1−α)n(1-\alpha)^n, but each new return keeps moving the estimate by α\alpha times its noise, so the variance settles at α2σ2/(1−(1−α)2)=ασ2/(2−α)\alpha^2\sigma^2/(1-(1-\alpha)^2) = \alpha\sigma^2/(2-\alpha), roughly the variance of an average of 2/α2/\alpha returns. The same property lets it track a value that drifts.

Question 4

A return GtG_t is corrected by subtracting ∑kγkδk\sum_k \gamma^k\delta_k, where the δk\delta_k are TD errors computed with the exact VπV^\pi. What is the variance of the corrected estimate, and what is the catch?

  1. Zero, because the corrected estimate equals Vπ(St)V^\pi(S_t); the catch is that computing the correction requires VπV^\pi, the very thing being estimated
  2. Unchanged, because subtracting a zero-mean term cannot reduce variance
  3. Zero, and there is no catch: this is how TD(0) works
  4. Doubled, because two noisy quantities are combined
Show the answer

A. Zero, because the corrected estimate equals Vπ(St)V^\pi(S_t); the catch is that computing the correction requires VπV^\pi, the very thing being estimated

By telescoping, Gt−∑kγkδk=Vπ(St)G_t - \sum_k\gamma^k\delta_k = V^\pi(S_t), a constant given StS_t. The ideal control variate removes all the noise but needs the answer. With an approximate V^\hat V and a model, the leftover variance is governed by the Bellman residual of V^\hat V, which is how practical control variates and doubly robust estimators trade modeling effort for variance.

Further reading

  • S. P. Singh & R. S. Sutton, "Reinforcement learning with replacing eligibility traces," Machine Learning 22, 123–158 (1996).
  • M. J. Sobel, "The variance of discounted Markov decision processes," Journal of Applied Probability 19 (1982).
  • M. G. Azar, R. Munos & H. J. Kappen, "Minimax PAC bounds on the sample complexity of reinforcement learning with a generative model," Machine Learning 91, 325–349 (2013).
  • R. S. Sutton & A. G. Barto, Reinforcement Learning: An Introduction, ch. 5 (MIT Press, 2nd ed., 2018).